1

我正在使用在这里找到的 DCPcrypt 库。

这是一个加密字符串的小代码

InitializationVector: AnsiString;
const Key: Ansistring = 'keykeykeykey';
// Encrypt a string and return the Base64 encoded result
function Encrypt(DataToEncrypt: ansistring):ansistring;
var
  Cipher : TDCP_rijndael;
  Data: string;
  IV: array[0..15] of byte;      // the initialization vector
  i:Integer;
begin
  // Pad Key, IV and Data with zeros as appropriate
  FillChar(IV,Sizeof(IV),0);            // make the IV all zeros

  Data := PadWithZeros(DataToEncrypt,BlockSize);

  for i := 0 to (Length(IV) - 1) do   //just random values for the IV
    IV[i] := Random(256);

  Cipher := TDCP_rijndael.Create(nil);

  if Length(Key) <= 16 then
    Cipher.Init(Key[1],128,@IV[1])
  else if Length(Key) <= 24 then
    Cipher.Init(Key[1],192,@IV[1])
  else
    Cipher.Init(Key[1],256,@IV[1]);
  // Encrypt the data
  Cipher.EncryptCBC(Data[1],Data[1],Length(Data));
  // Free the cipher and clear sensitive information
  Cipher.Free;

  SetString(InitializationVector,PAnsiChar(@IV[1]),Length(IV));
  InitializationVector := Base64EncodeStr(InitializationVector);

  //Base64 encoded result
  Result := Base64EncodeStr(Data);
end;

我可以解密结果字符串,但只能解密一半。找到了一篇类似的帖子,但他在使用我正在做的 base64 编码密码时找到了答案。在这里

任何帮助表示赞赏!

4

1 回答 1

4

Delphi 2009/2010 和 XE 中的字符串默认为 Unicode 字符串。
这意味着单个字符可以占用 1 个或多个字节
你把旧AnsiString的代码放在代码中,但忘记了。

这意味着转换为 Unicode 会打乱您的解密,因为使用加密,即使是单个更改的位也会弄乱一切。

始终坚持使用 AnsiStrings,你应该没问题。

改变:

function Encrypt(DataToEncrypt: ansistring):ansistring;
var
  Cipher : TDCP_rijndael;
  Data: string;
  IV: array[0..15] of byte;      // the initialization vector
  i:Integer;
begin

// Encrypt a string and return the Base64 encoded result
function Encrypt(DataToEncrypt: AnsiString): AnsiString;
var
  Cipher: TDCP_rijndael;
  //Data: string; <<- change to ansistring
  Data: AnsiString;
  IV: array[0..15] of byte;      // the initialization vector
  i: Integer;
于 2011-04-26T21:05:07.770 回答