Java sha1散列算法原理及代碼實例
直接調(diào)用HashKit.sha1(String str)方法就可以了,,返回的是16進制的字符串長度是40,
也就是用md.digest()方法解析出來的字節(jié)數(shù)是160字節(jié)長度。
而MD5散列算法生成的字節(jié)數(shù)是128字節(jié)長度,返回的16進制的字符長度是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)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)2. ASP.NET MVC遍歷驗證ModelState的錯誤信息3. jsp網(wǎng)頁實現(xiàn)貪吃蛇小游戲4. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向5. CSS hack用法案例詳解6. asp中response.write("中文")或者js中文亂碼問題7. 將properties文件的配置設(shè)置為整個Web應(yīng)用的全局變量實現(xiàn)方法8. PHP設(shè)計模式中工廠模式深入詳解9. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明10. ASP實現(xiàn)加法驗證碼
