Rijndael或AES匹配java加密 - 使用salt和key

时间:2012-06-29 10:29:08

标签: c# java aes rijndael

我需要使用salt和密钥加密字符串以匹配java加密,以便第三方提供程序可以解密另一方的值。

我已经尝试了几篇StackOverflow文章,因为我不是加密专家,只是无法使用SALT和KEY作为第三方提供商获得相同的加密字符串。

我需要知道C#中的哪种加密类型和模式用于匹配此处使用的java的AES加密

https://gist.github.com/ca958d5921d47c4c0a0f

1 个答案:

答案 0 :(得分:3)

好的 - 即使它在某种程度上作弊,我也弄明白了。因为我找不到任何与第三方提供的普通AES加密相匹配的加密技术,我要求他们将其更改为

Cipher cipher = Cipher.getInstance(“AES / CBC / PKCS5Padding”);

有了这个,我修改了我的C#代码,最后得到了集成工作:

public static string Encrypt2(string plainText)
    {
        string PassPhrase = "somepassphrase";
        string SaltValue = "somesalt";
        int PasswordIterations = 0; //amend to match java encryption iteration
        string InitVector = "someiv";
        int KeySize = 0; //amend to match java encryption key size

        byte[] initVectorBytes = Encoding.ASCII.GetBytes(InitVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue);

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(
                                                        PassPhrase,
                                                        saltValueBytes,
                                                        PasswordIterations);

        byte[] keyBytes = password.GetBytes(KeySize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;

        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                         keyBytes,
                                                         initVectorBytes);
        MemoryStream memoryStream = new MemoryStream();

        CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                     encryptor,
                                                     CryptoStreamMode.Write);

        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] cipherTextBytes = memoryStream.ToArray();

        memoryStream.Close();
        cryptoStream.Close();

        string cipherText = Convert.ToBase64String(cipherTextBytes);

        return cipherText;
    }