Java之Base64編碼解析

雲水在掘金發表於2018-12-01

  說明:前段時間梳理了一下最近工作中用到加解密演算法,從最早的MD5、Base64到後面的對稱演算法DES、IDEA,非對稱演算法RSA、DSA等,準備整理出來做一備份。base64是比較特殊的,準確的說它是一種編碼方式,主要解決網路某些位元組編碼傳輸問題的;我們專案中也確實把它作為一種加密演算法,這裡在第4部分結合程式碼詳細說明(部分原理&圖片或取於網路)。

1、Base64編碼起源


  因為有些網路傳送渠道並不支援所有的位元組,例如傳統的郵件只支援可見字元的傳送,像ASCII碼的控制字元就 不能通過郵件傳送。這樣用途就受到了很大的限制,比如圖片二進位制流的每個位元組不可能全部是可見字元,所以就傳送不了。最好的方法就是在不改變傳統協議的情 況下,做一種擴充套件方案來支援二進位制檔案的傳送。把不可列印的字元也能用可列印字元來表示,問題就解決了。Base64編碼應運而生,Base64就是一種 基於64個可列印字元來表示二進位制資料的表示方法。


2、Base64編碼原理


在這裡插入圖片描述
  這是一張base64的序列圖,通常一個位元組是用8個bit 表示,在通常字元處理中一個字元通常是2位元組16bit,也有utf-8中字元佔3個位元組24bit...;而base64是用6個bit表示一個位元組,通過是以6的位數12bit,18bit....去處理;這裡取8與6的最小公位數24,所以通過用4個Base64字元可以表示3個標準的ascll字元(所以經過base64編碼後,長度會比源串長1/3,後面談到RSA會具體說明加密後的長度變化)。
在這裡插入圖片描述
  像上圖中,A字元佔一個位元組8位,轉成base64編碼 先以6位劃分,第二個6位只有01其餘位則用0佔用,第三個6位與第四個6位為空,則用==表示,這也是我們常看到經base64轉碼後為啥常以=結尾的原因。


3、Base64加解密


  這裡加解密,主要是以Java自帶的為主(這裡用的是jdk7),jdk中實現base64加解密 主要是基於圖一中標準的字典序實現的,原始碼在rt.jar中。

在這裡插入圖片描述
  具體程式碼會在第4部分中說明,很顯然JDK實現了標準的字典序,用來進base64進行編碼處理肯定沒問題,但用來加解密貌似沒意義,大家用共同的標準,就像你家的門給每個訪問都準備的鑰匙。


4、變化的Base64序列


   如果讓Base64具有加解密的功能,至少要一部分是變化的;這裡可以通過變化標準序列的方式;建議大家用到的時候,可以先看一下第3部分中標出那個類的原始碼(沒幾行程式碼);這個變化的序列可以根據時間、根據UUID、根據一切可以變換的東西來生成,這裡是根據UUID來隨機生成序列。    1、生成隨機序列

private static String base64Str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	// 根據UUID生成
	public static synchronized String getRandomBase64(int len) {
		char[] chars = base64Str.toCharArray();
		String uuid = UUID.randomUUID().toString();
		byte[] sha256Arr = null;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
			messageDigest.reset();
			sha256Arr = messageDigest.digest(uuid.getBytes());
			if (sha256Arr != null) {
				for (int i = 0; i < sha256Arr.length; i++) {
					int pos = Math.abs(sha256Arr[i]) % 32;
					char tmp = chars[i];
					chars[i] = chars[32 + pos];
					chars[32 + pos] = tmp;
				}
			}
		} catch (Exception e) {}
		return new String(chars).substring(0, len);
	}
複製程式碼

  2、base64的編碼與解碼的演算法我就不自己實現了(網上有各種實現),我比較懶,直接Copy出來改JDK7原始碼自帶的,將它帶的標準序列替換掉(下面只是測試程式碼,不嚴謹供參考用)。

public class Base64Encode extends CharacterEncoder {
	public static char[] pem_array;
	@Override
	protected int bytesPerAtom() {
		return 3;
	}
	@Override
	protected int bytesPerLine() {
		return 57;
	}
	@Override
	protected void encodeAtom(final OutputStream outputStream,
			final byte[] array, final int n, final int n2) throws IOException {
		if (n2 == 1) {
			final byte b = array[n];
			final int n3 = 0;
			outputStream.write(Base64Encode.pem_array[b >>> 2 & 0x3F]);
			outputStream.write(Base64Encode.pem_array[(b << 4 & 0x30)
					+ (n3 >>> 4 & 0xF)]);
			outputStream.write(61);
			outputStream.write(61);
		} else if (n2 == 2) {
			final byte b2 = array[n];
			final byte b3 = array[n + 1];
			final int n4 = 0;
			outputStream.write(Base64Encode.pem_array[b2 >>> 2 & 0x3F]);
			outputStream.write(Base64Encode.pem_array[(b2 << 4 & 0x30)
					+ (b3 >>> 4 & 0xF)]);
			outputStream.write(Base64Encode.pem_array[(b3 << 2 & 0x3C)
					+ (n4 >>> 6 & 0x3)]);
			outputStream.write(61);
		} else {
			final byte b4 = array[n];
			final byte b5 = array[n + 1];
			final byte b6 = array[n + 2];
			outputStream.write(Base64Encode.pem_array[b4 >>> 2 & 0x3F]);
			outputStream.write(Base64Encode.pem_array[(b4 << 4 & 0x30)
					+ (b5 >>> 4 & 0xF)]);
			outputStream.write(Base64Encode.pem_array[(b5 << 2 & 0x3C)
					+ (b6 >>> 6 & 0x3)]);
			outputStream.write(Base64Encode.pem_array[b6 & 0x3F]);
		}
	}
	/*static {
    pem_array = new char[] { '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', '+', '/' };
	}*/
}
複製程式碼
public class Base64Decode extends CharacterDecoder{
	public static  char[] pem_array;
    private static  byte[] pem_convert_array;
    byte[] decode_buffer;
    public Base64Decode() {
        this.decode_buffer = new byte[4];
    }
    @Override
    protected int bytesPerAtom() {
        return 4;
    } 
    @Override
    protected int bytesPerLine() {
        return 72;
    }  
    @Override
    protected void decodeAtom(final PushbackInputStream pushbackInputStream, final OutputStream outputStream, int n) throws IOException {
        int n2 = -1;
        int n3 = -1;
        int n4 = -1;
        int n5 = -1;
        if (n < 2) {
            throw new CEFormatException("Base64Decode: Not enough bytes for an atom.");
        }
        int read;
        do {
            read = pushbackInputStream.read();
            if (read == -1) {
                throw new CEStreamExhausted();
            }
        } while (read == 10 || read == 13);
        this.decode_buffer[0] = (byte)read;
        if (this.readFully(pushbackInputStream, this.decode_buffer, 1, n - 1) == -1) {
            throw new CEStreamExhausted();
        }
        if (n > 3 && this.decode_buffer[3] == 61) {
            n = 3;
        }
        if (n > 2 && this.decode_buffer[2] == 61) {
            n = 2;
        }
        switch (n) {
            case 4: {
                n5 = Base64Decode.pem_convert_array[this.decode_buffer[3] & 0xFF];
            }
            case 3: {
                n4 = Base64Decode.pem_convert_array[this.decode_buffer[2] & 0xFF];
            }
            case 2: {
                n3 = Base64Decode.pem_convert_array[this.decode_buffer[1] & 0xFF];
                n2 = Base64Decode.pem_convert_array[this.decode_buffer[0] & 0xFF];
                break;
            }
        }
        switch (n) {
            case 2: {
                outputStream.write((byte)((n2 << 2 & 0xFC) | (n3 >>> 4 & 0x3)));
                break;
            }
            case 3: {
                outputStream.write((byte)((n2 << 2 & 0xFC) | (n3 >>> 4 & 0x3)));
                outputStream.write((byte)((n3 << 4 & 0xF0) | (n4 >>> 2 & 0xF)));
                break;
            }
            case 4: {
                outputStream.write((byte)((n2 << 2 & 0xFC) | (n3 >>> 4 & 0x3)));
                outputStream.write((byte)((n3 << 4 & 0xF0) | (n4 >>> 2 & 0xF)));
                outputStream.write((byte)((n4 << 6 & 0xC0) | (n5 & 0x3F)));
                break;
            }
        }
    }   
     {
       // pem_array = new char[] { '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', '+', '/' };
        pem_convert_array = new byte[256];
        for (int i = 0; i < 255; ++i) {
            Base64Decode.pem_convert_array[i] = -1;
        }
        for (int j = 0; j < Base64Decode.pem_array.length; ++j) {
            Base64Decode.pem_convert_array[Base64Decode.pem_array[j]] = (byte)j;
        }
    }
}
複製程式碼

  這裡寫了兩個類Base64Encoder、Base64Decoder分別繼承CharacterEncoder和CharacterDecoder兩個你類(照抄原始碼),將標準序列中private final 改掉便可。   3、傳入隨機序列,測試,可以多試幾次

private static char[] ch = Base64Util.getRandomBase64(64).toCharArray() ;
	// 加密
	public static String getBase64(String str) throws Exception {
		byte[] b = null;
		String s = null;
			b = str.getBytes("utf-8");
		if (b != null) {
			Base64Encode.pem_array=ch;
			s = new Base64Encode().encode(b);
		}
		return s;
	}
	// 解密
	public static String getFromBase64(String s) throws Exception {
		byte[] b = null;
		String result = null;
		if (s != null) {
			Base64Decode.pem_array = ch ;
			Base64Decode decoder = new Base64Decode();
				b = decoder.decodeBuffer(s);
				result = new String(b, "utf-8");
		}
		return result;
	}
	public static void main(String[] s) throws Exception{
		String o = "日明星辰hello" ;
		System.out.println(getBase64(o));
		System.out.println(getFromBase64(getBase64(o)));
	}
複製程式碼

在這裡插入圖片描述


持續更新中,可以關注........

javaview.jpg

相關文章