开发者

Rijndael encryption

i'm using DCPcrypt library found here.

Here is a little code to encrypt a string

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])
  el开发者_Go百科se
    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;

I can decrypt the resulted string, but only half of it. Found one similar post, but he found answer when encoding cryptogram with base64 which i'm doing. Here.

Any help is appreciated!


Strings in Delphi 2009/2010 and XE are Unicode strings by default.
This means that individual characters can take up 1 or more bytes.
You put good old AnsiString in the code, but forgot one.

This means that the translation to Unicode is messing up your decryption, since with encryption even a single changed bit will mess everything up.

Stick with AnsiStrings throughout and you should be fine.

Change:

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

to

// 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜