BASE64URL編碼的流程:
1、明文使用BASE64進行加密
2、在BASE64的基礎上進行一下的編碼:
1)去除尾部的"="
2)把"+"替換成"-"
3)把"/"替換成"_"
BASE64URL解碼的流程:
1、把BASE64URL的編碼做如下解碼:
1)把"-"替換成"+"
2)把"_"替換成"/"
3)(計算BASE64URL編碼長度)%4
a)結果為0,不做處理
b)結果為2,字符串添加"=="
c)結果為3,字符串添加"="
2、使用BASE64解碼密文,得到原始的明文
BASE64URL在JAVA中的實現
public static String base64UrlEncode(byte[] simple) {
String s = new String(Base64.encodeBase64(simple)); // Regular base64 encoder s = s.split("=")[0]; // Remove any trailing '='s s = s.replace('+', '-'); // 62nd char of encoding s = s.replace('/', '_'); // 63rd char of encoding return s; } public static byte[] base64UrlDecode(String cipher) { String s = cipher; s = s.replace('-', '+'); // 62nd char of encoding s = s.replace('_', '/'); // 63rd char of encoding switch (s.length() % 4) { // Pad with trailing '='s case 0: break; // No pad chars in this case case 2: s += "=="; break; // Two pad chars case 3: s += "="; break; // One pad char default: System.err.println("Illegal base64url String!"); } return Base64.decodeBase64(s); // Standard base64 decoder}
from http://shimingxy.blog.163.com/blog/static/740383420152113532844/