QAES-AES加密支持单元

AES加密Delphi有很多实现,QAES也是抄自先烈们的实现,进行了二次封装,但将接口进一步简单化,让其更易用。

TQAES = record
  private
    FKey: QStringW;
    FMode: TQAESEncryptMode;
    FKeyType: TQAESKeyType;
    FInitVector: TQAESBuffer;
  public
    function AsECB(const AKey: QStringW;
      AKeyType: TQAESKeyType = kt256):PQAES; overload;
    function AsCBC(const AInitVector: TQAESBuffer; const AKey: QStringW;
      AKeyType: TQAESKeyType = kt256):PQAES; overload;
    procedure Encrypt(ASource, ADest: TStream); overload;
    procedure Encrypt(const p: Pointer; len: Integer;
      var AResult: TBytes); overload;
    procedure Encrypt(const AData: TBytes; var AResult: TBytes); overload;
    procedure Encrypt(const AData: QStringW; var AResult: TBytes); overload;
    procedure Encrypt(const ASourceFile, ADestFile: QStringW); overload;
    // 解密函数
    procedure Decrypt(ASource, ADest: TStream); overload;
    procedure Decrypt(const AData: TBytes; var AResult: TBytes); overload;
    function Decrypt(const AData: TBytes): String; overload;
    procedure Decrypt(const ASourceFile, ADestFile: QStringW); overload;
    property Key: QStringW read FKey write FKey;
    property Mode: TQAESEncryptMode read FMode;
    property KeyType: TQAESKeyType read FKeyType write FKeyType;
  end;

由于使用了记录(结构体)做为封装的基础,所以调用起来及其简洁:

var
  AES:TQAES;
...
//要加密,执行下面代码之一:
//1.ECB加密,默认加密位数
AES.AsECB(密钥).Encrypt(...);
//2.CBC加密,默认加密位数
AES.AsCBC(密钥,初始化向量).Encrypt(...)
...
//要解密,同样简单
//1.ECB解密
AES.AsECB(密钥).Decrypt(...)
//2.CBC解密
AES.AsCBC(密钥,初始化向量).Decrypt(...)

 

分享到: