package com.neusoft.common.encrypt;
import java.security.MessageDigest;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
/**
* 加密方式工具类 (JDK1.6以上)
*/
public class EncryptUtils {
/**
* 使用指定的加密算法加密字符串<br>
* @param text 待加密的字符串
* @param encName 加密方法,为null时默认为SHA-256,可以为SHA-1,MD5,SHA-256,SHA-384,SHA-512
* @return
*/
public static byte[] degestString(String text, String encName) {
MessageDigest md = null;
byte[] bt = text.getBytes();
try {
if (null == encName) {
encName = "SHA-256";
}
md = MessageDigest.getInstance(encName);
md.update(bt);
return md.digest();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
/**
* BASE64加密
* @param origin 待机解密的byte数组
* @return
*/
public static byte[] encryptBASE64(byte[] origin) {
if (origin == null) {
return null;
}
return Base64.encodeBase64(origin);
}
/**
* BASE64解密,采用Apache的commons-codec包中方法,不建议使用sun自己的
* @param dest 待解密的字节数组
* @return
*/
public static byte[] decryptBASE64(byte[] dest) {
if (dest == null) {
return null;
}
return Base64.decodeBase64(dest);
}
/**
* 使用Apache的codec加密,使用MD5算法<br>
* 注意:返回的字符串为小写,请比较时注意
* @param text 待加密的字符串
* @return
*/
public static String getMd5UseApacheCodec(String text) {
if (null == text) {
return null;
}
return DigestUtils.md5Hex(text);
}
/**
* 使用Apache的codec加密,使用SHA算法<br>
* 注意:返回值为小写字符,请比较时注意
* @param text 待加密的字符串
* @param algorithm 加密算法 SHA-1,SHA-256,SHA-384,SHA-512
* @return
*/
public static String getShaUseApacheCodec(String text, String algorithm) {
if (text == null) {
return null;
}
if (null == algorithm) {
return DigestUtils.shaHex(text);
} else {
if ("SHA-1".equals(algorithm)) {
return DigestUtils.shaHex(text);
} else if ("SHA-256".equals(algorithm)) {
return DigestUtils.sha256Hex(text);
} else if ("SHA-384".equals(algorithm)) {
return DigestUtils.sha384Hex(text);
} else if ("SHA-512".equals(algorithm)) {
return DigestUtils.sha512Hex(text);
} else {
return null;
}
}
}
}
转载于:https://my.oschina.net/hongchq/blog/70348