如果你看 一下java8以上的版本中的java.util.Base64.Encoder的源碼,你會看到這裡涉及兩種不同的标準 RFC 2045/ RFC 4648
差別在于最後兩個字元的選用、回行符選用、結尾是否配齊等選項。
很多實作不完全是按上面的标準來的,導緻結果各異。
private Encoder(boolean isURL, byte[] newline, int linemax, boolean doPadding) {
this.isURL = isURL;
this.newline = newline;
this.linemax = linemax;
this.doPadding = doPadding;
}
private static final char[] toBase64 = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
private static final char[] toBase64URL = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
};
private static final int MIMELINEMAX = 76;
private static final byte[] CRLF = new byte[] {'\r', '\n'};
static final Encoder RFC4648 = new Encoder(false, null, -1, true);
static final Encoder RFC4648_URLSAFE = new Encoder(true, null, -1, true);
static final Encoder RFC2045 = new Encoder(false, CRLF, MIMELINEMAX, true);
用是面的類,測試如下
import java.util.Base64;
public class Base64Test {
@Test
public void testBase64() {
String s ="{\"name\": \"Connor\"}";
final byte[] bf = s.getBytes();
System.out.println(s);
System.out.println(Base64.getEncoder().encodeToString(bf));
System.out.println(Base64.getUrlEncoder().encodeToString(bf));
System.out.println(Base64.getMimeEncoder().encodeToString(bf));
}
}
會輸出:
{"name": "Connor"}
eyJuYW1lIjogIkNvbm5vciJ9
eyJuYW1lIjogIkNvbm5vciJ9
eyJuYW1lIjogIkNvbm5vciJ9