delphi Base32 的加密和解密  
官方Delphi 学习QQ群: 682628230(三千人)
频道

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

推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.051364898681641 seconds