Search in sources :

Example 76 with GeneralSecurityException

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

the class SSLContextParameters method createSSLContext.

/**
     * Creates an {@link SSLContext} based on the related configuration options
     * of this instance. Namely, {@link #keyManagers}, {@link #trustManagers}, and
     * {@link #secureRandom}, but also respecting the chosen provider and secure
     * socket protocol as well.
     *
     * @param camelContext  The camel context
     *
     * @return a newly configured instance
     *
     * @throws GeneralSecurityException if there is a problem in this instances
     *             configuration or that of its nested configuration options
     * @throws IOException if there is an error reading a key/trust store
     */
public SSLContext createSSLContext(CamelContext camelContext) throws GeneralSecurityException, IOException {
    if (camelContext != null) {
        // setup CamelContext before creating SSLContext
        setCamelContext(camelContext);
        if (keyManagers != null) {
            keyManagers.setCamelContext(camelContext);
        }
        if (trustManagers != null) {
            trustManagers.setCamelContext(camelContext);
        }
        if (secureRandom != null) {
            secureRandom.setCamelContext(camelContext);
        }
        if (clientParameters != null) {
            clientParameters.setCamelContext(camelContext);
        }
        if (serverParameters != null) {
            serverParameters.setCamelContext(camelContext);
        }
    }
    LOG.trace("Creating SSLContext from SSLContextParameters [{}].", this);
    LOG.info("Available providers: {}.", Security.getProviders());
    KeyManager[] keyManagers = this.keyManagers == null ? null : this.keyManagers.createKeyManagers();
    TrustManager[] trustManagers = this.trustManagers == null ? null : this.trustManagers.createTrustManagers();
    SecureRandom secureRandom = this.secureRandom == null ? null : this.secureRandom.createSecureRandom();
    SSLContext context;
    if (this.getProvider() == null) {
        context = SSLContext.getInstance(this.parsePropertyValue(this.getSecureSocketProtocol()));
    } else {
        context = SSLContext.getInstance(this.parsePropertyValue(this.getSecureSocketProtocol()), this.parsePropertyValue(this.getProvider()));
    }
    if (this.getCertAlias() != null && keyManagers != null) {
        for (int idx = 0; idx < keyManagers.length; idx++) {
            if (keyManagers[idx] instanceof X509KeyManager) {
                try {
                    keyManagers[idx] = new AliasedX509ExtendedKeyManager(this.getCertAlias(), (X509KeyManager) keyManagers[idx]);
                } catch (Exception e) {
                    throw new GeneralSecurityException(e);
                }
            }
        }
    }
    LOG.debug("SSLContext [{}], initialized from [{}], is using provider [{}], protocol [{}], key managers {}, trust managers {}, and secure random [{}].", new Object[] { context, this, context.getProvider(), context.getProtocol(), keyManagers, trustManagers, secureRandom });
    context.init(keyManagers, trustManagers, secureRandom);
    this.configureSSLContext(context);
    // Decorate the context.
    context = new SSLContextDecorator(new SSLContextSpiDecorator(context, this.getSSLEngineConfigurers(context), this.getSSLSocketFactoryConfigurers(context), this.getSSLServerSocketFactoryConfigurers(context)));
    return context;
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) TrustManager(javax.net.ssl.TrustManager) X509KeyManager(javax.net.ssl.X509KeyManager) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager)

Example 77 with GeneralSecurityException

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

the class JarUtils method verifySignature.

/**
     * This method handle all the work with  PKCS7, ASN1 encoding, signature verifying,
     * and certification path building.
     * See also PKCS #7: Cryptographic Message Syntax Standard:
     * http://www.ietf.org/rfc/rfc2315.txt
     * @param signature - the input stream of signature file to be verified
     * @param signatureBlock - the input stream of corresponding signature block file
     * @return array of certificates used to verify the signature file
     * @throws IOException - if some errors occurs during reading from the stream
     * @throws GeneralSecurityException - if signature verification process fails
     */
public static Certificate[] verifySignature(InputStream signature, InputStream signatureBlock) throws IOException, GeneralSecurityException {
    BerInputStream bis = new BerInputStream(signatureBlock);
    ContentInfo info = (ContentInfo) ContentInfo.ASN1.decode(bis);
    SignedData signedData = info.getSignedData();
    if (signedData == null) {
        throw new IOException("No SignedData found");
    }
    Collection<org.apache.harmony.security.x509.Certificate> encCerts = signedData.getCertificates();
    if (encCerts.isEmpty()) {
        return null;
    }
    X509Certificate[] certs = new X509Certificate[encCerts.size()];
    int i = 0;
    for (org.apache.harmony.security.x509.Certificate encCert : encCerts) {
        certs[i++] = new X509CertImpl(encCert);
    }
    List<SignerInfo> sigInfos = signedData.getSignerInfos();
    SignerInfo sigInfo;
    if (!sigInfos.isEmpty()) {
        sigInfo = sigInfos.get(0);
    } else {
        return null;
    }
    // Issuer
    X500Principal issuer = sigInfo.getIssuer();
    // Certificate serial number
    BigInteger snum = sigInfo.getSerialNumber();
    // Locate the certificate
    int issuerSertIndex = 0;
    for (i = 0; i < certs.length; i++) {
        if (issuer.equals(certs[i].getIssuerDN()) && snum.equals(certs[i].getSerialNumber())) {
            issuerSertIndex = i;
            break;
        }
    }
    if (i == certs.length) {
        // No issuer certificate found
        return null;
    }
    if (certs[issuerSertIndex].hasUnsupportedCriticalExtension()) {
        throw new SecurityException("Can not recognize a critical extension");
    }
    // Get Signature instance
    final String daOid = sigInfo.getDigestAlgorithm();
    final String daName = sigInfo.getDigestAlgorithmName();
    final String deaOid = sigInfo.getDigestEncryptionAlgorithm();
    String alg = null;
    Signature sig = null;
    if (daOid != null && deaOid != null) {
        alg = daOid + "with" + deaOid;
        try {
            sig = Signature.getInstance(alg);
        } catch (NoSuchAlgorithmException e) {
        }
        // Try to convert to names instead of OID.
        if (sig == null) {
            final String deaName = sigInfo.getDigestEncryptionAlgorithmName();
            alg = daName + "with" + deaName;
            try {
                sig = Signature.getInstance(alg);
            } catch (NoSuchAlgorithmException e) {
            }
        }
    }
    /*
         * TODO figure out the case in which we'd only use digestAlgorithm and
         * add a test for it.
         */
    if (sig == null && daOid != null) {
        alg = daOid;
        try {
            sig = Signature.getInstance(alg);
        } catch (NoSuchAlgorithmException e) {
        }
        if (sig == null && daName != null) {
            alg = daName;
            try {
                sig = Signature.getInstance(alg);
            } catch (NoSuchAlgorithmException e) {
            }
        }
    }
    // We couldn't find a valid Signature type.
    if (sig == null) {
        return null;
    }
    sig.initVerify(certs[issuerSertIndex]);
    // If the authenticatedAttributes field of SignerInfo contains more than zero attributes,
    // compute the message digest on the ASN.1 DER encoding of the Attributes value.
    // Otherwise, compute the message digest on the data.
    List<AttributeTypeAndValue> atr = sigInfo.getAuthenticatedAttributes();
    byte[] sfBytes = new byte[signature.available()];
    signature.read(sfBytes);
    if (atr == null) {
        sig.update(sfBytes);
    } else {
        sig.update(sigInfo.getEncodedAuthenticatedAttributes());
        // If the authenticatedAttributes field contains the message-digest attribute,
        // verify that it equals the computed digest of the signature file
        byte[] existingDigest = null;
        for (AttributeTypeAndValue a : atr) {
            if (Arrays.equals(a.getType().getOid(), MESSAGE_DIGEST_OID)) {
                if (existingDigest != null) {
                    throw new SecurityException("Too many MessageDigest attributes");
                }
                Collection<?> entries = a.getValue().getValues(ASN1OctetString.getInstance());
                if (entries.size() != 1) {
                    throw new SecurityException("Too many values for MessageDigest attribute");
                }
                existingDigest = (byte[]) entries.iterator().next();
            }
        }
        // message digest entry.
        if (existingDigest == null) {
            throw new SecurityException("Missing MessageDigest in Authenticated Attributes");
        }
        MessageDigest md = null;
        if (daOid != null) {
            md = MessageDigest.getInstance(daOid);
        }
        if (md == null && daName != null) {
            md = MessageDigest.getInstance(daName);
        }
        if (md == null) {
            return null;
        }
        byte[] computedDigest = md.digest(sfBytes);
        if (!Arrays.equals(existingDigest, computedDigest)) {
            throw new SecurityException("Incorrect MD");
        }
    }
    if (!sig.verify(sigInfo.getEncryptedDigest())) {
        throw new SecurityException("Incorrect signature");
    }
    return createChain(certs[issuerSertIndex], certs);
}
Also used : ASN1OctetString(org.apache.harmony.security.asn1.ASN1OctetString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ContentInfo(org.apache.harmony.security.pkcs7.ContentInfo) X509CertImpl(org.apache.harmony.security.provider.cert.X509CertImpl) BerInputStream(org.apache.harmony.security.asn1.BerInputStream) MessageDigest(java.security.MessageDigest) SignedData(org.apache.harmony.security.pkcs7.SignedData) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) AttributeTypeAndValue(org.apache.harmony.security.x501.AttributeTypeAndValue) SignerInfo(org.apache.harmony.security.pkcs7.SignerInfo) Signature(java.security.Signature) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 78 with GeneralSecurityException

use of java.security.GeneralSecurityException in project sailfish-mfa by picos-io.

the class TOTP method hmac_sha.

private static byte[] hmac_sha(String crypto, byte[] keyBytes, byte[] text) {
    try {
        Mac hmac;
        hmac = Mac.getInstance(crypto);
        SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
        hmac.init(macKey);
        return hmac.doFinal(text);
    } catch (GeneralSecurityException gse) {
        throw new UndeclaredThrowableException(gse);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) Mac(javax.crypto.Mac)

Example 79 with GeneralSecurityException

use of java.security.GeneralSecurityException in project cas by apereo.

the class RestfulAuthenticationPolicy method isSatisfiedBy.

@Override
public boolean isSatisfiedBy(final Authentication authentication) throws Exception {
    try {
        final HttpHeaders acceptHeaders = new HttpHeaders();
        acceptHeaders.setAccept(CollectionUtils.wrap(MediaType.APPLICATION_JSON));
        final HttpEntity<Principal> entity = new HttpEntity<>(authentication.getPrincipal(), acceptHeaders);
        LOGGER.warn("Checking authentication policy for [{}] via POST at [{}]", authentication.getPrincipal(), this.endpoint);
        final ResponseEntity<String> resp = restTemplate.exchange(this.endpoint, HttpMethod.POST, entity, String.class);
        if (resp == null) {
            LOGGER.warn("[{}] returned no responses", this.endpoint);
            throw new GeneralSecurityException("No response returned from REST endpoint to determine authentication policy");
        }
        if (resp.getStatusCode() != HttpStatus.OK) {
            final Exception ex = handleResponseStatusCode(resp.getStatusCode(), authentication.getPrincipal());
            throw new GeneralSecurityException(ex);
        }
        return true;
    } catch (final HttpClientErrorException e) {
        final Exception ex = handleResponseStatusCode(e.getStatusCode(), authentication.getPrincipal());
        throw new GeneralSecurityException(ex);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) GeneralSecurityException(java.security.GeneralSecurityException) Principal(org.apereo.cas.authentication.principal.Principal) AccountLockedException(javax.security.auth.login.AccountLockedException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) AccountExpiredException(javax.security.auth.login.AccountExpiredException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) GeneralSecurityException(java.security.GeneralSecurityException) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException)

Example 80 with GeneralSecurityException

use of java.security.GeneralSecurityException in project cas by apereo.

the class UniquePrincipalAuthenticationPolicy method isSatisfiedBy.

@Override
public boolean isSatisfiedBy(final Authentication authentication) throws Exception {
    try {
        final Principal authPrincipal = authentication.getPrincipal();
        final long count = this.ticketRegistry.getTickets(t -> {
            boolean pass = TicketGrantingTicket.class.isInstance(t) && !t.isExpired();
            if (pass) {
                final Principal principal = TicketGrantingTicket.class.cast(t).getAuthentication().getPrincipal();
                pass = principal.getId().equalsIgnoreCase(authPrincipal.getId());
            }
            return pass;
        }).count();
        if (count == 0) {
            LOGGER.debug("Authentication policy is satisfied with [{}]", authPrincipal.getId());
            return true;
        }
        LOGGER.warn("Authentication policy cannot be satisfied for principal [{}] because [{}] sessions currently exist", authPrincipal.getId(), count);
        return false;
    } catch (final Exception e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : AuthenticationPolicy(org.apereo.cas.authentication.AuthenticationPolicy) Slf4j(lombok.extern.slf4j.Slf4j) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) GeneralSecurityException(java.security.GeneralSecurityException) Authentication(org.apereo.cas.authentication.Authentication) Principal(org.apereo.cas.authentication.principal.Principal) AllArgsConstructor(lombok.AllArgsConstructor) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) GeneralSecurityException(java.security.GeneralSecurityException) Principal(org.apereo.cas.authentication.principal.Principal) GeneralSecurityException(java.security.GeneralSecurityException)

Aggregations

GeneralSecurityException (java.security.GeneralSecurityException)1171 IOException (java.io.IOException)435 Cipher (javax.crypto.Cipher)144 Test (org.junit.Test)136 X509Certificate (java.security.cert.X509Certificate)124 KeyStore (java.security.KeyStore)89 SSLContext (javax.net.ssl.SSLContext)84 SecretKeySpec (javax.crypto.spec.SecretKeySpec)80 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)72 ArrayList (java.util.ArrayList)72 File (java.io.File)61 InputStream (java.io.InputStream)57 Certificate (java.security.cert.Certificate)57 PublicKey (java.security.PublicKey)53 PrivateKey (java.security.PrivateKey)50 FileInputStream (java.io.FileInputStream)49 BigInteger (java.math.BigInteger)49 SecretKey (javax.crypto.SecretKey)48 IvParameterSpec (javax.crypto.spec.IvParameterSpec)43 SecureRandom (java.security.SecureRandom)42