MessageDigest类可用加密算法及使用
MessageDigest类可用加密算法及使用
- 在线手册javaAPI 在线手册(Ctrl +F 搜索 messageDigest即可)
使用方法很简单,直接上代码(java自带类,无需导包)
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class test {
//加密算法
private static final String MD5 = "MD5";
public static void main(String[] args) throws Exception{
//需要加密的数据
String str = "12346";
byte[] bs = encode(str,MD5);
//将byte转换成16进制输出
for(byte b : bs){
System.out.printf("%02x",b); //%02x表示以16进制格式化输出,02表示不足2位在左边补0
}
}
/**
* @param data 需要加密的数据
* @param str 加密算法
* @return 加密后的值
* @throws NoSuchAlgorithmException
*/
public static byte[] encode(String data, String str) throws NoSuchAlgorithmException{
MessageDigest md = MessageDigest.getInstance(str);
return md.digest(data.getBytes());
}
}
- MessageDigest可使用的加密方法有MD2\MD5\SHA-1\SHA-256\SHA-384\SHA-512
- MessageDigest加密后返回的是字节数组,再转化成16进制即可
##byte转16进制的其中三种方法
public static String byteToHexString(byte b){
return String.format("%02x", b);
}
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public static String byteToHexString(byte b){
return hexDigits[b >> 4 & 0xf] + hexDigits[b & 0xf];
}
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
##测试数据及其他地址