Java--使用Base64编码对url传值

     有些时候我们可能需要把信息通过url传递,但是url中出现特殊字符如空格,#,&等符号会使原有的信息失真,还有当传递密码等重要信息的时候可能就需要更复杂的加密解密算法。

    这里使用的apache commons项目下的一个改进的base64算法,专门对url重新编码和加密的,如果要是传递重要信息,可以用DES+Base64来解决。
    下载地址如下, 1.3之前版本没有这个类,所以最好使用1.4以上的版本:
     http://commons.apache.org/codec/download_codec.cgi
   
    具体使用给出个小例子
    
  
  
  
  
  1. import org.apache.commons.codec.binary.Base64; 
  2.  
  3. import sun.misc.BASE64Decoder; 
  4. import sun.misc.BASE64Encoder; 
  5.  
  6. /** 
  7.  * 对url加密的加密解密算法,这样的加密结果只有数字和字母 
  8.  * @author Administrator 
  9.  * 
  10.  */ 
  11. public class Base64Encoding { 
  12.     private static final BASE64Decoder decoder = new BASE64Decoder(); 
  13.     private static final BASE64Encoder encoder = new BASE64Encoder(); 
  14.     private static final Base64 base64 = new Base64(); 
  15.  
  16.     /** 
  17.      * BASE64加密 
  18.      *  
  19.      * @param key 
  20.      * @return 
  21.      * @throws Exception 
  22.      */ 
  23.     public static String encryptBASE64(String key) throws Exception { 
  24.         if (key == null || key.length() < 1) { 
  25.             return ""
  26.         } 
  27.         //return new String(encoder.encode(key.getBytes())); 
  28.         return new String(base64.encodeBase64URLSafe((new String(encoder.encode(key.getBytes()))).getBytes())); 
  29.     } 
  30.      
  31.      
  32.     public void changeCodeGBK(){ 
  33.          
  34.     } 
  35.     /** 
  36.      * BASE64解密 
  37.      *  
  38.      * @param key 
  39.      * @return 
  40.      * @throws Exception 
  41.      */ 
  42.     public static String decryptBASE64(String key) throws Exception { 
  43.         if (key == null || key.length() < 1) { 
  44.             return ""
  45.         } 
  46.         return new String(decoder.decodeBuffer(new String(base64.decodeBase64(key.getBytes())))); 
  47.         //return new String(base64.decodeBase64(key.getBytes())); 
  48.          
  49.          
  50.     } 
  51.      
  52.     public static void main(String[] args) throws Exception { 
  53.         String s=Base64Encoding.encryptBASE64("$%&^*%^*  ^"); 
  54.         System.out.println(s); 
  55.         System.out.println(Base64Encoding.decryptBASE64(s)); 
  56.     } 
  57. 输出结果:
  58. SkNVbVhpb2xYaW9nSUY0PQ $%&^*%^* ^

你可能感兴趣的:(base64,加密解密,URL传值,url加密,连接传值)