当前位置: 源码素材网 » Delphi教程 » 详情页

我收藏的Delphi Base64加密、解密函数 代码分享

  •   时间:2019-01-29
  • 概述:解密 加密 Base64

这是我收藏的一个用于Delphi编程的Base64加密、解密函数,已经在我的Delphi项目中使用过,用起来挺方便,代码也简单,分享给大家:

function  Base64Encode(const s: string): string;  //string转Base64
var
  i,c1,c2,c3: Integer;
  m,n: Integer;
const
  Base64: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
begin
  Result := '';
  m:=1;
  n:=0;
  for i := 1 to (Length(s) div 3) do
  begin
    c1 := Ord(s[m]);
    c2 := Ord(s[m+1]);
    c3 := Ord(s[m+2]);
    m:=m+3;
    Result := Result+base64[(c1 shr 2)and $3F+1];
    Result := Result+base64[((c1 shl 4)and $30) or ((c2 shr 4)and $0F)+1];
    Result := Result+base64[((c2 shl 2)and $3C) or ((c3 shr 6)and $03)+1];
    Result := Result+base64[c3 and $3F+1];
    n:=n+4;
    if(n = 76)then
    begin
       n:=0;
       Result := Result+#13#10;
    end;
  end;
  if (Length(s) mod 3)=1 then
  begin
    c1 := Ord(s[m]);
    Result := Result+base64[(c1 shr 2)and $3F+1];
    Result := Result+base64[(c1 shl 4)and $30+1];
    Result := Result+'=';
    Result := Result+'=';
  end;
  if (Length(s) mod 3)=2 then
  begin
    c1 := Ord(s[m]);
    c2 := Ord(s[m+1]);
    Result := Result+ base64[(c1 shr 2)and $3F+1];
    Result := Result+ base64[((c1 shl 4)and $30) or ((c2 shr 4)and $0F)+1];
    Result := Result+base64[(c2 shl 2)and $3C+1];
    Result := Result+ '=';
  end;

function  Base64Decode(const s: string): string;  //Base64转String
var
  i,m,n: Integer;
  c1,c2,c3,c4: Integer;
const
  Base64: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
begin
  Result := '';
  n:=1;
  m:=Length(s);
  if s[m]='='then m:=m-1;
  if s[m]='='then m:=m-1;
  for i:=1 to m div 4 do
  begin
    c1:=Pos(s[n],Base64)-1;
    c2:=Pos(s[n+1],Base64)-1;
    c3:=Pos(s[n+2],Base64)-1;
    c4:=Pos(s[n+3],Base64)-1;
    n:=n+4;
    Result:=Result+Chr(((c1 shl 2)and $FC)or((c2 shr 4)and $3));
    Result:=Result+Chr(((c2 shl 4)and $F0)or((c3 shr 2)and $0F));
    Result:=Result+Chr(((c3 shl 6)and $C0)or c4);
  end;
  if m mod 4=2 then
  begin
    c1:=Pos(s[n],Base64)-1;
    c2:=Pos(s[n+1],Base64)-1;
    Result:=Result+Chr(((c1 shl 2)and $FC)or((c2 shr 4)and $3));
  end;

  if m mod 4=3 then
  begin
    c1:=Pos(s[n],Base64)-1;
    c2:=Pos(s[n+1],Base64)-1;
    c3:=Pos(s[n+2],Base64)-1;
    Result:=Result+Chr(((c1 shl 2)and $FC)or((c2 shr 4)and $3));
    Result:=Result+Chr(((c2 shl 4)and $F0)or((c3 shr 2)and $0F));
  end;

    相关声明:

      若“我收藏的Delphi Base64加密、解密函数 代码分享”有损您的权益,请告之我们删除内容。
      部分文章来源于网络,版权归原作者所有。