加密工具,base64加密、sha256加密、MD5加密
程序员文章站
2024-03-19 13:23:04
...
import sun.misc.BASE64Encoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
*
* 加密工具
*
* @author jy
* @version [版本号, 2018-7-22]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class EncryptUtil
{
/**
* base64加密
*
* @param bt 被sha256加密过后的byte
* @return
* @see [类、类#方法、类#成员]
*/
public static String base64(byte[] bt){
String s = null;
if (null != bt) {
s = new BASE64Encoder().encode(bt);
}
return s;
}
/**
* sha256加密
*
* @param param 加密的参数
* @return
* @throws NoSuchAlgorithmException
* @see [类、类#方法、类#成员]
*/
public static byte[] SHA256(String param)
throws NoSuchAlgorithmException{
byte[] bt = param.getBytes();
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(bt);
return md.digest();
}
/**
* md5加密
*
* @param param 加密的参数
* @return
* @throws NoSuchAlgorithmException
* @see [类、类#方法、类#成员]
*/
public final static String GetMD5Code(StringBuffer data) {//StringBuffer类型
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(data.toString().getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if(i<0) i+= 256;
if(i<16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
return buf.toString().toUpperCase();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
return null;
}
}
public final static String GetMD5Code(String data) {//String类型,统一utf-8
try {
byte[] btInput = data.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(btInput);
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if(i<0) i+= 256;
if(i<16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
return buf.toString().toUpperCase();
} catch (Exception e) {
// TODO Auto-generated catch block
return null;
}
}
public final static String GetMD5_16Code(String data) {//String类型,只取部分数据
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(data.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if(i<0) i+= 256;
if(i<16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
return buf.toString().toUpperCase().substring(8,24);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
}
总结:具体出处均来自网上。
上一篇: 数字签名--ECDSA实现
下一篇: RSA 数字签名算法(Java版)