Java到C#.net-使用带有密码的AES进行加密和解密

时间:2018-07-10 08:42:29

标签: java .net aes

我们有一个Java库,该库将使用带有密码的AES进行加密和解密,我们需要将其移植到.NET。

这是我的Java代码-

import java.util.*;
import java.lang.*;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

class Rextester
{  
    public static void main(String args[])
    {
        byte[] encrypted = EncryptonToBytes("Hello");
        System.out.println("Encrypted: " + encrypted); // Result --> Encrypted: [B@1c53fd30
        String decrypted = DecryptionFromBytes(encrypted);
        System.out.println("Decrypted: " + decrypted);
    }

    public static final byte[] EncryptonToBytes(String str)
    {
        byte[] result = null; 

        //Create SecretKey object from common secret key string mentioned in constants class
        byte[] encoded = new BigInteger("728faf34b64cd55c8d1d500268026ffb", 16).toByteArray();
        SecretKey secretKey = new SecretKeySpec(encoded, "AES");

        Cipher cipher;
        try {
            //Cipher class object using AES as transformation
            cipher = Cipher.getInstance("AES");

            //Initialize cipher in encrypt mode along with secret key object created above.
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            //Encrypt input string
            result = cipher.doFinal(str.getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        } 

        //Return null in case of any error
        return result;
    }

    public static String DecryptionFromBytes(byte[] base64Data) 
    {       
        try {
            //Create SecretKey object from common secret key string mentioned in constants class
            byte[] encoded = new BigInteger("728faf34b64cd55c8d1d500268026ffb", 16).toByteArray();
            SecretKey secretKey = new SecretKeySpec(encoded, "AES");

            //Cipher class object using AES as transformation
            Cipher cipher = Cipher.getInstance("AES");

            //Initialize cipher in decrypt mode along with secret key object created above.
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            //Decrypt input byte array
            byte[] decryptedByte = cipher.doFinal(base64Data);

            //return decrypted input bytes as string
            return (new String(decryptedByte));
        } catch (Exception e) {
            e.printStackTrace();
        } 

        //return empty string if any error 
        return "";
    }
}

我关注了以下一些文章-

  1. Using AES encryption in C#
  2. http://csharphelper.com/blog/2014/09/encrypt-or-decrypt-files-in-c/
  3. https://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt
  4. Cipher, Java encrypt, C# decrypt
  5. Password encryption/decryption code in .NET
  6. https://ourcodeworld.com/articles/read/471/how-to-encrypt-and-decrypt-files-using-the-aes-encryption-algorithm-in-c-sharp
  7. http://mjremijan.blogspot.com/2014/08/aes-encryption-between-java-and-c.html

但是他们都没有给我想要的输出。我正在寻找的是-我的java和.net函数都应该给我相同的结果。 从上周开始,我一直在努力完成它,这让我非常沮丧。您的帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

两种方法:

public static byte[] EncryptionToBytes(string str)
{
    using (var aes = new AesManaged())
    {
        aes.Key = new byte[] { 0x72, 0x8f, 0xaf, 0x34, 0xb6, 0x4c, 0xd5, 0x5c, 0x8d, 0x1d, 0x50, 0x02, 0x68, 0x02, 0x6f, 0xfb };
        aes.Mode = CipherMode.ECB;
        aes.Padding = PaddingMode.PKCS7;

        using (var ms = new MemoryStream())
        {
            using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                byte[] data = Encoding.UTF8.GetBytes(str);
                cs.Write(data, 0, data.Length);
            }

            byte[] encrypted = ms.ToArray();
            return encrypted;
        }
    }
}

public static string DecryptionFromBytes(byte[] encrypted)
{
    using (var aes = new AesManaged())
    {
        aes.Key = new byte[] { 0x72, 0x8f, 0xaf, 0x34, 0xb6, 0x4c, 0xd5, 0x5c, 0x8d, 0x1d, 0x50, 0x02, 0x68, 0x02, 0x6f, 0xfb };
        aes.Mode = CipherMode.ECB;
        aes.Padding = PaddingMode.PKCS7;

        using (var ms2 = new MemoryStream())
        {
            using (var ms = new MemoryStream(encrypted))
            using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
            {
                cs.CopyTo(ms2);
            }

            byte[] decrypted = ms2.ToArray();
            return Encoding.UTF8.GetString(decrypted);
        }
    }
}

请注意

System.out.println("Encrypted: " + encrypted);

不会打印byte[],但会打印print [, followed by a character representing the type of the array's elements (in your case C for char), followed by @ then the "identity hash code" of the array (think of it like you would a "memory address")

Java似乎使用了ECB模式的AES(没有查找文档),填充了PKCS7(this证实了我的看法)

请注意,String.getBytes()使用“默认”编码进行编码,这在不同计算机上可能会有所不同。最好使用getBytes("UTF-8")new String(bytes, "UTF-8")(请参阅https://stackoverflow.com/a/5729823/613130)。在我编写的代码中,我使用了UTF8。您可以使用Encoding.Default模拟Java代码。