使用Rijndael

时间:2017-12-07 09:41:12

标签: java c# encryption cryptography aes

我获得了一个Rijndael .Net加密文件和.Net RSA XML Key,并要求用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

1 个答案:

答案 0 :(得分:0)

您正在以错误的方式使用公钥。你真的了解C#程序是如何工作的吗?它使用什么参数?

您只是使用公钥位作为AES密钥(即使我不知道如何从中获取162个字节)。

这是"混合加密的例子" - 数据本身由随机AES密钥加密(在此声称它是256位),AES密钥(在这种情况下也是IV)由RSA公钥加密。在Java中有许多examples how to do that

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

参与参数 - 您正在使用PKCS5Padding,但检查.NET代码,它是不同的