u=1413084622,3353334159&fm=21&gp=0

Simple Java encryption algorithms include:

  1. BASE64, strictly speaking, is an encoding format, not an encryption algorithm
  2. MD5 (Message Digest Algorithm 5, information digest algorithm)
  3. SHA (Secure Hash Algorithm, secure hash algorithm)
  4. HMAC (Hash Message Authentication Code, hash message authentication code)

1. BASE64

Base64 is one of the most common encoding methods used on the network for transmitting 8-bit byte code. You can refer to RFC2045~RFC2049, which contain the detailed specifications of MIME. Base64 encoding can be used to pass longer identification information in the HTTP environment. For example, in the Java Persistence system Hibernate, Base64 is used to encode a longer unique identifier (usually a 128-bit UUID) into a string, used as a parameter in HTTP forms and HTTP GET URLs. In other applications, it is also often necessary to encode binary data into a form suitable for placement in URLs (including hidden form fields). In this case, Base64 encoding is unreadable, meaning the encoded data cannot be directly seen by the naked eye. (Source: Baidu Baike)

Java implementation code:

package com.cn.单向加密;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/*
BASE64的加密解密是双向的,可以求反解.
BASE64Encoder和BASE64Decoder是非官方JDK实现类。虽然可以在JDK里能找到并使用,但是在API里查不到。
JRE 中 sun 和 com.sun 开头包的类都是未被文档化的,他们属于 java, javax 类库的基础,其中的实现大多数与底层平台有关,
一般来说是不推荐使用的。 
BASE64 严格地说,属于编码格式,而非加密算法 
主要就是BASE64Encoder、BASE64Decoder两个类,我们只需要知道使用对应的方法即可。
另,BASE加密后产生的字节位数是8的倍数,如果不够位数以=符号填充。 
BASE64 
按照RFC2045的定义,Base64被定义为:Base64内容传送编码被设计用来把任意序列的8位字节描述为一种不易被人直接识别的形式。
(The Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable.) 
常见于邮件、http加密,截取http信息,你就会发现登录操作的用户名、密码字段通过BASE64加密的。
*/

public class BASE64 {
    /**  
     * BASE64解密  
     *   
     * @param key  
     * @return  
     * @throws Exception  
     */  
    public static byte[] decryptBASE64(String key) throws Exception {   
        return (new BASE64Decoder()).decodeBuffer(key);   
    }   

    /**  
     * BASE64加密  
     *   
     * @param key  
     * @return  
     * @throws Exception  
     */  
    public static String encryptBASE64(byte[] key) throws Exception {   
        return (new BASE64Encoder()).encodeBuffer(key);   
    }  

    public static void main(String[] args) {

     String  str="12345678";

        try {
        String  result1= BASE64.encryptBASE64(str.getBytes());
         System.out.println("result1=====加密数据=========="+result1);

         byte  result2[]= BASE64.decryptBASE64(result1);
         String  str2=new String(result2);
         System.out.println("str2========解密数据========"+str2);
    } catch (Exception e) {
        e.printStackTrace();
    }

    }

}

2. MD5

MD5That is Message-Digest Algorithm 5 (information-digest algorithm 5), used to ensure complete and consistent information transmission. It is one of the widely used hash algorithms in computers (also translated as digest algorithm, hash algorithm), and mainstream programming languages generally already have MD5 implementations. Computing data (such as Chinese characters) into another fixed-length value is the basic principle of hash algorithms. MD5's predecessors include MD2, MD3and MD4. It is widely used in encryption and decryption technology, often for file verification. Verification? No matter how large the file is, a unique MD5 value can be generated after MD5 hashing. For example, current ISO verification is all MD5 verification. How is it used? Of course, the ISO is processed with MD5 to produce an MD5 value. Friends who download Linux ISO files have usually seen an MD5 string next to the download link. It is used to verify whether the file is consistent.

Java implementation code:

package com.cn.单向加密;

import java.math.BigInteger;
import java.security.MessageDigest;
/*
MD5(Message Digest algorithm 5,信息摘要算法) 
通常我们不直接使用上述MD5加密。通常将MD5产生的字节数组交给BASE64再加密一把,得到相应的字符串
Digest:汇编
*/
public class MD5 {
    public static final String KEY_MD5 = "MD5";   

    public static  String  getResult(String inputStr)
    {
        System.out.println("=======加密前的数据:"+inputStr);
        BigInteger bigInteger=null;

        try {
         MessageDigest md = MessageDigest.getInstance(KEY_MD5);   
         byte[] inputData = inputStr.getBytes(); 
         md.update(inputData);   
         bigInteger = new BigInteger(md.digest());   
        } catch (Exception e) {e.printStackTrace();}
        System.out.println("MD5加密后:" + bigInteger.toString(16));   
        return bigInteger.toString(16);
    }

    public static void main(String args[])
    {
        try {
             String inputStr = "简单加密8888888888888888888";   
             getResult(inputStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

The MD5 algorithm has the following characteristics:

1. Compressibility: For data of any length, the length of the calculated MD5 value is fixed.
2. Easy to compute: It is easy to calculate the MD5 value from the original data.
3. Resistance to modification: Any change to the original data, even modifying only 1 byte, will result in a greatly different MD5 value.
4. Weak collision resistance: Given the original data and its MD5 value, it is very difficult to find a data (i.e., forged data) with the same MD5 value.
5. Strong collision resistance: It is very difficult to find two different data that have the same MD5 value.
The function of MD5 is to "compress" large-volume information into a secret format before signing a private key with digital signature software (that is, transforming a byte string of arbitrary length into a hexadecimal digit string of fixed length). Besides MD5, other well-known ones include sha-1, RIPEMD, and Haval, etc.

3.SHA

The Secure Hash Algorithm (SHA) is mainly applicable to the digital signature algorithm (Digital Signature Algorithm, DSA) defined in the Digital Signature Standard (DSS). For messages less than 2^64 bits in length, SHA1 produces a 160-bit message digest. After years of development and improvement by encryption experts, this algorithm has become increasingly perfect and is widely used. The idea of the algorithm is to receive a piece of plaintext and then convert it into a piece of (usually smaller) ciphertext in an irreversible way. It can also be simply understood as the process of taking a string of input codes (called pre-mapping or information) and converting them into a shorter, fixed-bit output sequence, i.e., a hash value (also called information digest or message authentication code). The hash function value can be said to be a "fingerprint" or "digest" of the plaintext, so a digital signature on the hash value can be regarded as a digital signature on this plaintext.

Java implementation code:

package com.cn.单向加密;

import java.math.BigInteger;
import java.security.MessageDigest;

/*
SHA(Secure Hash Algorithm,安全散列算法),数字签名等密码学应用中重要的工具,
被广泛地应用于电子商务等信息安全领域。虽然,SHA与MD5通过碰撞法都被破解了, 
但是SHA仍然是公认的安全加密算法,较之MD5更为安全*/
public class SHA {
     public static final String KEY_SHA = "SHA";   

    public static  String  getResult(String inputStr)
    {
        BigInteger sha =null;
        System.out.println("=======加密前的数据:"+inputStr);
        byte[] inputData = inputStr.getBytes();   
        try {
             MessageDigest messageDigest = MessageDigest.getInstance(KEY_SHA);  
             messageDigest.update(inputData);
             sha = new BigInteger(messageDigest.digest());   
             System.out.println("SHA加密后:" + sha.toString(32));   
        } catch (Exception e) {e.printStackTrace();}
        return sha.toString(32);
    }

    public static void main(String args[])
    {
        try {
             String inputStr = "简单加密";   
             getResult(inputStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Comparison between SHA-1 and MD5

Because both are derived from MD4, SHA-1 and MD5 are very similar to each other. Correspondingly, their strength and other characteristics are also similar, but there are the following differences:
l Security against brute force attacks: The most significant and important difference is that the SHA-1 digest is 32 bits longer than the MD5 digest. Using brute force techniques, the difficulty of producing any message whose digest equals a given message digest is on the order of 2^128 operations for MD5, and on the order of 2^160 operations for SHA-1. Thus, SHA-1 has greater strength against brute force attacks.
l Security against cryptanalysis: Due to the design of MD5, it is vulnerable to cryptanalytic attacks; SHA-1 appears to be less susceptible to such attacks.
l Speed: On the same hardware, SHA-1 runs slower than MD5.

4.HMAC

HMAC (Hash Message Authentication Code, hash message authentication code) is an authentication protocol based on a keyed Hash algorithm. The principle of message authentication code implementation is to use a public function and a key to generate a fixed-length value as an authentication identifier, and use this identifier to authenticate the integrity of the message. A key is used to generate a small fixed-size data block, namely MAC, which is added to the message and then transmitted. The receiver uses the key shared with the sender for identification and authentication, etc.

Java implementation code:

package com.cn.单向加密;
/*
HMAC 
HMAC(Hash Message Authentication Code,散列消息鉴别码,基于密钥的Hash算法的认证协议。
消息鉴别码实现鉴别的原理是,用公开函数和密钥产生一个固定长度的值作为认证标识,用这个标识鉴别消息的完整性。
使用一个密钥生成一个固定大小的小数据块,
即MAC,并将其加入到消息中,然后传输。接收方利用与发送方共享的密钥进行鉴别认证等。*/
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.cn.comm.Tools;

/**  
 * 基础加密组件  
 */  
public abstract class HMAC {   
    public static final String KEY_MAC = "HmacMD5";   

    /**  
     * 初始化HMAC密钥  
     *   
     * @return  
     * @throws Exception  
     */  
    public static String initMacKey() throws Exception {   
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);   
        SecretKey secretKey = keyGenerator.generateKey();   
        return BASE64.encryptBASE64(secretKey.getEncoded());   
    }   

    /**  
     * HMAC加密  :主要方法
     *   
     * @param data  
     * @param key  
     * @return  
     * @throws Exception  
     */  
    public static String encryptHMAC(byte[] data, String key) throws Exception {   

        SecretKey secretKey = new SecretKeySpec(BASE64.decryptBASE64(key), KEY_MAC);   
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());   
        mac.init(secretKey);   
        return new String(mac.doFinal(data));   

    }   

    public static  String  getResult1(String inputStr)
    {
        String path=Tools.getClassPath();
        String fileSource=path+"/file/HMAC_key.txt";
        System.out.println("=======加密前的数据:"+inputStr);
        String  result=null;
        try {
            byte[] inputData = inputStr.getBytes(); 
            String key = HMAC.initMacKey(); /*产生密钥*/  
            System.out.println("Mac密钥:===" + key);  
            /*将密钥写文件*/
            Tools.WriteMyFile(fileSource,key);
            result= HMAC.encryptHMAC(inputData, key);
            System.out.println("HMAC加密后:===" + result); 
        } catch (Exception e) {e.printStackTrace();}  
       return result.toString();
    }

    public static  String  getResult2(String inputStr)
    {
        System.out.println("=======加密前的数据:"+inputStr);
         String path=Tools.getClassPath();
         String fileSource=path+"/file/HMAC_key.txt";
         String key=null;;
        try {
             /*将密钥从文件中读取*/
             key=Tools.ReadMyFile(fileSource);
             System.out.println("getResult2密钥:===" + key);  
        } catch (Exception e1) {
            e1.printStackTrace();}
        String  result=null;
        try {
            byte[] inputData = inputStr.getBytes();  
            /*对数据进行加密*/
            result= HMAC.encryptHMAC(inputData, key);
            System.out.println("HMAC加密后:===" + result); 
        } catch (Exception e) {e.printStackTrace();}  
       return result.toString();
    }

    public static void main(String args[])
    {
        try {
             String inputStr = "简单加密"; 
             /*使用同一密钥:对数据进行加密:查看两次加密的结果是否一样*/
             getResult1(inputStr); 
             getResult2(inputStr);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Source: http://www.cnblogs.com/oumyye/p/4593592.html