Search in sources :

Example 26 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project j2objc by google.

the class OAEPParameterSpecTest method testGetMGFAlgorithm.

/**
 * getMGFAlgorithm() method testing.
 */
public void testGetMGFAlgorithm() {
    String mdName = "SHA-1";
    String mgfName = "MGF1";
    AlgorithmParameterSpec mgfSpec = MGF1ParameterSpec.SHA1;
    PSource pSrc = PSource.PSpecified.DEFAULT;
    OAEPParameterSpec ps = new OAEPParameterSpec(mdName, mgfName, mgfSpec, pSrc);
    assertTrue("The returned value does not equal to the " + "value specified in the constructor.", ps.getMGFAlgorithm().equals(mgfName));
}
Also used : PSource(javax.crypto.spec.PSource) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec)

Example 27 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project keycloak by keycloak.

the class RsaKeyEncryption256JWEAlgorithmProvider method decodeCek.

@Override
public byte[] decodeCek(byte[] encodedCek, Key privateKey) throws Exception {
    AlgorithmParameters algp = AlgorithmParameters.getInstance("OAEP");
    AlgorithmParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
    algp.init(paramSpec);
    Cipher cipher = getCipherProvider();
    cipher.init(Cipher.DECRYPT_MODE, privateKey, algp);
    return cipher.doFinal(encodedCek);
}
Also used : Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) AlgorithmParameters(java.security.AlgorithmParameters) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec)

Example 28 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project keycloak by keycloak.

the class RsaKeyEncryption256JWEAlgorithmProvider method encodeCek.

@Override
public byte[] encodeCek(JWEEncryptionProvider encryptionProvider, JWEKeyStorage keyStorage, Key publicKey) throws Exception {
    AlgorithmParameters algp = AlgorithmParameters.getInstance("OAEP");
    AlgorithmParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
    algp.init(paramSpec);
    Cipher cipher = getCipherProvider();
    cipher.init(Cipher.ENCRYPT_MODE, publicKey, algp);
    byte[] cekBytes = keyStorage.getCekBytes();
    return cipher.doFinal(cekBytes);
}
Also used : Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) AlgorithmParameters(java.security.AlgorithmParameters) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec)

Example 29 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project santuario-java by apache.

the class XMLEncryptOutputProcessor method createInternalEncryptionOutputProcessor.

/**
 * Override this method to return a different AbstractInternalEncryptionOutputProcessor instance
 * which will write out the KeyInfo contents in the EncryptedData.
 */
protected AbstractInternalEncryptionOutputProcessor createInternalEncryptionOutputProcessor(EncryptionPartDef encryptionPartDef, XMLSecStartElement startElement, String encoding, final OutboundSecurityToken keyWrappingToken) throws XMLStreamException, XMLSecurityException {
    final AbstractInternalEncryptionOutputProcessor processor = new AbstractInternalEncryptionOutputProcessor(encryptionPartDef, startElement, encoding) {

        @Override
        protected void createKeyInfoStructure(OutputProcessorChain outputProcessorChain) throws XMLStreamException, XMLSecurityException {
            if (keyWrappingToken == null) {
                // Do not write out a KeyInfo element
                return;
            }
            final String encryptionKeyTransportAlgorithm = getSecurityProperties().getEncryptionKeyTransportAlgorithm();
            PublicKey pubKey = keyWrappingToken.getPublicKey();
            Key secretKey = keyWrappingToken.getSecretKey(encryptionKeyTransportAlgorithm);
            if (pubKey == null && secretKey == null) {
                // Do not write out a KeyInfo element
                return;
            }
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, true, null);
            List<XMLSecAttribute> attributes = new ArrayList<>(1);
            String keyId = IDGenerator.generateID("EK");
            attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Id, keyId));
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey, true, attributes);
            attributes = new ArrayList<>(1);
            attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportAlgorithm));
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptionMethod, false, attributes);
            final String encryptionKeyTransportDigestAlgorithm = getSecurityProperties().getEncryptionKeyTransportDigestAlgorithm();
            final String encryptionKeyTransportMGFAlgorithm = getSecurityProperties().getEncryptionKeyTransportMGFAlgorithm();
            if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm) || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) {
                byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams();
                if (oaepParams != null) {
                    createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_OAEPparams, false, null);
                    createCharactersAndOutputAsEvent(outputProcessorChain, Base64.getMimeEncoder().encodeToString(oaepParams));
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_OAEPparams);
                }
                if (encryptionKeyTransportDigestAlgorithm != null) {
                    attributes = new ArrayList<>(1);
                    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportDigestAlgorithm));
                    createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod, true, attributes);
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod);
                }
                if (encryptionKeyTransportMGFAlgorithm != null) {
                    attributes = new ArrayList<>(1);
                    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportMGFAlgorithm));
                    createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc11_MGF, true, attributes);
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc11_MGF);
                }
            }
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptionMethod);
            createKeyInfoStructureForEncryptedKey(outputProcessorChain, keyWrappingToken);
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData, false, null);
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue, false, null);
            // encrypt the symmetric session key with the public key from the receiver:
            String jceid = JCEAlgorithmMapper.translateURItoJCEID(encryptionKeyTransportAlgorithm);
            if (jceid == null) {
                throw new XMLSecurityException("algorithms.NoSuchMap", new Object[] { encryptionKeyTransportAlgorithm });
            }
            try {
                Cipher cipher = Cipher.getInstance(jceid);
                AlgorithmParameterSpec algorithmParameterSpec = null;
                if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm) || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) {
                    String jceDigestAlgorithm = "SHA-1";
                    if (encryptionKeyTransportDigestAlgorithm != null) {
                        jceDigestAlgorithm = JCEAlgorithmMapper.translateURItoJCEID(encryptionKeyTransportDigestAlgorithm);
                    }
                    PSource.PSpecified pSource = PSource.PSpecified.DEFAULT;
                    byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams();
                    if (oaepParams != null) {
                        pSource = new PSource.PSpecified(oaepParams);
                    }
                    MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
                    if (encryptionKeyTransportMGFAlgorithm != null) {
                        String jceMGFAlgorithm = JCEAlgorithmMapper.translateURItoJCEID(encryptionKeyTransportMGFAlgorithm);
                        mgfParameterSpec = new MGF1ParameterSpec(jceMGFAlgorithm);
                    }
                    algorithmParameterSpec = new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource);
                }
                if (pubKey != null) {
                    cipher.init(Cipher.WRAP_MODE, pubKey, algorithmParameterSpec);
                } else {
                    cipher.init(Cipher.WRAP_MODE, secretKey, algorithmParameterSpec);
                }
                String tokenId = outputProcessorChain.getSecurityContext().get(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION);
                SecurityTokenProvider<OutboundSecurityToken> securityTokenProvider = outputProcessorChain.getSecurityContext().getSecurityTokenProvider(tokenId);
                final OutboundSecurityToken securityToken = securityTokenProvider.getSecurityToken();
                Key sessionKey = securityToken.getSecretKey(getSecurityProperties().getEncryptionSymAlgorithm());
                if (pubKey != null) {
                    int blockSize = cipher.getBlockSize();
                    if (blockSize > 0 && blockSize < sessionKey.getEncoded().length) {
                        throw new XMLSecurityException("stax.unsupportedKeyTransp");
                    }
                }
                byte[] encryptedEphemeralKey = cipher.wrap(sessionKey);
                createCharactersAndOutputAsEvent(outputProcessorChain, Base64.getMimeEncoder().encodeToString(encryptedEphemeralKey));
            } catch (NoSuchPaddingException e) {
                throw new XMLSecurityException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new XMLSecurityException(e);
            } catch (InvalidKeyException e) {
                throw new XMLSecurityException(e);
            } catch (IllegalBlockSizeException e) {
                throw new XMLSecurityException(e);
            } catch (InvalidAlgorithmParameterException e) {
                throw new XMLSecurityException(e);
            }
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue);
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData);
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey);
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
        }

        protected void createKeyInfoStructureForEncryptedKey(OutputProcessorChain outputProcessorChain, OutboundSecurityToken securityToken) throws XMLStreamException, XMLSecurityException {
            SecurityTokenConstants.KeyIdentifier keyIdentifier = getSecurityProperties().getEncryptionKeyIdentifier();
            X509Certificate[] x509Certificates = securityToken.getX509Certificates();
            if (x509Certificates == null) {
                if (securityToken.getPublicKey() != null && SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) {
                    createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, true, null);
                    XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain, securityToken.getPublicKey());
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
                }
                return;
            }
            if (!SecurityTokenConstants.KeyIdentifier_NoKeyInfo.equals(keyIdentifier)) {
                createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, true, null);
                if (keyIdentifier == null || SecurityTokenConstants.KeyIdentifier_IssuerSerial.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509IssuerSerialStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) {
                    XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_SkiKeyIdentifier.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509SubjectKeyIdentifierStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509CertificateStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_X509SubjectName.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509SubjectNameStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_KeyName.equals(keyIdentifier)) {
                    String keyName = getSecurityProperties().getEncryptionKeyName();
                    XMLSecurityUtils.createKeyNameTokenStructure(this, outputProcessorChain, keyName);
                } else {
                    throw new XMLSecurityException("stax.unsupportedToken", new Object[] { keyIdentifier });
                }
                createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
            }
        }
    };
    processor.getAfterProcessors().add(XMLEncryptOutputProcessor.class.getName());
    return processor;
}
Also used : ArrayList(java.util.ArrayList) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) OutboundSecurityToken(org.apache.xml.security.stax.securityToken.OutboundSecurityToken) XMLSecAttribute(org.apache.xml.security.stax.ext.stax.XMLSecAttribute) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) SecurityTokenConstants(org.apache.xml.security.stax.securityToken.SecurityTokenConstants) PSource(javax.crypto.spec.PSource) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) X509Certificate(java.security.cert.X509Certificate) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec) Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) MGF1ParameterSpec(java.security.spec.MGF1ParameterSpec)

Example 30 with OAEPParameterSpec

use of javax.crypto.spec.OAEPParameterSpec in project santuario-java by apache.

the class XMLCipher method decryptKey.

/**
 * Decrypt a key from a passed in EncryptedKey structure
 *
 * @param encryptedKey Previously loaded EncryptedKey that needs
 * to be decrypted.
 * @param algorithm Algorithm for the decrypted key
 * @return a key corresponding to the given type
 * @throws XMLEncryptionException
 */
public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws XMLEncryptionException {
    LOG.debug("Decrypting key from previously loaded EncryptedKey...");
    if (cipherMode != UNWRAP_MODE) {
        throw new XMLEncryptionException("empty", "XMLCipher unexpectedly not in UNWRAP_MODE...");
    }
    if (algorithm == null) {
        throw new XMLEncryptionException("empty", "Cannot decrypt a key without knowing the algorithm");
    }
    if (key == null) {
        LOG.debug("Trying to find a KEK via key resolvers");
        KeyInfo ki = encryptedKey.getKeyInfo();
        if (ki != null) {
            ki.setSecureValidation(secureValidation);
            try {
                String keyWrapAlg = encryptedKey.getEncryptionMethod().getAlgorithm();
                String keyType = JCEMapper.getJCEKeyAlgorithmFromURI(keyWrapAlg);
                if ("RSA".equals(keyType) || "EC".equals(keyType)) {
                    key = ki.getPrivateKey();
                } else {
                    key = ki.getSecretKey();
                }
            } catch (Exception e) {
                LOG.debug(e.getMessage(), e);
            }
        }
        if (key == null) {
            LOG.error("XMLCipher::decryptKey called without a KEK and cannot resolve");
            throw new XMLEncryptionException("empty", "Unable to decrypt without a KEK");
        }
    }
    // Obtain the encrypted octets
    XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey);
    cipherInput.setSecureValidation(secureValidation);
    byte[] encryptedBytes = cipherInput.getBytes();
    String jceKeyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(algorithm);
    LOG.debug("JCE Key Algorithm: {}", jceKeyAlgorithm);
    Cipher c;
    if (contextCipher == null) {
        // Now create the working cipher
        c = constructCipher(encryptedKey.getEncryptionMethod().getAlgorithm(), encryptedKey.getEncryptionMethod().getDigestAlgorithm());
    } else {
        c = contextCipher;
    }
    Key ret;
    try {
        EncryptionMethod encMethod = encryptedKey.getEncryptionMethod();
        OAEPParameterSpec oaepParameters = constructOAEPParameters(encMethod.getAlgorithm(), encMethod.getDigestAlgorithm(), encMethod.getMGFAlgorithm(), encMethod.getOAEPparams());
        if (oaepParameters == null) {
            c.init(Cipher.UNWRAP_MODE, key);
        } else {
            c.init(Cipher.UNWRAP_MODE, key, oaepParameters);
        }
        ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException(ike);
    } catch (NoSuchAlgorithmException nsae) {
        throw new XMLEncryptionException(nsae);
    } catch (InvalidAlgorithmParameterException e) {
        throw new XMLEncryptionException(e);
    }
    LOG.debug("Decryption of key type {} OK", algorithm);
    return ret;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) URISyntaxException(java.net.URISyntaxException) TransformationException(org.apache.xml.security.transforms.TransformationException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) KeyResolverException(org.apache.xml.security.keys.keyresolver.KeyResolverException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidTransformException(org.apache.xml.security.transforms.InvalidTransformException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec) KeyInfo(org.apache.xml.security.keys.KeyInfo) Cipher(javax.crypto.Cipher) Key(java.security.Key)

Aggregations

OAEPParameterSpec (javax.crypto.spec.OAEPParameterSpec)34 PSource (javax.crypto.spec.PSource)19 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)15 MGF1ParameterSpec (java.security.spec.MGF1ParameterSpec)11 Cipher (javax.crypto.Cipher)10 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)6 InvalidKeyException (java.security.InvalidKeyException)6 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)6 URISyntaxException (java.net.URISyntaxException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 InvalidParameterSpecException (java.security.spec.InvalidParameterSpecException)4 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)4 AlgorithmParameters (java.security.AlgorithmParameters)3 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 URI (java.net.URI)2 InvalidParameterException (java.security.InvalidParameterException)2 Key (java.security.Key)2 NoSuchProviderException (java.security.NoSuchProviderException)2 SecureRandom (java.security.SecureRandom)2