簡體   English   中英

使用Rijndael在.Net中加密的Java解密文件時出錯

[英]Error while decrypting file in java which is encrypted in.Net using Rijndael

我得到了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中,有很多示例如何做到這一點

即使解密AES密鑰,您也應該知道用於加密它的參數(RSA / ECB / PKCS5Padding,RSA-AOEP等),盡管它應該位於XML內。

輸入參數-您正在使用PKCS5Padding ,但是檢查.NET代碼,則有所不同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM