使用C#中的AESManaged进行AES加密

时间:2014-03-26 15:05:56

标签: c# java android encryption windows-phone-8

伙计们我在windows phone 8.in做一个项目尝试使用密钥和iv对字节数组进行字节数组加密。同时在android和wp8中传递相同的密钥和iv。但是没有得到相同的输出。我的代码怎么了?请帮我解决这个问题。

我的C#aes加密代码是:

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;
}

我的android安卓加密代码是:

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;
}