2011-04-28 70 views
0

代碼我使用(XE):Rijndael加密。首先人物怪異

// Encrypt a string and return the Base64 encoded result 
function Encrypt(DataToEncrypt: ansistring):ansistring; 
const Key: Ansistring = 'keykey'; 
    KeySize = 32; // 32 bytes = 256 bits 
    BlockSize = 16; // 16 bytes = 128 bits 
var 
    Cipher : TDCP_rijndael; 
    Data: ansistring; 
    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)); //Save IV 
    InitializationVector := Base64EncodeStr(InitializationVector); 

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

function Decrypt(IV,Cryptogram:ansistring):ansistring; 
const Key: Ansistring = 'keykey'; 
    KeySize = 32; // 32 bytes = 256 bits 
    BlockSize = 16; // 16 bytes = 128 bits 
var 
    Cipher : TDCP_rijndael; 
begin 
    if IV='' then 
    IV := InitializationVector; 

    Cryptogram := Base64DecodeStr(cryptogram); 
    // Create the cipher and initialise according to the key length 
    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]); 
    // Decrypt the data 
    Cipher.DecryptCBC(cryptogram[1],cryptogram[1],Length(cryptogram)); 
    // Free the cipher and clear sensitive information 
    Cipher.Free; 
    // Display the result 
    Result := cryptogram; 
end; 

它工作得很好,只是當我嘗試解密串,我得到:

$ C#$ C'C」 #$B'ÛW'#$1F'Ø<™Ç'#$8D'Ž'#$ 8D'!'mydata

因此,前幾個字母變得非常怪異。其餘的解密就好! 找到類似的問題here,但沒有解決方案。 在此先感謝!

回答

5

第一件顯而易見的事情是,你正在閱讀/寫作超過IV的結尾。您將其聲明爲[0..15],但訪問元素1(!)之後的所有內容,包括Cipher.Init和SetString。

+0

另外,我忘了解碼64 IV!謝謝你的幫助 – Peacelyk 2011-05-11 18:57:06