实际上,在这个jar包里已经封装好了相关的加密解密算法,我们只需要调用相关方法即可实现目的,当然为了方便在项目中频繁使用,我们可以将相关的方法统一封装在一个方法类中


一 导入jar包

  在Javaweb项目中,将commons-codec-1.10.jar放入 WEB-INF/lib 中,在纯Java项目里,可以在项目上鼠标右键,选择Build Path-->Configure Build Path ,在这里进行配置:

在Java中利用Apache Commons Codec API实现常见的加密解密算法,如:md5,sha256


二 新建EncryptionUtil.java方法类


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.io.UnsupportedEncodingException;
 
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
 
public class EncryptionUtil {
    /**
     * Base64 encode
     * */
    public static String base64Encode(String data){
        return Base64.encodeBase64String(data.getBytes());
    }
     
    /**
     * Base64 decode
     * @throws UnsupportedEncodingException 
     * */
    public static String base64Decode(String data) throws UnsupportedEncodingException{
        return new String(Base64.decodeBase64(data.getBytes()),"utf-8");
    }
     
    /**
     * md5
     * */
    public static String md5Hex(String data){
        return DigestUtils.md5Hex(data);
    }
     
    /**
     * sha1
     * */
    public static String sha1Hex(String data){
        return DigestUtils.sha1Hex(data);
    }
     
    /**
     * sha256
     * */
    public static String sha256Hex(String data){
        return DigestUtils.sha256Hex(data);
    }
     
}