【问题标题】:Java to C#.net - Encryption and decryption using AES with PasswordJava to C#.net - 使用带密码的 AES 进行加密和解密
【发布时间】:2018-12-18 00:52:15
【问题描述】:

我们有 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 函数都应该给我相同的结果。 从上周开始,我一直在努力完成它,完全沮丧。非常感谢您的帮助。

【问题讨论】:

    标签: java .net aes


    【解决方案1】:

    两种方法:

    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代码。

    【讨论】:

      猜你喜欢
      • 2014-01-14
      • 2021-04-27
      • 2011-04-26
      • 2013-04-19
      • 1970-01-01
      • 2015-10-22
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多