0

Guys i m doing a project in windows phone 8.i m trying to do aes encryption of a byte array into byte array using key and iv.Also passing the same key and iv in android and wp8.but not getting the same outputs.Whats wrong with my code??? please help me regarding this issue.

My C# aes encryption code is:

public static byte[] Encrypt (byte[] data, byte[] key) 
{
    byte[] encrypted;

    using (AesManaged AESM = new AesManaged())
    {
        byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        AESM.KeySize = 128;
        AESM.BlockSize = AESM.LegalBlockSizes[0].MaxSize;
        AESM.Key = key;
        AESM.IV = iv;

        ICryptoTransform encryptor = AESM.CreateEncryptor();

        encrypted = encryptor.TransformFinalBlock(data, 0, data.Length);
    }
    return encrypted;
}

My android aes encryption code is:

public static byte[] encryptAESWithIV(byte[] key, byte[] clearText) throws 
NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, 
InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, 
UnsupportedEncodingException 
{
    SecretKeySpec skeySpec = new SecretKeySpec(key, CIPHER_AES);

    Cipher cipher = Cipher.getInstance(CIPHER_AES_MODE);

    byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

    try 
    {
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv));
    }
    catch (InvalidAlgorithmParameterException e)
    {
        e.printStackTrace();
    }

    byte[] encrypted = cipher.doFinal(clearText);
    byte[] output = new byte[encrypted.length + iv.length];

    System.arraycopy(iv, 0, output, 0, iv.length);
    System.arraycopy(encrypted, 0, output, iv.length, encrypted.length);

    return output;
}
SynerCoder
  • 12,493
  • 4
  • 47
  • 78
bilal
  • 3
  • 1
  • 2
  • The problem might be that the block cipher mode used (e.g. ECB, CBC, CFB etc.) might be different between the two systems. – zindorsky Mar 26 '14 at 15:40
  • How can i add same cipher solution in C#???? Is there any way that i can get the same output in C#? – bilal Mar 26 '14 at 15:49
  • What do you mean by "cipher solution"? It sounds like you don't have much knowledge of basic crypto. Find a book, learn what block cipher modes are, and come back. – zindorsky Mar 26 '14 at 18:35
  • What is your CIPHER_AES_MODE? That string is typically specifying cipher, block mode and padding. – user515430 Mar 26 '14 at 18:52
  • I do not know much about cipher mode.Can you please tell me how to add it in my code???? thanks – bilal Mar 27 '14 at 11:54