Java?實現(xiàn)字符串SHA1加密方法
更新時間:2021年11月20日 16:14:40 作者:RYANRUN潤
這篇文章主要介紹了Java?實現(xiàn)字符串SHA1加密方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
Java 字符串SHA1加密
導(dǎo)入類
import java.security.MessageDigest;
定義函數(shù)
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實現(xiàn)加密解密
封裝一個方法用于加密
/**
* sha1加密
* @param data
* @return
* @throws NoSuchAlgorithmException
*/
public static String sha1(String data) throws NoSuchAlgorithmException {
//加鹽 更安全一些
data += "lyz";
//信息摘要器 算法名稱
MessageDigest md = MessageDigest.getInstance("SHA1");
//把字符串轉(zhuǎn)為字節(jié)數(shù)組
byte[] b = data.getBytes();
//使用指定的字節(jié)來更新我們的摘要
md.update(b);
//獲取密文 (完成摘要計算)
byte[] b2 = md.digest();
//獲取計算的長度
int len = b2.length;
//16進制字符串
String str = "0123456789abcdef";
//把字符串轉(zhuǎn)為字符串數(shù)組
char[] ch = str.toCharArray();
//創(chuàng)建一個40位長度的字節(jié)數(shù)組
char[] chs = new char[len*2];
//循環(huán)20次
for(int i=0,k=0;i<len;i++) {
byte b3 = b2[i];//獲取摘要計算后的字節(jié)數(shù)組中的每個字節(jié)
// >>>:無符號右移
// &:按位與
//0xf:0-15的數(shù)字
chs[k++] = ch[b3 >>> 4 & 0xf];
chs[k++] = ch[b3 & 0xf];
}
//字符數(shù)組轉(zhuǎn)為字符串
return new String(chs);
}
主函數(shù)測試
public static void main(String[] args) throws NoSuchAlgorithmException {
String data = "跳梁小豆tlxd666";
String result = sha1(data);
System.out.println("加密后:"+result);
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaWeb實現(xiàn)mysql數(shù)據(jù)庫數(shù)據(jù)的添加和刪除
這篇文章主要介紹了如何利用JavaWeb實現(xiàn)mysql數(shù)據(jù)庫數(shù)據(jù)的添加和刪除功能,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2022-03-03
java 使用JDBC構(gòu)建簡單的數(shù)據(jù)訪問層實例詳解
以下是如何使用JDBC構(gòu)建一個數(shù)據(jù)訪問層,包括數(shù)據(jù)轉(zhuǎn)換(將從數(shù)據(jù)庫中查詢的數(shù)據(jù)封裝到對應(yīng)的對象中……),數(shù)據(jù)庫的建立,以及如何連接到數(shù)據(jù)庫,需要的朋友可以參考下2016-11-11
spring boot項目打包成war在tomcat運行的全步驟
這篇文章主要給大家介紹了關(guān)于spring boot項目打包成war在tomcat運行的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用spring boot具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-04-04
Eclipse連接Mysql數(shù)據(jù)庫操作總結(jié)
這篇文章主要介紹了Eclipse連接Mysql數(shù)據(jù)庫操作總結(jié)的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08

