加密算法 -- SHA-256
作者:互联网
java的 SHA-256加密,几乎与 MD5加密的写法一样:
import java.security.MessageDigest;
import java.util.Arrays;
public class Hello {
public static void main(String[] args) {
String name = "哈喽啊";
try {
MessageDigest instance = MessageDigest.getInstance("SHA-256");
// md5的加盐
instance.update("xxx".getBytes());
// md5加密的字节数组
byte[] nameBytes = instance.digest(name.getBytes());
System.out.println(Arrays.toString(nameBytes));// 打印结果:[-16, 34, -105, -18, -53, -91, 98, 48, -40, 115, 11, 25, 22, 7, -108, 5, 24, 51, -38, 36, 17, 94, -3, -102, -6, -76, -61, -77, -29, 4, 107, 84]
String res = new String(nameBytes);
System.out.println(res);
//创建一个可变字符串 sb
StringBuilder sb = new StringBuilder();
for (int i=0;i<nameBytes.length;i++){
int val = nameBytes[i] & 255; //将负数转换成整数
if (val < 16) {
sb.append("0");
}
// 将val转换成16进制,再添加到sb这个可变的字符串中
sb.append(Integer.toHexString(val));
}
//再将可变的字符串sb ,转换成不可变的字符串
String hexData = sb.toString();
System.out.println(hexData); // 打印结果:f02297eecba56230d8730b19160794051833da24115efd9afab4c3b3e3046b54
}catch (Exception e){
System.out.println(e);
}
}
}
标签:java,String,instance,--,SHA,nameBytes,256,加密算法 来源: https://www.cnblogs.com/zhiqianggege/p/16211985.html