1 简介
Base64是一种基于64个可打印字符来表示二进制数据的方法.包括小写字母a-z、大写字母A-Z、数字0-9、符号"+“、”/"一共64个字符的字符集,(任何符号都可以转换成这个字符集中的字符,这个转换过程就叫做base64编码。
Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3x8 = 4x6 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。
2 字符对照表
3 编解码规则
3.1编码步骤
1、把字符串转化成ASCII码;如果是数据流,忽略该步;
2、根据ASCII码(数据流)的二进制进行每6bit/组进行分组,如果最后一组小于6bit,则填充0,以达到6bit,并且在编码末尾添加“=”;
3、跟据每组数据查表,得到对应的编码。
3.2 解码步骤
解码为编码的逆过程:
1、根据编码字符查找对应的数字;
2、每个数字转化成6个bit;
3、把以上bit串按8bit/组进行分组;
4、每组的数字即为数据流。
4 举例
4.1 编码
4.1.1 字节长度 mod 3 = 0
比如字符串: base64
对应ASCII(HEX): 62 61 73 65 36 34
2进制:01100010 01100001 01110011 01100101 00110110 00110100
分组(6bit/组): 011000 100110 000101 110011 011001 010011 011000 110100
分组对应十进制:24 38 5 51 25 19 24 52
查找对应编码:YmFzZTY0
4.1.2 字节长度 mod 3 = 1
比如字符串: base
对应ASCII(HEX): 62 61 73 65
2进制:01100010 01100001 01110011 01100101
分组(6bit/组): 011000 100110 000101 110011 011001 01xxxx(x填充bit-0) xxxxxx(对应编码“=”)xxxxxx(对应编码“=”)
分组对应十进制:24 38 5 51 25 10
查找对应编码:YmFzZQ==
4.1.3 字节长度 mod 3 = 2
比如字符串: base6
对应ASCII(HEX): 62 61 73 65 36
2进制:01100010 01100001 01110011 01100101 00110110
分组(6bit/组): 011000 100110 000101 110011 011001 010011 0110xx(x填充bit-0) xxxxxx(对应编码“=”)
分组对应十进制:24 38 5 51 25 19 24
查找对应编码:YmFzZTY=
4.2 解码
(略)
5、实现
Delphi 7实现:encddecd.pas
function StreamToBase64(AStream: TStream) : string;
var
temp: TStringStream;
begin
try
temp := TStringStream.Create('');
EncodeStream(AStream, temp); //Delphi7 自带unit EncdDecd的方法
Result:=temp.DataString;
except
end;
FreeAndNil(temp);
end;
function BytesToBase64(const bytes : TByteArray;len:integer) : string;
var
memoryStream : TMemoryStream;
begin
try
memoryStream := TMemoryStream.Create;
memoryStream.WriteBuffer(bytes[0], len);
memoryStream.Seek(0, soFromBeginning);
Result := StreamToBase64(memoryStream);
memoryStream.Free;
except
end;
end;
function Encode_Bsae64(Value: string): string;
var
Data_Input:TByteArray;
Data_Input_Len :Word;
begin
fillchar(Data_Input,sizeof(Data_Input),0);
Data_Input_Len := StrHexToByteBuf(Value, @Data_Input);
Encode_Bsae64 := BytesToBase64(Data_Input, Data_Input_Len);
end;
procedure TForm1.btnHex_Base64Click(Sender: TObject);
begin
mmobase64.Clear;
mmobase64.Lines.Add(Encode_Bsae64(mmoHex.Text));
end;
function Decrypt_Bsae64(Value: string): string;
var
AStream: TStringStream;
temp:TMemoryStream;
Buf_T:array [0..1023] of byte;
begin
try
AStream := TStringStream.Create(Value);
temp := TMemoryStream.Create;
DecodeStream(AStream, temp); //Delphi7 自带unit EncdDecd的方法
temp.Position := 0;
temp.Read(Buf_T, sizeof(Buf_T));
Result := ByteBufToHexStr(@Buf_T, temp.Size);
except
end;
FreeAndNil(temp);
FreeAndNil(AStream);
end;
procedure TForm1.btnBase64_HHexClick(Sender: TObject);
begin
mmoHex.Clear;
mmoHex.Lines.Add(Decrypt_Bsae64(mmobase64.Text));
end;