Delphi Base32 的加密和解密


本文整理自网络,侵删。

 
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;

――――――――――――――――

原文链接:https://blog.csdn.net/warrially/article/details/103146664

相关阅读 >>

Delphi取cpu利用率

Delphi 检测服务器地址是否有效

Delphi 如何在richedit控件里加入链接

Delphi基于高斯-拉普拉斯算子的图像边缘检测

Delphi 串口常用的字符串转换函数

Delphi字符串反转函数

常用的几个网络函数和系统函数

Delphi richedit根据鼠标位置定位光标的方法

Delphi 蜂鸣器发声

Delphi 获取文件的最新修改时间

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...