DelphiBase32の暗号化と復号化


const
  ValidChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

// Base32解码
function Base32Decode(const source: string): string;
var
  UpperSource: string;
  p, i, l, n, j: Integer;
begin
  UpperSource := UpperCase(source);

  l := Length(source);
  n := 0;
  j := 0;
  Result := '';

  for i := 1 to l do
  begin
    n := n shl 5; 				// Move buffer left by 5 to make room

    p := Pos(UpperSource[i], ValidChars);
    if p >= 0 then
      n := n + (p - 1);         // Add value into buffer

    j := j + 5;				// Keep track of number of bits in buffer

    if (j >= 8) then
    begin
      j := j - 8;
      Result := Result + chr((n and ($FF shl j)) shr j);
    end;
  end;
end;


// Base32编码
function Base32Encode(str: UTF8String): string;
var
  B: Int64;
  i, j, len: Integer;
begin
  Result := '';
  //每5个字符一组进行编码(5个字符x8=40位,5位*8字符=40位,BASE32每个字符用5位表示)
  len := length(str);
  while len > 0 do
  begin
    if len >= 5 then
      len := 5;
    //将这5个字符的ASCII码按顺序存放到Int64(共8个字节)整数中
    B := 0;
    for i := 1 to len do
      B := B shl 8 + Ord(str[i]); //存放一个字符,左移一个字节(8位)
    B := B shl ((8 - len) * 8); //最后再左移3个字节(3*8)
    j := system.Math.ceil(len * 8 / 5);
    //编码,每5位表示一个字符,8个字符刚好是40位
    for i := 1 to 8 do
    begin
      if i <= j then
      begin
        Result := Result + ValidChars[B shr 59 + 1]; //右移7*8位+3位,从BASE32表中取字符
        B := B shl 5; //每次左移5位
      end
      else
        Result := Result + '=';
    end;
    //去掉已处理的5个字符
    delete(str, 1, len);
    len := length(str);
  end;
end;

使用する

おすすめ

転載: blog.csdn.net/warrially/article/details/103146664
おすすめ