有些时候我们可能需要把信息通过url传递,但是url中出现特殊字符如空格,#,&等符号会使原有的信息失真,还有当传递密码等重要信息的时候可能就需要更复杂的加密解密算法。
这里使用的apache commons项目下的一个改进的base64算法,专门对url重新编码和加密的,如果要是传递重要信息,可以用DES+Base64来解决。
下载地址如下,
1.3之前版本没有这个类,所以最好使用1.4以上的版本:
具体使用给出个小例子
- import org.apache.commons.codec.binary.Base64;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- /**
- * 对url加密的加密解密算法,这样的加密结果只有数字和字母
- * @author Administrator
- *
- */
- public class Base64Encoding {
- private static final BASE64Decoder decoder = new BASE64Decoder();
- private static final BASE64Encoder encoder = new BASE64Encoder();
- private static final Base64 base64 = new Base64();
- /**
- * BASE64加密
- *
- * @param key
- * @return
- * @throws Exception
- */
- public static String encryptBASE64(String key) throws Exception {
- if (key == || key.length() < 1) {
- return "";
- }
- //return new String(encoder.encode(key.getBytes()));
- return new String(base64.encodeBase64URLSafe((new String(encoder.encode(key.getBytes()))).getBytes()));
- }
- public void changeCodeGBK(){
- }
- /**
- * BASE64解密
- *
- * @param key
- * @return
- * @throws Exception
- */
- public static String decryptBASE64(String key) throws Exception {
- if (key == || key.length() < 1) {
- return "";
- }
- return new String(decoder.decodeBuffer(new String(base64.decodeBase64(key.getBytes()))));
- //return new String(base64.decodeBase64(key.getBytes()));
- }
- public static void main(String[] args) throws Exception {
- String s=Base64Encoding.encryptBASE64("$%&^*%^* ^");
- System.out.println(s);
- System.out.println(Base64Encoding.decryptBASE64(s));
- }
- }
- 输出结果:
- SkNVbVhpb2xYaW9nSUY0PQ $%&^*%^* ^
本文出自 “orangleliu笔记本” 博客,请务必保留此出处 http://blog.csdn.net/orangleliu/article/details/38309367