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

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

    这里使用的apache commons项目下的一个改进的base64算法,专门对url重新编码和加密的,如果要是传递重要信息,可以用DES+Base64来解决。
    下载地址如下, 1.3之前版本没有这个类,所以最好使用1.4以上的版本:
   
    具体使用给出个小例子
    
[java]  view plain  copy
  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 ==  || 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 ==  || 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. 输出结果:  
  59. SkNVbVhpb2xYaW9nSUY0PQ  $%&^*%^*  ^  

本文出自  orangleliu笔记本  博客,请务必保留此出处 http://blog.csdn.net/orangleliu/article/details/38309367   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值