Yair Landmann
Yair Landmann

Reputation: 69

Can`t decrypt correctly

We have used this encryption method that we have found here and this is it:

    public static byte[] Key = new byte[]{0x43, 0x72, 0x6e, 0x6d, 0x54, 0x4d, 0x65,
                                  0x94, 0x16, 0x32, 0x44, 0x84, 0x7e, 0x18,
                                  0x64, 0x76, 0x6e, 0x63, 0x64, 0x7a, 0x5f,
                                  0x84, 0x7f, 0x9a};

    public static byte[] Encrypt(byte[] data)
    {
        MemoryStream ms = new MemoryStream();
        Rijndael alg = Rijndael.Create();
        alg.Key = Key;
        CryptoStream cs = new CryptoStream(ms,
        alg.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(data, 0, data.Length);
        cs.Close();
        byte[] encryptedData = ms.ToArray();
        return encryptedData;
    }

when we decrypt it we used this function:

    public static byte[] Decrypt(byte[] data)
    {
        MemoryStream ms = new MemoryStream();
        Rijndael alg = Rijndael.Create();
        alg.Key = Key;
        CryptoStream cs = new CryptoStream(ms,
        alg.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(data, 0, data.Length);
        cs.Close();
        byte[] decryptedData = ms.ToArray();
        return decryptedData;
    }

as given here. we wrote a function to make sure that the byte array before encrypted is the same as the byte array after decrypted and it failled this test. what can be my problem?

Upvotes: 0

Views: 70

Answers (1)

ofcoursedude
ofcoursedude

Reputation: 456

You need to also save the Initialization Vector (IV) in the encryption phase and use it in the decryption phase. You can either use the IV that's created upon the algorithm object instantiation (in which case you need to save it somewhere so as you can reuse it), or specify your own in the same way as you specify the Key. See https://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.iv(v=vs.110).aspx for more details.

Upvotes: 1

Related Questions