Example usage for java.security Key getEncoded

List of usage examples for java.security Key getEncoded

Introduction

In this page you can find the example usage for java.security Key getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Returns a {@code SubjectKeyIdentifier} for the received {@code Key}.
 *
 * @param key//from   ww  w .j  av  a2s.com
 *            the key for generating the identifier
 * @return a {@code SubjectKeyIdentifier} for the received {@code Key}
 * @throws IOException
 *             if any problem occurs while reading the key
 */
private final SubjectKeyIdentifier createSubjectKeyIdentifier(final Key key) throws IOException {
    final ASN1Sequence seq; // Sequence for the key info
    ASN1InputStream stream = null; // Stream for reading the key

    try {
        stream = new ASN1InputStream(new ByteArrayInputStream(key.getEncoded()));
        seq = (ASN1Sequence) stream.readObject();
    } finally {
        IOUtils.closeQuietly(stream);
    }

    return new BcX509ExtensionUtils().createSubjectKeyIdentifier(new SubjectPublicKeyInfo(seq));
}

From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java

/**
 * Generates an AES key from the password using PBKDF2.
 *
 * @param salt the salt/*from   w  w w.  ja  va  2s  . c  om*/
 */
protected Key generateSecretKey(byte[] salt) throws GeneralSecurityException {
    char[] password = getPassword();
    SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF2_WITH_HMAC_SHA1);
    PBEKeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, PBKDF2_KEY_LENGTH);
    clearPassword(password);
    Key derived = factory.generateSecret(spec);
    spec.clearPassword();
    return new SecretKeySpec(derived.getEncoded(), AES);
}

From source file:org.apache.xml.security.stax.impl.processor.output.AbstractSignatureEndingOutputProcessor.java

@Override
public void processHeaderEvent(OutputProcessorChain outputProcessorChain)
        throws XMLStreamException, XMLSecurityException {

    OutputProcessorChain subOutputProcessorChain = outputProcessorChain.createSubChain(this);

    List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1);
    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Id, IDGenerator.generateID(null)));
    XMLSecStartElement signatureElement = createStartElementAndOutputAsEvent(subOutputProcessorChain,
            XMLSecurityConstants.TAG_dsig_Signature, true, attributes);

    SignatureAlgorithm signatureAlgorithm;
    try {//from  ww w.  j  a  v a 2 s .co m
        signatureAlgorithm = SignatureAlgorithmFactory.getInstance()
                .getSignatureAlgorithm(getSecurityProperties().getSignatureAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        throw new XMLSecurityException(e);
    } catch (NoSuchProviderException e) {
        throw new XMLSecurityException(e);
    }

    String tokenId = outputProcessorChain.getSecurityContext()
            .get(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE);
    if (tokenId == null) {
        throw new XMLSecurityException("stax.keyNotFound");
    }
    SecurityTokenProvider<OutboundSecurityToken> wrappingSecurityTokenProvider = outputProcessorChain
            .getSecurityContext().getSecurityTokenProvider(tokenId);
    if (wrappingSecurityTokenProvider == null) {
        throw new XMLSecurityException("stax.keyNotFound");
    }
    final OutboundSecurityToken wrappingSecurityToken = wrappingSecurityTokenProvider.getSecurityToken();
    if (wrappingSecurityToken == null) {
        throw new XMLSecurityException("stax.keyNotFound");
    }

    String sigAlgorithm = getSecurityProperties().getSignatureAlgorithm();
    Key key = wrappingSecurityToken.getSecretKey(sigAlgorithm);
    //todo remove and use wrappingSecurityToken.isSymmetric or so?
    if (XMLSecurityConstants.NS_XMLDSIG_HMACSHA1.equals(sigAlgorithm)) {
        key = XMLSecurityUtils.prepareSecretKey(sigAlgorithm, key.getEncoded());
    }
    signatureAlgorithm.engineInitSign(key);

    SignedInfoProcessor signedInfoProcessor = newSignedInfoProcessor(signatureAlgorithm, signatureElement,
            subOutputProcessorChain);
    createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignedInfo, false,
            null);

    attributes = new ArrayList<XMLSecAttribute>(1);
    final String signatureCanonicalizationAlgorithm = getSecurityProperties()
            .getSignatureCanonicalizationAlgorithm();
    attributes
            .add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, signatureCanonicalizationAlgorithm));
    createStartElementAndOutputAsEvent(subOutputProcessorChain,
            XMLSecurityConstants.TAG_dsig_CanonicalizationMethod, false, attributes);

    if (getSecurityProperties().isAddExcC14NInclusivePrefixes()
            && XMLSecurityConstants.NS_C14N_EXCL.equals(signatureCanonicalizationAlgorithm)) {
        attributes = new ArrayList<XMLSecAttribute>(1);
        attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_PrefixList,
                signedInfoProcessor.getInclusiveNamespacePrefixes()));
        createStartElementAndOutputAsEvent(subOutputProcessorChain,
                XMLSecurityConstants.TAG_c14nExcl_InclusiveNamespaces, true, attributes);
        createEndElementAndOutputAsEvent(subOutputProcessorChain,
                XMLSecurityConstants.TAG_c14nExcl_InclusiveNamespaces);
    }

    createEndElementAndOutputAsEvent(subOutputProcessorChain,
            XMLSecurityConstants.TAG_dsig_CanonicalizationMethod);

    attributes = new ArrayList<XMLSecAttribute>(1);
    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm,
            getSecurityProperties().getSignatureAlgorithm()));
    createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignatureMethod,
            false, attributes);
    createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignatureMethod);

    Iterator<SignaturePartDef> signaturePartDefIterator = signaturePartDefList.iterator();
    while (signaturePartDefIterator.hasNext()) {
        SignaturePartDef signaturePartDef = signaturePartDefIterator.next();
        String uriString;
        if (signaturePartDef.isExternalResource()) {
            uriString = signaturePartDef.getSigRefId();
        } else if (signaturePartDef.isGenerateXPointer()) {
            uriString = "#xpointer(id('" + signaturePartDef.getSigRefId() + "'))";
        } else {
            uriString = "#" + signaturePartDef.getSigRefId();
        }
        attributes = new ArrayList<XMLSecAttribute>(1);
        attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_URI, uriString));
        createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_Reference,
                false, attributes);
        createTransformsStructureForSignature(subOutputProcessorChain, signaturePartDef);

        attributes = new ArrayList<XMLSecAttribute>(1);
        attributes.add(
                createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, signaturePartDef.getDigestAlgo()));
        createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod,
                false, attributes);
        createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod);
        createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestValue,
                false, null);
        createCharactersAndOutputAsEvent(subOutputProcessorChain, signaturePartDef.getDigestValue());
        createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestValue);
        createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_Reference);
    }

    createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignedInfo);
    subOutputProcessorChain.removeProcessor(signedInfoProcessor);

    createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignatureValue,
            false, null);
    final byte[] signatureValue = signedInfoProcessor.getSignatureValue();
    createCharactersAndOutputAsEvent(subOutputProcessorChain,
            new Base64(76, new byte[] { '\n' }).encodeToString(signatureValue));
    createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignatureValue);

    attributes = new ArrayList<XMLSecAttribute>(1);
    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Id, IDGenerator.generateID(null)));
    if (!SecurityTokenConstants.KeyIdentifier_NoKeyInfo
            .equals(getSecurityProperties().getSignatureKeyIdentifier())) {
        createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo,
                false, attributes);
        createKeyInfoStructureForSignature(subOutputProcessorChain, wrappingSecurityToken,
                getSecurityProperties().isUseSingleCert());
        createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
    }
    createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_Signature);
}

From source file:org.guanxi.sp.engine.service.saml2.WebBrowserSSOAuthConsumerService.java

/**
 * Decrypts a SAML2 Web Browser SSO Response from an IdP
 *
 * @param encryptedResponse The encrypted Response
 * @param xmlOptions XmlOptions describing namesapces in the Response
 * @param privateKey the Guard's private key used to decrypt the Response
 * @return decrypted Response/*from w ww  .jav  a2 s. c  o  m*/
 */
private ResponseDocument decryptResponse(ResponseDocument encryptedResponse, XmlOptions xmlOptions,
        PrivateKey privateKey) throws GuanxiException {
    try {
        // For decryption, we need to be in DOM land
        Document rawSAMLResponseDoc = (Document) encryptedResponse.newDomNode(xmlOptions);

        /* XMLBeans doesn't give us access to the embedded encryption key for some reason
         * so we need to break out to DOM and back again.
         */
        NodeList nodes = encryptedResponse.getResponse().getEncryptedAssertionArray(0).getEncryptedData()
                .getKeyInfo().getDomNode().getChildNodes();
        Node node = null;
        for (int c = 0; c < nodes.getLength(); c++) {
            node = nodes.item(c);
            if (node.getLocalName() != null) {
                if (node.getLocalName().equals("EncryptedKey"))
                    break;
            }
        }
        EncryptedKeyDocument encKeyDoc = EncryptedKeyDocument.Factory.parse(node, xmlOptions);

        // Get a handle on the encypted data in DOM land
        String namespaceURI = EncryptionConstants.EncryptionSpecNS;
        String localName = EncryptionConstants._TAG_ENCRYPTEDDATA;

        // Recurse through the decryption process
        NodeList encyptedDataNodes = rawSAMLResponseDoc.getElementsByTagNameNS(namespaceURI, localName);
        while (encyptedDataNodes.getLength() > 0) {
            Element encryptedDataElement = (Element) encyptedDataNodes.item(0);

            /* This block unwraps and decrypts the secret key. The IdP first encrypts the attributes
             * using a secret key. It then encrypts that secret key using the public key of the Guard.
             * So the first step is to use the Guard's private key to decrypt the secret key.
             */
            String algorithm = encKeyDoc.getEncryptedKey().getEncryptionMethod().getAlgorithm();
            XMLCipher xmlCipher = XMLCipher.getInstance();
            xmlCipher.init(XMLCipher.UNWRAP_MODE, privateKey);
            EncryptedData encryptedData = xmlCipher.loadEncryptedData(rawSAMLResponseDoc, encryptedDataElement);
            EncryptedKey encryptedKey = encryptedData.getKeyInfo().itemEncryptedKey(0);
            Key decryptedSecretKey = xmlCipher.decryptKey(encryptedKey, algorithm);

            // This block uses the decrypted secret key to decrypt the attributes
            Key secretKey = new SecretKeySpec(decryptedSecretKey.getEncoded(), "AES");
            XMLCipher xmlDecryptCipher = XMLCipher.getInstance();
            xmlDecryptCipher.init(XMLCipher.DECRYPT_MODE, secretKey);
            xmlDecryptCipher.doFinal(rawSAMLResponseDoc, encryptedDataElement);

            // Any more encryption to handle?
            encyptedDataNodes = rawSAMLResponseDoc.getElementsByTagNameNS(namespaceURI, localName);
        }

        // And back to XMLBeans for that nice API!
        return ResponseDocument.Factory.parse(rawSAMLResponseDoc);
    } catch (XmlException xe) {
        logger.error("XML problem decrypting the response", xe);
        throw new GuanxiException(xe);
    } catch (XMLEncryptionException xee) {
        logger.error("XML problem decrypting the response", xee);
        throw new GuanxiException(xee);
    } catch (Exception e) {
        logger.error("Problem decrypting the response", e);
        throw new GuanxiException(e);
    }
}

From source file:org.apache.hadoop.io.crypto.KeyStoreKeyProvider.java

/**
 * Implementation of getting keys from the key store.
 *///from   w  w w. j a  v  a  2 s.  co  m
@Override
public Key[] getKeys(String[] keyNames) throws CryptoException {
    if (keyStore == null)
        throw new CryptoException("Key store is not intialized.");

    if (keyNames == null)
        return null;

    Key[] rawKeys = new Key[keyNames.length];

    try {
        for (int i = 0; i < keyNames.length; i++) {
            String keyName = keyNames[i];
            String password = getKeyPassword(keyName);

            char[] passphase = null;
            if (password != null)
                passphase = password.toCharArray();

            Key.KeyType keyType = Key.KeyType.OPAQUE;
            String algorithm = null;
            String format = null;
            byte[] rawKey;

            java.security.Key key = keyStore.getKey(keyName, passphase);
            if (key != null) {
                // secret key or private key
                rawKey = key.getEncoded();
                algorithm = key.getAlgorithm();
                format = key.getFormat();

                if (key instanceof SecretKey) {
                    keyType = Key.KeyType.SYMMETRIC_KEY;
                } else if (key instanceof PrivateKey) {
                    keyType = Key.KeyType.PRIVATE_KEY;
                }
            } else {
                // trusted certificate
                Certificate certificate = keyStore.getCertificate(keyName);
                if (certificate == null)
                    throw new CryptoException("Key " + keyName + " not found");

                keyType = Key.KeyType.CERTIFICATE;
                rawKey = certificate.getEncoded();
            }

            rawKeys[i] = new Key(keyType, algorithm, 0, format, rawKey);
        }
    } catch (KeyStoreException e) {
        throw new CryptoException(e);
    } catch (UnrecoverableEntryException e) {
        throw new CryptoException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoException(e);
    } catch (CertificateException e) {
        throw new CryptoException(e);
    }

    return rawKeys;
}

From source file:org.apache.xml.security.stax.impl.processor.output.XMLEncryptOutputProcessor.java

/**
 * Override this method to return a different AbstractInternalEncryptionOutputProcessor instance
 * which will write out the KeyInfo contents in the EncryptedData.
 *///  w ww  .j  ava  2s . c  o m
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<XMLSecAttribute>(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<XMLSecAttribute>(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.encodeBase64String(oaepParams));
                    createEndElementAndOutputAsEvent(outputProcessorChain,
                            XMLSecurityConstants.TAG_xenc_OAEPparams);
                }

                if (encryptionKeyTransportDigestAlgorithm != null) {
                    attributes = new ArrayList<XMLSecAttribute>(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<XMLSecAttribute>(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,
                        new Base64(76, new byte[] { '\n' }).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 {
                    throw new XMLSecurityException("stax.unsupportedToken", new Object[] { keyIdentifier });
                }

                createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
            }
        }
    };
    processor.getAfterProcessors().add(XMLEncryptOutputProcessor.class.getName());
    return processor;
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Returns a JsonValue map representing key
 *
 * @param key  The key//from w w w  . jav  a 2 s  . c o  m
 * @return a JsonValue map representing the key
 * @throws Exception
 */
protected Map<String, Object> getSecretKeyMap(Key key) throws Exception {
    Map<String, Object> keyMap = new HashMap<>();
    keyMap.put("algorithm", key.getAlgorithm());
    keyMap.put("format", key.getFormat());
    keyMap.put("encoded", Base64.encode(key.getEncoded()));
    return keyMap;
}

From source file:energy.usef.environment.tool.security.KeystoreService.java

public byte[] loadSecretKey() {
    char[] ksPassword = toCharArray(keystorePassword);
    char[] ksKeyPassword = toCharArray(keystorePKPassword);

    Key key = null;
    try (InputStream is = new FileInputStream(keystoreFilename)) {
        KeyStore ks = KeyStore.getInstance(JCEKS);
        ks.load(is, ksPassword);/*w w  w .  ja  va2s.co  m*/
        key = ks.getKey(keystorePKAlias, ksKeyPassword);
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
            | UnrecoverableKeyException e) {
        LOGGER.error("Exception occured during the loading of the secret key. {}", e);
        throw new RuntimeException(e);
    }
    if (key == null) {
        return new byte[0];
    }
    LOGGER.info("Algorithm: " + key.getAlgorithm());
    LOGGER.info("Format: " + key.getFormat());
    return key.getEncoded();
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl.java

private void selfTestGuardedString(OperationResult parentTestResult) {
    OperationResult result = parentTestResult
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString");

    OperationResult subresult = result//from w  w  w . j a v a 2  s.  c o m
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString.encryptorReflection");
    EncryptorFactory encryptorFactory = EncryptorFactory.getInstance();
    subresult.addReturn("encryptorFactoryImpl", encryptorFactory.getClass());
    LOGGER.debug("Encryptor factory implementation class: {}", encryptorFactory.getClass());
    Encryptor encryptor = EncryptorFactory.getInstance().newRandomEncryptor();
    subresult.addReturn("encryptorImpl", encryptor.getClass());
    LOGGER.debug("Encryptor implementation class: {}", encryptor.getClass());
    if (encryptor.getClass().getName().equals("org.identityconnectors.common.security.impl.EncryptorImpl")) {
        // let's do some reflection magic to have a look inside
        try {
            LOGGER.trace("Encryptor fields: {}", Arrays.asList(encryptor.getClass().getDeclaredFields()));
            Field keyField = encryptor.getClass().getDeclaredField("key");
            keyField.setAccessible(true);
            Key key = (Key) keyField.get(encryptor);
            subresult.addReturn("keyAlgorithm", key.getAlgorithm());
            subresult.addReturn("keyLength", key.getEncoded().length * 8);
            subresult.addReturn("keyFormat", key.getFormat());
            subresult.recordSuccess();
        } catch (IllegalArgumentException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (IllegalAccessException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (NoSuchFieldException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (SecurityException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        }
    }

    OperationResult encryptorSubresult = result
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString.encryptor");
    try {
        String plainString = "Scurvy seadog";
        byte[] encryptedBytes = encryptor.encrypt(plainString.getBytes());
        byte[] decryptedBytes = encryptor.decrypt(encryptedBytes);
        String decryptedString = new String(decryptedBytes);
        if (!plainString.equals(decryptedString)) {
            encryptorSubresult.recordFatalError(
                    "Encryptor roundtrip failed; encrypted=" + plainString + ", decrypted=" + decryptedString);
        } else {
            encryptorSubresult.recordSuccess();
        }
    } catch (Throwable e) {
        LOGGER.error("Encryptor operation error: {}", e.getMessage(), e);
        encryptorSubresult.recordFatalError("Encryptor opeation error: " + e.getMessage(), e);
    }

    final OperationResult guardedStringSubresult = result
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString.guardedString");
    // try to encrypt and decrypt GuardedString
    try {
        final String origString = "Shiver me timbers";
        // This should encrypt it
        GuardedString guardedString = new GuardedString(origString.toCharArray());
        // and this should decrypt it
        guardedString.access(new GuardedString.Accessor() {
            @Override
            public void access(char[] decryptedChars) {
                if (!(new String(decryptedChars)).equals(origString)) {
                    guardedStringSubresult.recordFatalError("GuardeString roundtrip failed; encrypted="
                            + origString + ", decrypted=" + (new String(decryptedChars)));
                }
            }
        });
        guardedStringSubresult.recordSuccessIfUnknown();
    } catch (Throwable e) {
        LOGGER.error("GuardedString operation error: {}", e.getMessage(), e);
        guardedStringSubresult.recordFatalError("GuardedString opeation error: " + e.getMessage(), e);
    }

    result.computeStatus();
}

From source file:it.scoppelletti.programmerpower.security.CryptoUtils.java

/**
 * Restituisce i parametri per la ricostruzione di una chiave di
 * crittografia.//from   w ww  .java2s  . c  o m
 * 
 * <P>Il metodo {@code toProperties} rileva i provider del servizio
 * {@code KeyToPropertySetProvider} disponibili e delega il calcolo dei
 * parametri al primo di questi che supporta la tipologia della chiave di
 * crittografia {@code key}; se nessuno dei provider supporta la specifica
 * tipologia di chiavi, restituisce i parametri che rappresentano la chiave
 * codificata come sequenza di byte nel formato Base64 come definito da RFC
 * 2045.</P>
 * 
 * @param  key     Chiave.
 * @param  encoded Indica se restituire i parametri che rappresentano la
 *                 chiave codificata come sequenza di byte senza rilevare
 *                 gli eventuali provider {@code KeyToPropertySetProvider}
 *                 disponibili.
 * @return         Propriet&agrave;. 
 * @see #getKey
 * @see it.scoppelletti.programmerpower.security.spi.CryptoKeyFactory
 * @see it.scoppelletti.programmerpower.security.spi.EncodedKeyFactory
 * @see it.scoppelletti.programmerpower.security.spi.KeyToPropertySetProvider
 * @see <A HREF="http://www.ietf.org/rfc/rfc2045.txt" TARGET="_blank">RFC
 *      2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format
 *      of Internet Message Bodies</A> 
 */
public static Properties toProperties(Key key, boolean encoded) {
    byte[] data;
    KeyRep.Type keyType;
    Properties props;
    KeyToPropertySetService svc;
    SecurityResources res = new SecurityResources();

    if (key == null) {
        throw new ArgumentNullException("key");
    }

    if (!encoded) {
        svc = new KeyToPropertySetService(key);
        props = svc.query();
        if (props != null) {
            return props;
        }
    }

    if (key instanceof PublicKey) {
        keyType = KeyRep.Type.PUBLIC;
    } else if (key instanceof PrivateKey) {
        keyType = KeyRep.Type.PRIVATE;
    } else if (key instanceof SecretKey) {
        keyType = KeyRep.Type.SECRET;
    } else {
        throw new InvalidCastException(key.getClass().getName(), KeyRep.Type.class.getName());
    }

    data = key.getEncoded();
    if (data == null) {
        throw new SecurityException(res.getEncodedFormatNotSupportedException());
    }

    props = new Properties();
    if (keyType == KeyRep.Type.SECRET) {
        props.setProperty(CryptoUtils.PROP_KEYFACTORY, RawKeyFactory.class.getName());
    } else {
        props.setProperty(CryptoUtils.PROP_KEYFACTORY, EncodedKeyFactory.class.getName());
        props.setProperty(EncodedKeyFactory.PROP_KEYTYPE, keyType.name());
    }

    props.setProperty(RawKeyFactory.PROP_ALGORITHM, key.getAlgorithm());
    props.setProperty(RawKeyFactory.PROP_DATA, Base64.encodeBase64String(data));

    return props;
}