Java sha1散列算法原理及代碼實(shí)例
直接調(diào)用HashKit.sha1(String str)方法就可以了,,返回的是16進(jìn)制的字符串長度是40,
也就是用md.digest()方法解析出來的字節(jié)數(shù)是160字節(jié)長度。
而MD5散列算法生成的字節(jié)數(shù)是128字節(jié)長度,返回的16進(jìn)制的字符長度是32位
代碼如下
public class HashKit { private static final char[] HEX_DIGITS = '0123456789abcdef'.toCharArray(); public static String sha1(String srcStr){ return hash('SHA-1', srcStr); } public static String hash(String algorithm, String srcStr) { try {MessageDigest md = MessageDigest.getInstance(algorithm);byte[] bytes = md.digest(srcStr.getBytes('utf-8'));return toHex(bytes); } catch (Exception e) {throw new RuntimeException(e); } } public static String toHex(byte[] bytes) { StringBuilder ret = new StringBuilder(bytes.length * 2); for (int i=0; i<bytes.length; i++) {ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);ret.append(HEX_DIGITS[bytes[i] & 0x0f]); } return ret.toString(); }}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. jstl 字符串處理函數(shù)2. JSP動態(tài)網(wǎng)頁開發(fā)原理詳解3. XHTML 1.0:標(biāo)記新的開端4. Vue中使用Echarts儀表盤展示實(shí)時數(shù)據(jù)的實(shí)現(xiàn)5. 深入理解JavaScript中的Base64編碼字符串6. java 字符串轉(zhuǎn)化為字符數(shù)組的3種實(shí)現(xiàn)案例7. JSP頁面的靜態(tài)包含和動態(tài)包含使用方法8. WAP建站W(wǎng)ML語言語法基礎(chǔ)教程第1/6頁9. 基于python實(shí)現(xiàn)判斷字符串是否數(shù)字算法10. PHP擴(kuò)展之URL編碼、解碼及解析——URLs
