Java 字符串SHA1加密
导入类
import java.security.MessageDigest;
定义函数
private String toUserPwd(final String password) {
try {
if (password == null) {
return null;
}
final MessageDigest messageDigest = MessageDigest.getInstance("SHA");
final byte[] digests = messageDigest.digest(password.getBytes());
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < digests.length; i++) {
int halfbyte = (digests[i] >>> 4) & 0x0F;
for (int j = 0; j <= 1; j++) {
stringBuilder.append(
((0 <= halfbyte) && (halfbyte <= 9))
? (char) ('0' + halfbyte)
: (char) ('a' + (halfbyte - 10)));
halfbyte = digests[i] & 0x0F;
}
}
return stringBuilder.toString();
} catch (final Throwable throwable) {
this.log.error("error converting password", throwable);
return null;
}
}
javaSHA1实现加密解密
封装一个方法用于加密
public static String sha1(String data) throws NoSuchAlgorithmException {
//加盐 更安全一些
data += "lyz";
//信息摘要器 算法名称
MessageDigest md = MessageDigest.getInstance("SHA1");
//把字符串转为字节数组
byte[] b = data.getBytes();
//使用指定的字节来更新我们的摘要
md.update(b);
//获取密文 (完成摘要计算)
byte[] b2 = md.digest();
//获取计算的长度
int len = b2.length;
//16进制字符串
String str = "0123456789abcdef";
//把字符串转为字符串数组
char[] ch = str.toCharArray();
//创建一个40位长度的字节数组
char[] chs = new char[len*2];
//循环20次
for(int i=0,k=0;i<len;i++) {
byte b3 = b2[i];//获取摘要计算后的字节数组中的每个字节
// >>>:无符号右移
// &:按位与
//0xf:0-15的数字
chs[k++] = ch[b3 >>> 4 & 0xf];
chs[k++] = ch[b3 & 0xf];
}
//字符数组转为字符串
return new String(chs);
}
主函数测试
public static void main(String[] args) throws NoSuchAlgorithmException {
String data = "跳梁小豆tlxd666";
String result = sha1(data);
System.out.println("加密后:"+result);
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。