|         最近研究了下加密的操作,自己本身對加密不是很熟悉,看了一下java對加密的一些操作,在這里總結一下。java從1.5之后提供了Base64Encoder和Base64Decoder。為大家用的普遍的方法先MD5加密然后base64編碼,代碼如下: | 01 | importjava.io.UnsupportedEncodingException; | 
| 02 | importjava.security.MessageDigest; | 
| 03 | importjava.security.NoSuchAlgorithmException; | 
| 05 | importorg.apache.commons.codec.binary.Base64; | 
| 06 | importorg.apache.commons.codec.digest.DigestUtils; | 
| 08 | importsun.misc.BASE64Encoder; | 
| 10 | publicclassEncryptUtil { | 
| 12 |      * 使用java原生(先MD5加密在base64編碼) | 
| 17 |     publicstaticString MD5Encode(String str) { | 
| 18 |         String newString = ''; | 
| 19 |         BASE64Encoder base64Encoder = newBASE64Encoder(); | 
| 21 |             MessageDigest digest = MessageDigest.getInstance('MD5'); | 
| 22 |             newString = base64Encoder.encode(digest.digest(str | 
| 24 |         } catch(NoSuchAlgorithmException e) { | 
| 26 |         } catch(UnsupportedEncodingException e) { | 
| 37 |     publicstaticString MD5Encode2(String str) { | 
| 38 |         String newString = ''; | 
| 40 |             newString = Base64.encodeBase64String(DigestUtils.md5(str | 
| 42 |         } catch(UnsupportedEncodingException e) { | 
| 48 |     publicstaticvoidmain(String[] args) { | 
| 49 |         System.out.println(EncryptUtil.MD5Encode('哆啦A夢')); | 
| 50 |         System.out.println(EncryptUtil.MD5Encode2('哆啦A夢')); | 
看了下源碼,Apache的MD5加密底層用的是java的MessageDigest,使用起來較為方便。當然還對sha算法進行了封裝: | 01 | publicString encode(String str) { | 
| 03 |             Hex.encodeHexString(DigestUtils.md5(str)); | 
| 05 |             DigestUtils.md5Hex(str); | 
| 07 |             DigestUtils.shaHex(str); | 
| 09 |             Hex.encodeHexString(DigestUtils.sha256(str)); | 
| 11 |             DigestUtils.sha256Hex(str.getBytes('utf-8')); | 
| 13 |             DigestUtils.sha384Hex(str); | 
| 14 |             DigestUtils.sha512Hex(str); | 
| 15 |         } catch(UnsupportedEncodingException e) { | 
 |