简体   繁体   中英

Java AES/CBC/PKCS5Padding in C#

I have been give Java encryption code that needs to be converted to C#. I think I'm pretty close... but I'm not sure how to duplicate the IV calculation... any help?

Java Code:

    public static string getAESencodingResult(String sSrc, String encrypt_key)
    {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = encrypt_key.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(encrypt_key.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return new BASE64Encoder().encode(encrypted);
    }

C# Code:

    static string EncryptStringToBytes(string plainText, byte[] key)
    {
        byte[] encrypted;
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = key;
            // rijAlg.IV = ???
            rijAlg.GenerateIV();
            rijAlg.Padding = PaddingMode.PKCS7;
            rijAlg.Mode = CipherMode.CBC;
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
            using (MemoryStream msEncrypt = new MemoryStream())
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
            {

                swEncrypt.Write(plainText);
                if (plainText.Length < 16)
                {
                    for (int i = plainText.Length; i < 16; i++)
                        swEncrypt.Write((byte)0x0);
                }
                swEncrypt.Flush();
                csEncrypt.FlushFinalBlock();
                encrypted = msEncrypt.ToArray();
            }
        }
        return Convert.ToBase64String(encrypted);
    }

If I'm not misunderstanding the Java code, you simply need to assign the key value to the IV as well:

rijAlg.Key = key;
rijAlg.IV = key;

And remove the GenerateIV line:

rijAlg.GenerateIV();

I understand that you're not in control of the Java code so you can't fix this, but for future readers: you shouldn't use the same IV every time you encrypt something. See this question for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM