RFC2898DeriveBytes implementation in Java

对着背影说爱祢 提交于 2019-12-06 17:30:56

问题


I have to decrypt a string encrypted in C# as a part of our project. This decryption is done using AES algorithm and packing mode as PKCS7. For generating the initialization vector they have used the following:

Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes("somestring", salt);

The salt is the default bytes.

This IV is used in encrypting the string using AES.

I have read through some documents and found that AES can be implemented in Java. But not sure on how to pass the IV and packing mode.

Also, I have seen that there are modes CBC, ECB for mentioning the Cipher block mode. I am not sure what mode is used in C# counterpart.

Below is the code in 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;
}

Can any one help me to create the equivalent in Java?


回答1:


i have somehow figured a way. it was working properly

I have requested the .net counterpart to pass the key and IV as strings. I encoded them to byte[] and used the below code

 String sKey ="fromdotnetpart";

 String sIv="fromdotnetiv";

    byte[] bKey = key.getBytes();
    byte[] iv = sIv.getBytes();
    SecretKeySpec skey = new SecretKeySpec(bKey, "AES");   
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    AlgorithmParameterSpec param = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, key,param);
    String decrypted = cipher.doFinal(encryptedString.getByte());

Hope this helps you. Please note that for higher strength AES encryption i.e AES-256,192 etc You need to download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files



来源:https://stackoverflow.com/questions/9375004/rfc2898derivebytes-implementation-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!