Hi,

I'm trying to use the WRAP.mode to use hybrid encryption. I have the following two functions for encrypting
and decrypting data:

When I use them like this:
Java Code:
byte[] ciphertext = secure.encrypt(plaintextstring.getBytes("UTF-8"), publicKey);

byte[] decrypted = secure.decrypt(ciphertext, privateKey);
I always get the error message:
java.security.InvalidKeyException: Unwrapping failed

Does anybody have an idea what is wrong with the code?

Java Code:
    public static byte[] encrypt(byte[] plainText, PublicKey publicKey)
    {
        byte[] data = null;

        try {
            // Create cipher object
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(random);    // Initialize with random data
            SecretKey key = keygen.generateKey();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipher.wrap(key);
            out.write(wrappedKey.length);
            out.write(wrappedKey);

            InputStream in = new ByteArrayInputStream(plainText);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipher);
            data = out.toByteArray();
            in.close();
            out.close();
        } catch (IOException e) {
            _logger.warning(e.getMessage());
        } catch (GeneralSecurityException e) {
            _logger.warning(e.getMessage());
        }

        return data;
    }

Java Code:
    public static byte[] decrypt(byte[] cipherText, PrivateKey privateKey)
    {
        byte[] data = null;

        try {
            ByteArrayInputStream in = new ByteArrayInputStream(cipherText);
            int length = in.read();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.UNWRAP_MODE, privateKey);
            Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);

            crypt(in, out, cipher);
            data = out.toByteArray();
            in.close();
            out.close();
        } catch (Exception e) {
            System.out.println(e);
       
        }

        return data;
    }