2012-06-29 74 views
0

我需要使用鹽和密鑰對字符串進行加密以匹配java加密,以便第三方提供者可以解密另一端的值。Rijndael或AES匹配java加密 - 使用salt和密鑰

我已經嘗試了幾個StackOverflow文章,因爲我不是加密專家,只是無法使用SALT和KEY作爲第三方提供者獲得相同的加密字符串。

我需要知道要使用的加密類型和模式在C#來匹配Java的AES加密這裏使用

https://gist.github.com/ca958d5921d47c4c0a0f

回答

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