public EncryptedKey encryptKey()

in src/main/java/org/apache/xml/security/encryption/XMLCipher.java [1337:1411]


    public EncryptedKey encryptKey(
        Document doc,
        Key key,
        String mgfAlgorithm,
        byte[] oaepParams,
        SecureRandom random
    ) throws XMLEncryptionException {
        LOG.log(Level.DEBUG, "Encrypting key ...");

        if (null == key) {
            throw new XMLEncryptionException("empty", "Key unexpectedly null...");
        }
        if (cipherMode != WRAP_MODE) {
            throw new XMLEncryptionException("empty", "XMLCipher unexpectedly not in WRAP_MODE...");
        }
        if (algorithm == null) {
            throw new XMLEncryptionException("empty", "XMLCipher instance without transformation specified");
        }

        contextDocument = doc;

        byte[] encryptedBytes = null;
        Cipher c;

        if (contextCipher == null) {
            // Now create the working cipher
            c = constructCipher(algorithm, null);
        } else {
            c = contextCipher;
        }
        // Now perform the encryption

        try {
            // Should internally generate an IV
            // todo - allow user to set an IV
            OAEPParameterSpec oaepParameters =
                constructOAEPParameters(
                    algorithm, digestAlg, mgfAlgorithm, oaepParams
                );
            if (random != null) {
                if (oaepParameters == null) {
                    c.init(Cipher.WRAP_MODE, this.key, random);
                } else {
                    c.init(Cipher.WRAP_MODE, this.key, oaepParameters, random);
                }
            } else {
                if (oaepParameters == null) {
                    c.init(Cipher.WRAP_MODE, this.key);
                } else {
                    c.init(Cipher.WRAP_MODE, this.key, oaepParameters);
                }
            }
            encryptedBytes = c.wrap(key);
        } catch (InvalidKeyException | IllegalBlockSizeException | InvalidAlgorithmParameterException e) {
            throw new XMLEncryptionException(e);
        }

        String base64EncodedEncryptedOctets = XMLUtils.encodeToString(encryptedBytes);
        LOG.log(Level.DEBUG, "Encrypted key octets:\n{0}", base64EncodedEncryptedOctets);
        LOG.log(Level.DEBUG, "Encrypted key octets length = {0}", base64EncodedEncryptedOctets.length());

        CipherValue cv = ek.getCipherData().getCipherValue();
        cv.setValue(base64EncodedEncryptedOctets);

        try {
            EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
            method.setDigestAlgorithm(digestAlg);
            method.setMGFAlgorithm(mgfAlgorithm);
            method.setOAEPparams(oaepParams);
            ek.setEncryptionMethod(method);
        } catch (URISyntaxException ex) {
            throw new XMLEncryptionException(ex);
        }
        return ek;
    }