轉:http://zoroeye.iteye.com/blog/2026984?utm_source=tuicool&utm_medium=referral
md5加密實現方法有很多種,也導致很難選擇。大概分析下自己了解的一些用法。
1.sun官方
sun提供了MessageDigest和BASE64Encoder可以用指定算法加密。
例:
- public static final String EncoderPwdByMd5(String str) throws NoSuchAlgorithmException,UnsupportedEncodingException
- {
- // 確定計算方法
- MessageDigest md5 = MessageDigest.getInstance("MD5");
- BASE64Encoder base64en = new BASE64Encoder();
- // 加密后的字符串,注意一定要自己指定編碼,否則會取系統默認。不同系統會不一致。
- String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
- return newstr;
- }
分析:
1)BASE64Encoder是不建議使用的,引入有時候也會報錯:
Access restriction: The type BASE64Encoder is not accessible due to restriction on required library C:\Program files\java\jdk1.6\jre\lib\rt.jar
oracle官方有文檔說明(Why Developers Should Not Write Programs That Call 'sun' Packages),sun.*下面的類不建議使用:
http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html
但也有兩種規避辦法。
方法一:
1. Open project properties.
2. Select Java Build Path node.
3. Select Libraries tab.
4. Remove JRE System Library.
5. Add Library JRE System Library.
方法二:
Go to Window-->Preferences-->Java-->Compiler-->Error/Warnings.
Select Deprecated and Restricted API. Change it to warning.
Change forbidden and Discouraged Reference and change it to warning. (or as your need.)
另外:
使用MessageDigest不使用BASE64Encoder也可以實現md5加密,但要自己實現md5算法,
比較麻煩。可以參考:
http://blog.csdn.net/xiao__gui/article/details/8148203http://blog.csdn.net/xiao__gui/article/details/8148203
http://wenku.baidu.com/link?url=pgf96g_dt2r2vEE88RG7jqMaW3PCSmxL_3sEBwbNb4EzLalQnb-hUsAB1bnqotbAlCDTT60WvFdS0hn9QTeSJAUtahDgpWE9Z_S-yM8Y6-a
2.sun官方和第三方結合
也可以使用MessageDigest 加第三方apache commons-codec的支持:
- final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
- messageDigest.reset();
- messageDigest.update(string.getBytes(Charset.forName("UTF8")));
- final byte[] resultByte = messageDigest.digest();
- String result = Hex.encodeHexString(resultByte);
注意:
以上兩種方法都使用了MessageDigest,需要特別強調:MessageDigest線程不安全。 The MessageDigest classes are NOT thread safe. If they're going to be used by different threads, just create a new one, instead of trying to reuse them.
3.使用第三方工具包
很多第三方工具都提供了md5,sha等加密方法。apache,google等都提供了工具包。
3.1 apache的commons-codec
1)maven配置(現在的版本有很多,選擇自己需要的):
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency>
2)引入包后:
- public static String encodeMD5Hex(String data)
- {
- return DigestUtils.md5Hex(data);
- }
並且該方法是線程安全的。
3.2 google的guava
Apache Common是一個時間比較久的框架了,Google針對基礎框架退出了自己的類庫,並且開源出來(http://code.google.com/p/guava-libraries/),名為“Guava”。它在部分功能上其實是ApacheCommon的一個子集,但在性能上做了很多優化,並且針對並發和大規模系統開發做了很多新的策略(如CopyOnWrite、Immutable、SkipList)等。雖然有些類和java.util.concurrent有些重疊,但是在一般環境下都可以替代。
md5示例:
- Hasher hasher = Hashing.md5().newHasher();
- hasher.putString("my string");
- byte[] md5 = hasher.hash().asBytes();
既方便又安全。
此外,其他組織或公司也有對外提供的工具類,額。。還不清楚。
綜上,從使用方便和安全性,性能等考慮,優先選擇還是第三方的工具包。