2011-04-28 5 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'Ç ' # $ B'UW '# $ 1F'Ø <Ç'# $ 8D'Ž '$ 8D'! 'mydata

이렇게 처음 몇 글자는 매우 이상한 문자가납니다. 그것의 나머지는 잘 해독됩니다! 비슷한 문제가 발견 되었으나 해결책이 없습니다. here 미리 감사드립니다.

답변

5

저에게 두드러지는 첫 번째 점은 당신이 IV의 끝을 지나서 읽고 쓰고 있다는 것입니다. [0..15]로 선언하지만 Cipher.Init와 SetString에서 요소 1 (!)부터 모든 것을 액세스합니다.

+0

또한, 나는 decode64 IV를 잊어 버렸습니다! 당신의 도움을 주셔서 감사합니다 – Peacelyk