Search in sources :

Example 36 with GeneralSecurityException

use of java.security.GeneralSecurityException in project wildfly by wildfly.

the class SingleSignOnSessionFactoryBuilder method getValue.

@Override
public SingleSignOnSessionFactory getValue() {
    KeyStore store = this.keyStore.getValue();
    String alias = this.keyAlias;
    CredentialSource source = this.credentialSource.getValue();
    try {
        if (!store.containsAlias(alias)) {
            UndertowLogger.ROOT_LOGGER.missingKeyStoreEntry(alias);
        }
        if (!store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
            UndertowLogger.ROOT_LOGGER.keyStoreEntryNotPrivate(alias);
        }
        PasswordCredential credential = source.getCredential(PasswordCredential.class);
        if (credential == null) {
            UndertowLogger.ROOT_LOGGER.missingCredential(source.toString());
        }
        ClearPassword password = credential.getPassword(ClearPassword.class);
        if (password == null) {
            UndertowLogger.ROOT_LOGGER.credentialNotClearPassword(credential.toString());
        }
        KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword()));
        KeyPair keyPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
        Optional<SSLContext> context = Optional.ofNullable(this.sslContext).map(dependency -> dependency.getValue());
        return new DefaultSingleSignOnSessionFactory(this.manager.getValue(), keyPair, connection -> context.ifPresent(ctx -> connection.setSSLSocketFactory(ctx.getSocketFactory())));
    } catch (GeneralSecurityException | IOException e) {
        throw new IllegalArgumentException(e);
    }
}
Also used : ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) KeyPair(java.security.KeyPair) ValueDependency(org.wildfly.clustering.service.ValueDependency) SSLContext(javax.net.ssl.SSLContext) Value(org.jboss.msc.value.Value) CredentialSource(org.wildfly.security.credential.source.CredentialSource) OperationContext(org.jboss.as.controller.OperationContext) DefaultSingleSignOnSessionFactory(org.wildfly.security.http.util.sso.DefaultSingleSignOnSessionFactory) GeneralSecurityException(java.security.GeneralSecurityException) CredentialSourceDependency(org.jboss.as.clustering.controller.CredentialSourceDependency) PasswordCredential(org.wildfly.security.credential.PasswordCredential) InjectedValueDependency(org.wildfly.clustering.service.InjectedValueDependency) ServiceTarget(org.jboss.msc.service.ServiceTarget) UndertowLogger(org.wildfly.extension.undertow.logging.UndertowLogger) SingleSignOnSessionFactory(org.wildfly.security.http.util.sso.SingleSignOnSessionFactory) CommonUnaryRequirement(org.jboss.as.clustering.controller.CommonUnaryRequirement) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) IOException(java.io.IOException) KeyStore(java.security.KeyStore) ResourceServiceBuilder(org.jboss.as.clustering.controller.ResourceServiceBuilder) Objects(java.util.Objects) ModelNodes(org.jboss.as.clustering.dmr.ModelNodes) ValueService(org.jboss.msc.service.ValueService) Stream(java.util.stream.Stream) OperationFailedException(org.jboss.as.controller.OperationFailedException) SingleSignOnManager(org.wildfly.security.http.util.sso.SingleSignOnManager) Optional(java.util.Optional) ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) ModelNode(org.jboss.dmr.ModelNode) Attribute(org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute) Builder(org.wildfly.clustering.service.Builder) KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) PasswordCredential(org.wildfly.security.credential.PasswordCredential) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) KeyStore(java.security.KeyStore) DefaultSingleSignOnSessionFactory(org.wildfly.security.http.util.sso.DefaultSingleSignOnSessionFactory) CredentialSource(org.wildfly.security.credential.source.CredentialSource)

Example 37 with GeneralSecurityException

use of java.security.GeneralSecurityException in project oxCore by GluuFederation.

the class LDAPConnectionProvider method createSSLConnectionPoolWithPreviousProtocols.

private LDAPConnectionPool createSSLConnectionPoolWithPreviousProtocols(SSLUtil sslUtil, BindRequest bindRequest, LDAPConnectionOptions connectionOptions, int maxConnections) throws LDAPException {
    for (int i = 1; i < SSL_PROTOCOLS.length; i++) {
        String protocol = SSL_PROTOCOLS[i];
        try {
            FailoverServerSet failoverSet = new FailoverServerSet(this.addresses, this.ports, sslUtil.createSSLSocketFactory(protocol), connectionOptions);
            LDAPConnectionPool connectionPool = new LDAPConnectionPool(failoverSet, bindRequest, maxConnections);
            log.info("Server supports: '" + protocol + "'");
            return connectionPool;
        } catch (GeneralSecurityException ex) {
            log.debug("Server not supports: '" + protocol + "'", ex);
        } catch (LDAPException ex) {
            // Error when LDAP server not supports specified encryption
            if (ex.getResultCode() != ResultCode.SERVER_DOWN) {
                throw ex;
            }
            log.debug("Server not supports: '" + protocol + "'", ex);
        }
    }
    return null;
}
Also used : LDAPConnectionPool(com.unboundid.ldap.sdk.LDAPConnectionPool) LDAPException(com.unboundid.ldap.sdk.LDAPException) GeneralSecurityException(java.security.GeneralSecurityException) FailoverServerSet(com.unboundid.ldap.sdk.FailoverServerSet)

Example 38 with GeneralSecurityException

use of java.security.GeneralSecurityException in project poi by apache.

the class StandardDecryptor method verifyPassword.

@Override
public boolean verifyPassword(String password) {
    EncryptionVerifier ver = getEncryptionInfo().getVerifier();
    SecretKey skey = generateSecretKey(password, ver, getKeySizeInBytes());
    Cipher cipher = getCipher(skey);
    try {
        byte[] encryptedVerifier = ver.getEncryptedVerifier();
        byte[] verifier = cipher.doFinal(encryptedVerifier);
        setVerifier(verifier);
        MessageDigest sha1 = CryptoFunctions.getMessageDigest(ver.getHashAlgorithm());
        byte[] calcVerifierHash = sha1.digest(verifier);
        byte[] encryptedVerifierHash = ver.getEncryptedVerifierHash();
        byte[] decryptedVerifierHash = cipher.doFinal(encryptedVerifierHash);
        // see 2.3.4.9 Password Verification (Standard Encryption)
        // ... The number of bytes used by the encrypted Verifier hash MUST be 32 ...
        // TODO: check and trim/pad the hashes to 32
        byte[] verifierHash = Arrays.copyOf(decryptedVerifierHash, calcVerifierHash.length);
        if (Arrays.equals(calcVerifierHash, verifierHash)) {
            setSecretKey(skey);
            return true;
        } else {
            return false;
        }
    } catch (GeneralSecurityException e) {
        throw new EncryptedDocumentException(e);
    }
}
Also used : EncryptionVerifier(org.apache.poi.poifs.crypt.EncryptionVerifier) SecretKey(javax.crypto.SecretKey) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) GeneralSecurityException(java.security.GeneralSecurityException) Cipher(javax.crypto.Cipher) MessageDigest(java.security.MessageDigest)

Example 39 with GeneralSecurityException

use of java.security.GeneralSecurityException in project poi by apache.

the class AgileEncryptor method confirmPassword.

@Override
public void confirmPassword(String password, byte[] keySpec, byte[] keySalt, byte[] verifier, byte[] verifierSalt, byte[] integritySalt) {
    AgileEncryptionVerifier ver = (AgileEncryptionVerifier) getEncryptionInfo().getVerifier();
    AgileEncryptionHeader header = (AgileEncryptionHeader) getEncryptionInfo().getHeader();
    ver.setSalt(verifierSalt);
    header.setKeySalt(keySalt);
    int blockSize = header.getBlockSize();
    pwHash = hashPassword(password, ver.getHashAlgorithm(), verifierSalt, ver.getSpinCount());
    /**
         * encryptedVerifierHashInput: This attribute MUST be generated by using the following steps:
         * 1. Generate a random array of bytes with the number of bytes used specified by the saltSize
         *    attribute.
         * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password,
         *    the binary byte array used to create the saltValue attribute, and a blockKey byte array
         *    consisting of the following bytes: 0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, and 0x79.
         * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue
         *    attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an
         *    integral multiple of blockSize bytes, pad the array with 0x00 to the next integral multiple of
         *    blockSize bytes.
         * 4. Use base64 to encode the result of step 3.
         */
    byte[] encryptedVerifier = hashInput(ver, pwHash, kVerifierInputBlock, verifier, Cipher.ENCRYPT_MODE);
    ver.setEncryptedVerifier(encryptedVerifier);
    /**
         * encryptedVerifierHashValue: This attribute MUST be generated by using the following steps:
         * 1. Obtain the hash value of the random array of bytes generated in step 1 of the steps for
         *    encryptedVerifierHashInput.
         * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password,
         *    the binary byte array used to create the saltValue attribute, and a blockKey byte array
         *    consisting of the following bytes: 0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, and 0x4e.
         * 3. Encrypt the hash value obtained in step 1 by using the binary form of the saltValue attribute as
         *    an initialization vector as specified in section 2.3.4.12. If hashSize is not an integral multiple of
         *    blockSize bytes, pad the hash value with 0x00 to an integral multiple of blockSize bytes.
         * 4. Use base64 to encode the result of step 3.
         */
    MessageDigest hashMD = getMessageDigest(ver.getHashAlgorithm());
    byte[] hashedVerifier = hashMD.digest(verifier);
    byte[] encryptedVerifierHash = hashInput(ver, pwHash, kHashedVerifierBlock, hashedVerifier, Cipher.ENCRYPT_MODE);
    ver.setEncryptedVerifierHash(encryptedVerifierHash);
    /**
         * encryptedKeyValue: This attribute MUST be generated by using the following steps:
         * 1. Generate a random array of bytes that is the same size as specified by the
         *    Encryptor.KeyData.keyBits attribute of the parent element.
         * 2. Generate an encryption key as specified in section 2.3.4.11, using the user-supplied password,
         *    the binary byte array used to create the saltValue attribute, and a blockKey byte array
         *    consisting of the following bytes: 0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, and 0xd6.
         * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue
         *    attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an
         *    integral multiple of blockSize bytes, pad the array with 0x00 to an integral multiple of
         *    blockSize bytes.
         * 4. Use base64 to encode the result of step 3.
         */
    byte[] encryptedKey = hashInput(ver, pwHash, kCryptoKeyBlock, keySpec, Cipher.ENCRYPT_MODE);
    ver.setEncryptedKey(encryptedKey);
    SecretKey secretKey = new SecretKeySpec(keySpec, header.getCipherAlgorithm().jceId);
    setSecretKey(secretKey);
    /*
         * 2.3.4.14 DataIntegrity Generation (Agile Encryption)
         * 
         * The DataIntegrity element contained within an Encryption element MUST be generated by using
         * the following steps:
         * 1. Obtain the intermediate key by decrypting the encryptedKeyValue from a KeyEncryptor
         *    contained within the KeyEncryptors sequence. Use this key for encryption operations in the
         *    remaining steps of this section.
         * 2. Generate a random array of bytes, known as Salt, of the same length as the value of the
         *    KeyData.hashSize attribute.
         * 3. Encrypt the random array of bytes generated in step 2 by using the binary form of the
         *    KeyData.saltValue attribute and a blockKey byte array consisting of the following bytes:
         *    0x5f, 0xb2, 0xad, 0x01, 0x0c, 0xb9, 0xe1, and 0xf6 used to form an initialization vector as
         *    specified in section 2.3.4.12. If the array of bytes is not an integral multiple of blockSize
         *    bytes, pad the array with 0x00 to the next integral multiple of blockSize bytes.
         * 4. Assign the encryptedHmacKey attribute to the base64-encoded form of the result of step 3.
         * 5. Generate an HMAC, as specified in [RFC2104], of the encrypted form of the data (message),
         *    which the DataIntegrity element will verify by using the Salt generated in step 2 as the key.
         *    Note that the entire EncryptedPackage stream (1), including the StreamSize field, MUST be
         *    used as the message.
         * 6. Encrypt the HMAC as in step 3 by using a blockKey byte array consisting of the following bytes:
         *    0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, and 0x33.
         * 7.  Assign the encryptedHmacValue attribute to the base64-encoded form of the result of step 6. 
         */
    this.integritySalt = integritySalt.clone();
    try {
        byte[] vec = CryptoFunctions.generateIv(header.getHashAlgorithm(), header.getKeySalt(), kIntegrityKeyBlock, header.getBlockSize());
        Cipher cipher = getCipher(secretKey, header.getCipherAlgorithm(), header.getChainingMode(), vec, Cipher.ENCRYPT_MODE);
        byte[] hmacKey = getBlock0(this.integritySalt, getNextBlockSize(this.integritySalt.length, blockSize));
        byte[] encryptedHmacKey = cipher.doFinal(hmacKey);
        header.setEncryptedHmacKey(encryptedHmacKey);
        cipher = Cipher.getInstance("RSA");
        for (AgileCertificateEntry ace : ver.getCertificates()) {
            cipher.init(Cipher.ENCRYPT_MODE, ace.x509.getPublicKey());
            ace.encryptedKey = cipher.doFinal(getSecretKey().getEncoded());
            Mac x509Hmac = CryptoFunctions.getMac(header.getHashAlgorithm());
            x509Hmac.init(getSecretKey());
            ace.certVerifier = x509Hmac.doFinal(ace.x509.getEncoded());
        }
    } catch (GeneralSecurityException e) {
        throw new EncryptedDocumentException(e);
    }
}
Also used : AgileCertificateEntry(org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier.AgileCertificateEntry) SecretKey(javax.crypto.SecretKey) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) Cipher(javax.crypto.Cipher) CryptoFunctions.getCipher(org.apache.poi.poifs.crypt.CryptoFunctions.getCipher) MessageDigest(java.security.MessageDigest) CryptoFunctions.getMessageDigest(org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest) Mac(javax.crypto.Mac)

Example 40 with GeneralSecurityException

use of java.security.GeneralSecurityException in project poi by apache.

the class SignatureFacet method newReference.

public static Reference newReference(String uri, List<Transform> transforms, String type, String id, byte[] digestValue, SignatureConfig signatureConfig) throws XMLSignatureException {
    // the references appear in the package signature or the package object
    // so we can use the default digest algorithm
    String digestMethodUri = signatureConfig.getDigestMethodUri();
    XMLSignatureFactory sigFac = signatureConfig.getSignatureFactory();
    DigestMethod digestMethod;
    try {
        digestMethod = sigFac.newDigestMethod(digestMethodUri, null);
    } catch (GeneralSecurityException e) {
        throw new XMLSignatureException("unknown digest method uri: " + digestMethodUri, e);
    }
    Reference reference;
    if (digestValue == null) {
        reference = sigFac.newReference(uri, digestMethod, transforms, type, id);
    } else {
        reference = sigFac.newReference(uri, digestMethod, transforms, type, id, digestValue);
    }
    brokenJvmWorkaround(reference);
    return reference;
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) DOMReference(org.apache.jcp.xml.dsig.internal.dom.DOMReference) Reference(javax.xml.crypto.dsig.Reference) GeneralSecurityException(java.security.GeneralSecurityException) DOMDigestMethod(org.apache.jcp.xml.dsig.internal.dom.DOMDigestMethod) DigestMethod(javax.xml.crypto.dsig.DigestMethod) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException)

Aggregations

GeneralSecurityException (java.security.GeneralSecurityException)1197 IOException (java.io.IOException)448 Cipher (javax.crypto.Cipher)148 Test (org.junit.Test)136 X509Certificate (java.security.cert.X509Certificate)130 KeyStore (java.security.KeyStore)98 SSLContext (javax.net.ssl.SSLContext)86 SecretKeySpec (javax.crypto.spec.SecretKeySpec)82 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)77 ArrayList (java.util.ArrayList)75 File (java.io.File)64 InputStream (java.io.InputStream)63 Certificate (java.security.cert.Certificate)61 PublicKey (java.security.PublicKey)56 FileInputStream (java.io.FileInputStream)54 PrivateKey (java.security.PrivateKey)51 BigInteger (java.math.BigInteger)50 SecretKey (javax.crypto.SecretKey)48 IvParameterSpec (javax.crypto.spec.IvParameterSpec)47 KeyPair (java.security.KeyPair)45