URL字符串加密

import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
 * 对URL进行加密类
 *
 * @author <a href="mailto:jiangtao@ultrapower.com.cn">jiangtao</a>
 *
 * @version $Revision$
 */
public class URLEncoder {
 private static char[] tab = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

 /**
  * 加密方式
  * @param s 要加密的串
  * @return 加密后的串
  */
 public static String encode(String s) {
        try {
            if (s == null || s.equals("")) return "";
            StringBuilder tmpStr = new StringBuilder();
            byte tmpByte[] = s.getBytes();
            for (byte aTmpByte : tmpByte)
                tmpStr.append("").append(tab[0x0f & (aTmpByte >> 4)]).append(tab[0x0F & aTmpByte]);
            return tmpStr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return s;
        }
    }
 
 /**
  * 解密方法
  * @param s 要加密的串
  * @return 解密后的串
  */
 public static String decode(String s) {
        try {
            if (s == null || s.equals("")) return "";
            ByteArrayOutputStream bytess = new ByteArrayOutputStream();
            byte tmpByte[] = s.toUpperCase().getBytes();
            for (int i = 0; i < tmpByte.length / 2; i++) {
                tmpByte[i * 2] = pocb(tmpByte[i * 2]);
                tmpByte[i * 2 + 1] = pocb(tmpByte[i * 2 + 1]);
                bytess.write((tmpByte[i * 2] << 4) | (tmpByte[i * 2 + 1]));
            }
            bytess.flush();
            return new String(bytess.toByteArray());
        } catch (Exception e) {
            return s;
        }
    }

    private static byte pocb(byte b) {
        if (b > 57) {
            b -= 55;
        } else {
            b -= 48;
        }
        return b;
    }

    public static String encodeBase64(String str) {
        byte[] b = str.getBytes();
        return new sun.misc.BASE64Encoder().encode(b);
    }


    public static String decodeBase64(String fileContent) throws IOException {
        byte[] b = new sun.misc.BASE64Decoder().decodeBuffer(fileContent);
        return new String(b);
    }

 /**
  * @param args
  */
 public static void main(String[] args) {
        String url = "url=XX中文//、中文测试ttt../test/bop.jsp?menuid=2020100007&menu=中国&amp;";
        System.out.println("encode :" + URLEncoder.encode(url));
     System.out.println("decode :" + URLEncoder.decode("687474703A2F2F7777772E626F6D632E636F6D3A383038312F7569702F6F7065726174696F6E2F626F70506F7065646F6D21626F70547265652E706F7274616C"));
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值