MD5加密和解密使用

public class MD5Utils {
    private static Logger logger = LoggerFactory.getLogger(MD5Utils.class);

    public static byte[] eccrypt(String info) throws NoSuchAlgorithmException {
        logger.debug("加密密码"+info);
        //获取MD5的MessageDigest对象
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] srcBytes = info.getBytes();
        md5.update(srcBytes);
        byte[] resultBytes = md5.digest();
        return resultBytes;
    }

    public static String getMD5(String password){
        try{
            byte[] resultBytes = eccrypt(password);
            String pd=ParseSystemUtil.parseByte2HexStr(resultBytes);
            logger.debug("加密完成");
            return pd;
        }catch (Exception e){
            logger.debug("MD5加密异常");
        }
        return "";
    }
}

转换格式
public class ParseSystemUtil {
/**将二进制转换成16进制
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = ‘0’ + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}

/**将16进制转换为二进制
 * @param hexStr
 * @return
 */
public static byte[] parseHexStr2Byte(String hexStr) {
    if (hexStr.length() < 1)
        return null;
    byte[] result = new byte[hexStr.length()/2];
    for (int i = 0;i< hexStr.length()/2; i++) {
        int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
        int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
        result[i] = (byte) (high * 16 + low);
    }
    return result;
}

}

两个Uitls 结合使用

你可能感兴趣的:(工具类)