java加密解密研究4、UrlBase64算法
先贴出Base64字符映射表:
上面的是Base64的字符映射表。
URL Base64的某些方面有别于Base64,它不需要定义每行字符数及行末回车换行符。同时,根据URL相关要求,符号“+”和符号“/”是不允许出现在URL中的,于是采用“-”和“_”符号取代。也就是说在上图的Base64字符映射表中 Value 63 对应的Encoding变成了“-”,Value 63 对应的Encoding变成了“_”。
同样,在URL中,符号“=”用作参数分隔符,所以也是不合法的。“=”在Base64中用作填充符,如果需要定长的Base64编码串,也姐需要相应的代替符号。Bouncy Castle和Commons Codec都实现了UrlBase64算法,不同的是Bouncy Castle使用“.”作为填充符,而Commons Codec直接放弃了填充符,使用不定长UrlBase64编码。
1、Bouncy Castle的实现和应用
package Test; import java.io.UnsupportedEncodingException; import org.bouncycastle.util.encoders.UrlBase64; /** * 封装Base64的工具类 * */ class UrlBase64Coder{ public final static String ENCODING="UTF-8"; //加密 public static String encoded(String data) throws UnsupportedEncodingException{ byte[] b=UrlBase64.encode(data.getBytes(ENCODING)); return new String(b,ENCODING); } //解密 public static String decode(String data) throws UnsupportedEncodingException{ byte[] b=UrlBase64.decode(data.getBytes(ENCODING)); return new String(b,ENCODING); } } /** * 测试类 */ public class UrlBase64Test { public static void main(String[] args) throws UnsupportedEncodingException { String str="Ad31"; //加密该字符串 String encodedString=UrlBase64Coder.encoded(str); System.out.println(encodedString); //解密该字符串 String decodedString=UrlBase64Coder.decode(encodedString); System.out.println(decodedString); } }
2、Commons Codec的实现和应用
package Test; import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Base64; /** * 封装Base64的工具类 * */ class UrlBase64Coder { public final static String ENCODING = "UTF-8"; // 加密 public static String encoded(String data) throws UnsupportedEncodingException { byte[] b = Base64.encodeBase64URLSafe(data.getBytes(ENCODING)); return new String(b, ENCODING); } // 解密 public static String decode(String data) throws UnsupportedEncodingException { byte[] b = Base64.decodeBase64(data.getBytes(ENCODING)); return new String(b, ENCODING); } } /** * 测试类 */ public class UrlBase64Test { public static void main(String[] args) throws UnsupportedEncodingException { String str = "Ad31"; // 加密该字符串 String encodedString = UrlBase64Coder.encoded(str); System.out.println(encodedString); // 解密该字符串 String decodedString = UrlBase64Coder.decode(encodedString); System.out.println(decodedString); } }
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: JNI学习(四)、本地方法创建java对象,以及对字符串的操作
- 下一篇:没有了