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 新建文件夹函数

Delphi 新增功能之: ioutils 单元(7): tfile 结构的功能

Delphi 如何将颜色值转换为灰度颜色值?

Delphi 判断字符串是否为纯字母组合

Delphi 用注册表对Delphi程序进行验证

Delphi 中相对路径与绝对路径、系统环境变量等相关函数说明

Delphi idhttp 获取链接连通状态

Delphi writeln 写入一行文本

Delphi idftp连不上ftp服务器的解决方法

Delphi ios 保持设备开机状态

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



打赏

取消

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

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

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

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

评论

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