使用org.apache.commons.codec做md5&SHA1&BASE64加密

来源:互联网 发布:mac 数据库建模软件 编辑:程序博客网 时间:2024/05/12 17:51

版权声明:本文为博主原创文章,未经博主允许不得转载。

导入的Jar包名称如下:
*import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;*

1.MD5加密

DigestUtils.md5Hex可以实现MD5的不可逆加密,参考下面的代码。

    /*     * 不可逆算法 MD5     */    public static String MD5(String codecStr) {        String md5Str = DigestUtils.md5Hex(codecStr);        return md5Str;    }

2.SHA加密

DigestUtils.shaHex,sha256Hex等方法可实现SHA类型的不可逆加密,参考下面的代码。

    /*     * 不可逆算法 SHA1&SHA2     */    public static String SHA(String shaType,String codecStr) {        String strSha = "";        if (shaType.equals("shaHex")) {            // 不推荐使用            strSha = DigestUtils.shaHex(codecStr);         }        if (shaType.equals("sha256Hex")) {            strSha = DigestUtils.sha256Hex(codecStr);        }        if (shaType.equals("sha384Hex")) {            strSha = DigestUtils.sha384Hex(codecStr);        }        if (shaType.equals("sha512Hex")) {            strSha = DigestUtils.sha512Hex(codecStr);        }        return strSha;    }

3.BASE64加密和解密

binary.Base64的方法可以实行可逆的加密和解密,参考下面的代码。

    /*     * 可逆算法 BASE64     */    public static String Base64(String type,String codecStr) {        String strBase64 = "";        if (type.equals("encode")) {            // 加密            byte[] b1 = Base64.encodeBase64(codecStr.getBytes(), true);            strBase64 = b1.toString();        }        if (type.equals("decode")) {            // 解密            byte[] b2 = Base64.decodeBase64(codecStr);            strBase64 = b2.toString();        }        return strBase64;    }
0 0
原创粉丝点击