Base64编码函数:
function Base64_Encode(var str:string):boolean;
const
EncodeBase64:string='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var
Byte1,Byte2,Byte3:char;
LenMod:integer;
LenDiv:integer;
i:integer;
EncodeStr:string;
begin
EncodeStr:='';
LenDiv:=length(str) div 3;
LenMod:=length(str) mod 3;
for i:=1 to LenDiv do
begin
Byte1:=str[i*3-2];
Byte2:=str[i*3-1];
Byte3:=str[i*3];
EncodeStr:=EncodeStr+EncodeBase64[(Byte(Byte1) shr 2)+1];
EncodeStr:=EncodeStr+EncodeBase64[(((Byte(Byte1) shl 4) or (Byte(Byte2) shr 4)) and $3f)+1];
EncodeStr:=EncodeStr+EncodeBase64[(((Byte(Byte2) shl 2) or (Byte(Byte3) shr 6)) and $3f)+1];
EncodeStr:=EncodeStr+EncodeBase64[((Byte(Byte3) and $3f))+1];
end;{end of for}
if LenMod=1 then
begin
Byte1:=str[length(str)];
EncodeStr:=EncodeStr+EncodeBase64[(Byte(Byte1) shr 2)+1];
EncodeStr:=EncodeStr+EncodeBase64[((Byte(Byte1) shl 4) and $3f)+1];
EncodeStr:=EncodeStr+'=';
EncodeStr:=EncodeStr+'=';
end;
if LenMod=2 then
begin
Byte1:=str[length(str)-1];
Byte2:=str[length(str)];
EncodeStr:=EncodeStr+EncodeBase64[(Byte(Byte1) shr 2)+1];
EncodeStr:=EncodeStr+EncodeBase64[(((Byte(Byte1) shl 4) or (Byte(Byte2) shr 4)) and $3f)+1];
EncodeStr:=EncodeStr+EncodeBase64[((Byte(Byte2) shl 2) and $3f)+1];
EncodeStr:=EncodeStr+'=';
end;
Str:=EncodeStr;
end;
解码函数:
function Base64_Decode(var str:string):boolean;
const
DecodeBase64:array[0..127] of integer
=(-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,63,
52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,
-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,
-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1);
var
i,LenDiv:integer;
DecodeStr:string;
B1,B2,B3,B4:char;
begin
LenDiv:=length(str) div 4;
DecodeStr:='';
for i:=1 to LenDiv do
begin
B1:=str[i*4-3];
B2:=str[i*4-2];
B3:=str[i*4-1];
B4:=str[i*4];
DecodeStr:=DecodeStr+char((DecodeBase64[ord(B1)] shl 2)
or (DecodeBase64[ord(B2)] shr 4));
if B3<>'=' then
DecodeStr:=DecodeStr+char((DecodeBase64[ord(B2)] shl 4)
or (DecodeBase64[ord(B3)] shr 2));
if B4<>'=' then
DecodeStr:=DecodeStr+char((DecodeBase64[ord(B3)] shl 6)
or DecodeBase64[ord(B4)]);
end;{end of for}
Str:=DecodeStr;
end;