Search in sources :

Example 31 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project signer by demoiselle.

the class TimeStampOperator method validate.

/**
 * Validate a time stamp
 *
 * @param content if it is assigned, the parameter hash must to be null
 * @param timeStamp timestamp to be validated
 * @param hash if it is assigned, the parameter content must to be null
 * @throws CertificateCoreException validate exception
 */
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
        CMSSignedData s = timeStampToken.toCMSSignedData();
        int verified = 0;
        Store<?> certStore = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        Iterator<SignerInformation> it = c.iterator();
        while (it.hasNext()) {
            SignerInformation signer = it.next();
            Collection<?> certCollection = certStore.getMatches(signer.getSID());
            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
            if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
                verified++;
            }
            cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
        }
        logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified));
        // Valida o hash  incluso no carimbo de tempo com hash do arquivo carimbado
        byte[] calculatedHash = null;
        if (content != null) {
            Digest digest = DigestFactory.getInstance().factoryDefault();
            digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
            calculatedHash = digest.digest(content);
        } else {
            calculatedHash = hash;
        }
        if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
            logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
        } else {
            throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
        }
    } catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
        throw new CertificateCoreException(ex.getMessage());
    }
}
Also used : Digest(org.demoiselle.signer.cryptography.Digest) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CMSException(org.bouncycastle.cms.CMSException)

Example 32 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project javaee7-samples by javaee-samples.

the class SecureServletTest method createSelfSignedCertificate.

// Private methods
// TODO: may move these to utility class
private static X509Certificate createSelfSignedCertificate(KeyPair keys) {
    try {
        Provider provider = new BouncyCastleProvider();
        Security.addProvider(provider);
        return new JcaX509CertificateConverter().setProvider(provider).getCertificate(new X509v3CertificateBuilder(new X500Name("CN=lfoo, OU=bar, O=kaz, L=zak, ST=lak, C=UK"), ONE, Date.from(now()), Date.from(now().plus(1, DAYS)), new X500Name("CN=lfoo, OU=bar, O=kaz, L=zak, ST=lak, C=UK"), SubjectPublicKeyInfo.getInstance(keys.getPublic().getEncoded())).build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider(provider).build(keys.getPrivate())));
    } catch (CertificateException | OperatorCreationException e) {
        throw new IllegalStateException(e);
    }
}
Also used : JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Provider(java.security.Provider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 33 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project gitblit by gitblit.

the class X509Utils method revoke.

/**
 * Revoke a certificate.
 *
 * @param cert
 * @param reason
 * @param caRevocationList
 * @param caPrivateKey
 * @param x509log
 * @return true if the certificate has been revoked
 */
public static boolean revoke(X509Certificate cert, RevocationReason reason, File caRevocationList, PrivateKey caPrivateKey, X509Log x509log) {
    try {
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(cert).getName());
        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
        if (caRevocationList.exists()) {
            byte[] data = FileUtils.readContent(caRevocationList);
            X509CRLHolder crl = new X509CRLHolder(data);
            crlBuilder.addCRL(crl);
        }
        crlBuilder.addCRLEntry(cert.getSerialNumber(), new Date(), reason.ordinal());
        // build and sign CRL with CA private key
        ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(caPrivateKey);
        X509CRLHolder crl = crlBuilder.build(signer);
        File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(tmpFile);
            fos.write(crl.getEncoded());
            fos.flush();
            fos.close();
            if (caRevocationList.exists()) {
                caRevocationList.delete();
            }
            tmpFile.renameTo(caRevocationList);
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (tmpFile.exists()) {
                tmpFile.delete();
            }
        }
        x509log.log(MessageFormat.format("Revoked certificate {0,number,0} reason: {1} [{2}]", cert.getSerialNumber(), reason.toString(), cert.getSubjectDN().getName()));
        return true;
    } catch (IOException | OperatorCreationException | CertificateEncodingException e) {
        logger.error(MessageFormat.format("Failed to revoke certificate {0,number,0} [{1}] in {2}", cert.getSerialNumber(), cert.getSubjectDN().getName(), caRevocationList));
    }
    return false;
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateEncodingException(java.security.cert.CertificateEncodingException) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) Date(java.util.Date) FileOutputStream(java.io.FileOutputStream) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) X509v2CRLBuilder(org.bouncycastle.cert.X509v2CRLBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) File(java.io.File)

Example 34 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project cloudstack by apache.

the class SAML2AuthManagerImpl method initSP.

protected boolean initSP() {
    KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
    if (keyStoreVO == null) {
        try {
            KeyPair keyPair = CertUtils.generateRandomKeyPair(4096);
            _ksDao.save(SAMLPluginConstants.SAMLSP_KEYPAIR, SAMLUtils.encodePrivateKey(keyPair.getPrivate()), SAMLUtils.encodePublicKey(keyPair.getPublic()), "samlsp-keypair");
            keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
            s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair");
        } catch (final NoSuchProviderException | NoSuchAlgorithmException e) {
            s_logger.error("Unable to create and save SAML keypair, due to: ", e);
        }
    }
    String spId = SAMLServiceProviderID.value();
    String spSsoUrl = SAMLServiceProviderSingleSignOnURL.value();
    String spSloUrl = SAMLServiceProviderSingleLogOutURL.value();
    String spOrgName = SAMLServiceProviderOrgName.value();
    String spOrgUrl = SAMLServiceProviderOrgUrl.value();
    String spContactPersonName = SAMLServiceProviderContactPersonName.value();
    String spContactPersonEmail = SAMLServiceProviderContactEmail.value();
    KeyPair spKeyPair = null;
    X509Certificate spX509Key = null;
    if (keyStoreVO != null) {
        final PrivateKey privateKey = SAMLUtils.decodePrivateKey(keyStoreVO.getCertificate());
        final PublicKey publicKey = SAMLUtils.decodePublicKey(keyStoreVO.getKey());
        if (privateKey != null && publicKey != null) {
            spKeyPair = new KeyPair(publicKey, privateKey);
            KeystoreVO x509VO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_X509CERT);
            if (x509VO == null) {
                try {
                    spX509Key = SAMLUtils.generateRandomX509Certificate(spKeyPair);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ObjectOutput out = new ObjectOutputStream(bos);
                    out.writeObject(spX509Key);
                    out.flush();
                    _ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT, Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert");
                    bos.close();
                } catch (final NoSuchAlgorithmException | NoSuchProviderException | CertificateException | SignatureException | InvalidKeyException | IOException | OperatorCreationException e) {
                    s_logger.error("SAML plugin won't be able to use X509 signed authentication", e);
                }
            } else {
                try {
                    ByteArrayInputStream bi = new ByteArrayInputStream(Base64.decodeBase64(x509VO.getCertificate()));
                    ObjectInputStream si = new ObjectInputStream(bi);
                    spX509Key = (X509Certificate) si.readObject();
                    bi.close();
                } catch (IOException | ClassNotFoundException ignored) {
                    s_logger.error("SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database.");
                }
            }
        }
    }
    if (spKeyPair != null && spX509Key != null && spId != null && spSsoUrl != null && spSloUrl != null && spOrgName != null && spOrgUrl != null && spContactPersonName != null && spContactPersonEmail != null) {
        _spMetadata.setEntityId(spId);
        _spMetadata.setOrganizationName(spOrgName);
        _spMetadata.setOrganizationUrl(spOrgUrl);
        _spMetadata.setContactPersonName(spContactPersonName);
        _spMetadata.setContactPersonEmail(spContactPersonEmail);
        _spMetadata.setSsoUrl(spSsoUrl);
        _spMetadata.setSloUrl(spSloUrl);
        _spMetadata.setKeyPair(spKeyPair);
        _spMetadata.setSigningCertificate(spX509Key);
        _spMetadata.setEncryptionCertificate(spX509Key);
        return true;
    }
    return false;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) ObjectOutput(java.io.ObjectOutput) PublicKey(java.security.PublicKey) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SignatureException(java.security.SignatureException) IOException(java.io.IOException) ObjectOutputStream(java.io.ObjectOutputStream) InvalidKeyException(java.security.InvalidKeyException) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) KeystoreVO(org.apache.cloudstack.framework.security.keystore.KeystoreVO) NoSuchProviderException(java.security.NoSuchProviderException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ObjectInputStream(java.io.ObjectInputStream)

Example 35 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project zeppelin by apache.

the class PEMImporter method loadKeyStore.

public static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword) throws IOException, GeneralSecurityException {
    PrivateKey key;
    try {
        key = createPrivateKey(privateKeyFile, keyPassword);
    } catch (OperatorCreationException | IOException | GeneralSecurityException | PKCSException e) {
        throw new GeneralSecurityException("Private Key issues", e);
    }
    List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile);
    if (certificateChain.isEmpty()) {
        throw new CertificateException("Certificate file does not contain any certificates: " + certificateChainFile);
    }
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("key", key, keyPassword.toCharArray(), certificateChain.stream().toArray(Certificate[]::new));
    return keyStore;
}
Also used : PrivateKey(java.security.PrivateKey) GeneralSecurityException(java.security.GeneralSecurityException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PKCSException(org.bouncycastle.pkcs.PKCSException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)88 IOException (java.io.IOException)51 ContentSigner (org.bouncycastle.operator.ContentSigner)38 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)36 CertificateException (java.security.cert.CertificateException)33 X509Certificate (java.security.cert.X509Certificate)31 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)23 Date (java.util.Date)22 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)19 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)19 CMSException (org.bouncycastle.cms.CMSException)17 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)15 X500Name (org.bouncycastle.asn1.x500.X500Name)15 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)15 GeneralName (org.bouncycastle.asn1.x509.GeneralName)14 NoSuchProviderException (java.security.NoSuchProviderException)12 CMSSignedData (org.bouncycastle.cms.CMSSignedData)12 GeneralSecurityException (java.security.GeneralSecurityException)11 InvalidKeyException (java.security.InvalidKeyException)11 CertificateEncodingException (java.security.cert.CertificateEncodingException)10