使用Rijndael解密在.Net中加密的Java中的文件时出错 - java

我得到了Rijndael .Net加密文件和.Net RSA XML密钥,并要求用Java对其解密。

提供给我的密钥是256位。

我已经解析了RSA XML文件并用Java生成了公共密钥。我尝试使用生成的密钥进行解密,但是我收到了异常Illegal Key Size,我认为我的Java代码做错了什么。

任何人都可以帮助检查我的代码是否有问题吗?

.Net加密代码:

public static void EncryptFile(string fileIn, string fileOut,
                                   string publicKeyName, string publicKeyFile)
    {
        try
        {
            // Read the public key from key file
            StreamReader sr = new StreamReader(publicKeyFile);
            string strKeyText = sr.ReadToEnd();
            sr.Close();

            //Initialize Key container and Crypto service provider
            RSACryptoServiceProvider rsa;
            CspParameters cspp = new CspParameters();
            cspp.KeyContainerName = publicKeyName;
            rsa = new RSACryptoServiceProvider(cspp);
            rsa.FromXmlString(strKeyText);
            rsa.PersistKeyInCsp = true;

            // Create instance of Rijndael for
            // symetric encryption of the data.
            RijndaelManaged alg = new RijndaelManaged();
            // Key size is set to 256 for strong encryption
            alg.KeySize = 256;
            alg.BlockSize = 256;
            // Cipher Mode is set to CBC to process the file in chunks
            alg.Mode = CipherMode.CBC;
            // Set padding mode to process the last block of the file
            alg.Padding = PaddingMode.ISO10126;

            ICryptoTransform transform = alg.CreateEncryptor();

            // Use RSACryptoServiceProvider to
            // enrypt the Rijndael key.
            byte[] KeyEncrypted = rsa.Encrypt(alg.Key, false);

            // Create byte arrays to contain
            // the length values of the key and IV.
            int intKeyLength = KeyEncrypted.Length;
            byte[] LenK = BitConverter.GetBytes(intKeyLength);
            int intIVLength = alg.IV.Length;
            byte[] LenIV = BitConverter.GetBytes(intIVLength);


            using (FileStream fsOut = new FileStream(fileOut, FileMode.Create))
            {
                // Write the following to the FileStream
                // for the encrypted file (fsOut):
                // - length of the key
                // - length of the IV
                // - ecrypted key
                // - the IV
                // - the encrypted cipher content
                fsOut.Write(LenK, 0, 4);
                fsOut.Write(LenIV, 0, 4);
                fsOut.Write(KeyEncrypted, 0, intKeyLength);
                fsOut.Write(alg.IV, 0, intIVLength);

                // Now write the cipher text using
                // a CryptoStream for encrypting.
                using (CryptoStream cs = new CryptoStream(fsOut, transform, CryptoStreamMode.Write))
                {
                    // intBlockSizeBytes can be any arbitrary size.
                    int intBlockSizeBytes = alg.BlockSize / 8;
                    byte[] DataBytes = new byte[intBlockSizeBytes];
                    int intBytesRead = 0;

                    using (FileStream fsIn = new FileStream(fileIn, FileMode.Open))
                    {
                        // By encrypting a chunk at
                        // a time, you can save memory
                        // and accommodate large files.
                        int intCount;
                        int intOffset = 0;

                        do
                        {
                            // if last block size is less than encryption chunk size
                            // use the last block size and padding character is used 
                            // for remaining bytes
                            if (intBlockSizeBytes > (fsIn.Length - fsIn.Position))
                            {
                                intBlockSizeBytes = ((int)(fsIn.Length - fsIn.Position));
                                DataBytes = new byte[intBlockSizeBytes];
                            }
                            // read data bytes
                            intCount = fsIn.Read(DataBytes, 0, intBlockSizeBytes);
                            intOffset += intCount;
                            // write it into crypto stream
                            cs.Write(DataBytes, 0, intCount);
                            intBytesRead += intBlockSizeBytes;
                        } while (intCount > 0);
                        // close input file
                        fsIn.Close();
                    }
                    // close crypto stream
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                // close output file
                fsOut.Close();
            }
        }
        catch
        {
            throw;
        }
    }

我写来解密的Java代码:

    byte[] expBytes = Base64.decodeBase64(pkey.getExponentEle().trim());
    byte[] modBytes = Base64.decodeBase64(pkey.getModulusEle().trim());
    byte[] dBytes = Base64.decodeBase64(pkey.getdEle().trim());

    BigInteger modules = new BigInteger(1, modBytes);
    BigInteger exponent = new BigInteger(1, expBytes);
    BigInteger d = new BigInteger(1, dBytes);

    KeyFactory factory = KeyFactory.getInstance("RSA");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(modules, exponent);
    PublicKey pubKey = factory.generatePublic(pubSpec);

    final byte[] keyData = Arrays.copyOf(pubKey.getEncoded(), 256
            / Byte.SIZE);
        final byte[] ivBytes = Arrays.copyOf(keyData, cipher.getBlockSize());
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivBytes);

        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyData, "AES"), paramSpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    System.out.println("decrypted: " + new String(decrypted));

如果将密码初始化更改为cipher.init(Cipher.DECRYPT_MODE, pubKey);,则出现错误Invalid AES key length: 162 bytes

参考方案

您使用公钥的方式错误。您是否真的了解C#程序的工作原理?它使用什么参数?

您只是将公共密钥位用作AES密钥(即使我不太了解如何从中获取162个字节)。

这是“混合加密”的示例-数据本身由随机AES密钥(在此您声明为256位)加密,而AES密钥(在本例中为IV)也由RSA公钥加密。在Java中,有许多examples how to do that。

即使解密AES密钥,您也应该知道用于加密它的参数(RSA / ECB / PKCS5Padding,RSA-AOEP等),尽管它应该位于XML内。

输入参数-您正在使用PKCS5Padding,但是请检查.NET代码,这是不同的

JAVA:字节码和二进制有什么区别? - java

java字节代码(已编译的语言,也称为目标代码)与机器代码(当前计算机的本机代码)之间有什么区别?我读过一些书,他们将字节码称为二进制指令,但我不知道为什么。 参考方案 字节码是独立于平台的,在Windows中运行的编译器编译的字节码仍将在linux / unix / mac中运行。机器代码是特定于平台的,如果在Windows x86中编译,则它将仅在Win…

java:继承 - java

有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…

Java:BigInteger,如何通过OutputStream编写它 - java

我想将BigInteger写入文件。做这个的最好方式是什么。当然,我想从输入流中读取(使用程序,而不是人工)。我必须使用ObjectOutputStream还是有更好的方法?目的是使用尽可能少的字节。谢谢马丁 参考方案 Java序列化(ObjectOutputStream / ObjectInputStream)是将对象序列化为八位字节序列的一种通用方法。但…

Java-如何将此字符串转换为日期? - java

我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…

Java:从类中查找项目名称 - java

仅通过类的实例,如何使用Java反射或类似方法查找项目名称?如果不是,项目名称(我真正想要的是)可以找到程序包名称吗? 参考方案 项目只是IDE使用的简单组织工具,因此项目名称不是类或JVM中包含的信息。要获取软件包,请使用Class#getPackage()。然后,可以调用Package#getName()将包作为您在代码的包声明中看到的String来获取…