??最近要與微信API做對(duì)接,用到了SHA1加密算法去生成簽名辜荠,在此做個(gè)記錄汽抚。
??安全哈希算法(Secure Hash Algorithm)主要適用于數(shù)字簽名標(biāo)準(zhǔn) (Digital Signature Standard DSS)里面定義的數(shù)字簽名算法(Digital Signature Algorithm DSA)。在SHA1算法中伯病,我們必須把原始消息(字符串造烁,文件等)轉(zhuǎn)換成位字符串否过。SHA1算法只接受位作為輸入。假設(shè)我們對(duì)字符串“abc”產(chǎn)生消息摘要惭蟋。首先需要進(jìn)行轉(zhuǎn)換為位字節(jié)苗桂,然后進(jìn)行補(bǔ)位補(bǔ)長(zhǎng)等操作,具體算法參見這里告组。
public static String getSha1(String str) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}