使用Apache commons-codec Base64实现加解密

commons-codec是Apache下面的一个加解密开发包

官方地址为:http://commons.apache.org/codec/

官方下载地址:http://commons.apache.org/codec/download_codec.cgi

在线文档:http://commons.apache.org/codec/userguide.html

下面示例为使用Base64实现字符串的加解密:

[java] view plain copy
  1. /** 
  2.      *  
  3.      * 创建日期2011-4-25上午10:12:38 
  4.      * 修改日期 
  5.      * 作者:dh *TODO 使用Base64加密算法加密字符串 
  6.      *return 
  7.      */  
  8.     public static String encodeStr(String plainText){  
  9.         byte[] b=plainText.getBytes();  
  10.         Base64 base64=new Base64();  
  11.         b=base64.encode(b);  
  12.         String s=new String(b);  
  13.         return s;  
  14.     }  
  15.       
  16.     /** 
  17.      *  
  18.      * 创建日期2011-4-25上午10:15:11 
  19.      * 修改日期 
  20.      * 作者:dh     *TODO 使用Base64加密 
  21.      *return 
  22.      */  
  23.     public static String decodeStr(String encodeStr){  
  24.         byte[] b=encodeStr.getBytes();  
  25.         Base64 base64=new Base64();  
  26.         b=base64.decode(b);  
  27.         String s=new String(b);  
  28.         return s;  
  29.     }  

commons-codec包可以从apache下载,最新版是1.3

不可逆算法

1.MD5

<!---->String str = "abc";
DigestUtils.md5Hex(str);

附.net生成MD5的方法,生成内容跟java一致:

<!----> String str = "abc";
FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");

 

2.SHA1

<!---->String str = "abc";
DigestUtils.shaHex(str);

附.net生成SHA1的方式,生成内容跟java一致:

<!----> String str = "abc" ;
FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");

 

可逆算法

常规加密解密算法:BASE64

加密

<!---->String str= "abc"; // abc为要加密的字符串
byte[] b = Base64.encodeBase64(str.getBytes(),  true);
System.out.println( new String(b));

解密

<!---->String str = "YWJj"; // YWJj为要解密的字符串
byte[] b = Base64.decodeBase64(str.getBytes());
System.out.println( new String(b));

猜你喜欢

转载自ximeng1234.iteye.com/blog/2213399