0
我必須解密一個以C#加密的字符串作爲我們項目的一部分。該解密使用AES算法和打包模式作爲PKCS7完成。爲了生成初始化向量,他們使用了以下內容:RFC2898DeriveBytes在Java中的實現
Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes("somestring", salt);
salt是默認字節。
此IV用於使用AES加密字符串。
我已經通讀了一些文檔,發現AES可以用Java實現。但不知道如何通過IV和包裝模式。
此外,我已經看到,有提及密碼塊模式的模式CBC,ECB。我不確定在C#中使用什麼模式。
下面是C#
/// Method to encrypt the plain text based on the key and Iv
/// </summary>
/// <param name="plainText"></param>
/// <param name="key"></param>
/// <returns>encrypted Text</returns>
private string Encrypt(string plainText, byte[] key)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the stream used to encrypt to an in memory
// array of bytes.
MemoryStream msEncrypt = null;
// Declare the RijndaelManaged object
// used to encrypt the data.
AesCryptoServiceProvider aesAlg = null;
// using (new Tracer("Encryption","",""))
// {
try
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new AesCryptoServiceProvider();
aesAlg.Key = key;
aesAlg.IV = GetInitializationVector();
aesAlg.Padding = PaddingMode.PKCS7;
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
msEncrypt = new MemoryStream();
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
// Console.WriteLine();
return Convert.ToBase64String(msEncrypt.ToArray());
// }
}
private byte[] GetInitializationVector()
{
byte[] iv;
//create the initial salt
byte[] salt = Encoding.Default.GetBytes("abcdefghijkl");
//create the key generator
Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes("ricksaw", salt);
iv = keyGenerator.GetBytes(16);
return iv;
}
任何一個可以幫助我在Java中創建等價的代碼?
'Rfc2898DeriveBytes'基於PBKDF2 – CodesInChaos 2012-02-21 12:03:11
那麼有沒有在java中的任何類實現PBKDF2 – VamsiKrishna 2012-02-21 12:06:33
@krish - 我不知道。你可以看一下'PBKDF2WithHmacSHA1',在java 6中添加。Re:* C#cipher模式* [默認是cbc](http://msdn.microsoft.com/en-us/library/system.security.cryptography .symmetricalgorithm.mode.aspx)。你還可以發佈你的Java代碼到目前爲止? – Leigh 2012-02-22 03:30:49