Search in sources :

Example 61 with OperatorCreationException

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

the class RequestSigner method signRequest.

/**
 * Signs a time stamp request
 *
 * @param privateKey private key to sign with
 * @param certificates certificate chain
 * @param request request to be signed
 * @return The signed request
 */
public byte[] signRequest(PrivateKey privateKey, Certificate[] certificates, byte[] request, String algorithm) {
    try {
        logger.info(timeStampMessagesBundle.getString("info.timestamp.sign.request"));
        Security.addProvider(new BouncyCastleProvider());
        X509Certificate signCert = (X509Certificate) certificates[0];
        List<X509Certificate> certList = new ArrayList<>();
        certList.add(signCert);
        // setup the generator
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        String varAlgorithm = null;
        if (algorithm != null && !algorithm.isEmpty()) {
            varAlgorithm = algorithm;
        } else {
            varAlgorithm = "SHA256withRSA";
        }
        SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder().build(varAlgorithm, privateKey, signCert);
        generator.addSignerInfoGenerator(signerInfoGenerator);
        Store<?> certStore = new JcaCertStore(certList);
        generator.addCertificates(certStore);
        // Store crlStore = new JcaCRLStore(crlList);
        // generator.addCRLs(crlStore);
        // Create the signed data object
        CMSTypedData data = new CMSProcessableByteArray(request);
        CMSSignedData signed = generator.generate(data, true);
        return signed.getEncoded();
    } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) {
        logger.info(ex.getMessage());
    }
    return null;
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) CMSTypedData(org.bouncycastle.cms.CMSTypedData) ArrayList(java.util.ArrayList) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JcaSimpleSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) CMSException(org.bouncycastle.cms.CMSException)

Example 62 with OperatorCreationException

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

the class X509CRLStreamWriter method preScan.

public synchronized X509CRLStreamWriter preScan(InputStream crlToChange, CRLEntryValidator validator) throws IOException {
    if (locked) {
        throw new IllegalStateException("Cannot modify a locked stream.");
    }
    if (preScanned) {
        throw new IllegalStateException("preScan has already been run.");
    }
    X509CRLEntryStream reaperStream = null;
    ASN1InputStream asn1In = null;
    try {
        reaperStream = new X509CRLEntryStream(crlToChange);
        if (!reaperStream.hasNext()) {
            emptyCrl = true;
            preScanned = true;
            return this;
        }
        while (reaperStream.hasNext()) {
            CRLEntry entry = reaperStream.next();
            if (validator != null && validator.shouldDelete(entry)) {
                // Get the serial number
                deletedEntries.add(entry.getUserCertificate().getValue());
                deletedEntriesLength += entry.getEncoded().length;
            }
        }
        /* At this point, crlToChange is at the point where the crlExtensions would
             * be.  RFC 5280 says that "Conforming CRL issuers are REQUIRED to include
             * the authority key identifier (Section 5.2.1) and the CRL number (Section 5.2.3)
             * extensions in all CRLs issued.
             */
        byte[] oldExtensions = null;
        ASN1Primitive o;
        asn1In = new ASN1InputStream(crlToChange);
        while ((o = asn1In.readObject()) != null) {
            if (o instanceof ASN1Sequence) {
                // Now we are at the signatureAlgorithm
                ASN1Sequence seq = (ASN1Sequence) o;
                if (seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) {
                    // It's possible an algorithm has already been set using setSigningAlgorithm()
                    if (signingAlg == null) {
                        signingAlg = AlgorithmIdentifier.getInstance(seq);
                    }
                    try {
                        // Build the signer
                        this.signer = createContentSigner(signingAlg, key);
                    } catch (OperatorCreationException e) {
                        throw new IOException("Could not create ContentSigner for " + signingAlg.getAlgorithm());
                    }
                }
            } else if (o instanceof ASN1BitString) {
                oldSigLength = o.getEncoded().length;
            } else {
                if (oldExtensions != null) {
                    throw new IllegalStateException("Already read in CRL extensions.");
                }
                oldExtensions = o.getEncoded();
            }
        }
        if (oldExtensions == null) {
            /* v1 CRLs (defined in RFC 1422) don't require extensions but all new
                 * CRLs should be v2 (defined in RFC 5280).  In the extremely unlikely
                 * event that someone is working with a v1 CRL, we handle it here although
                 * we print a warning.
                 */
            preScanned = true;
            newExtensions = null;
            extensionsDelta = 0;
            log.warn("The CRL you are modifying is a version 1 CRL." + " Please investigate moving to a version 2 CRL by adding the CRL Number" + " and Authority Key Identifier extensions.");
            return this;
        }
        newExtensions = updateExtensions(oldExtensions);
        // newExtension and oldExtensions have already been converted to DER so any difference
        // in the length of the L bytes will be accounted for in the overall difference between
        // the length of the two byte arrays.
        extensionsDelta = newExtensions.length - oldExtensions.length;
    } finally {
        if (reaperStream != null) {
            reaperStream.close();
        }
        IOUtils.closeQuietly(asn1In);
    }
    preScanned = true;
    return this;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) CRLEntry(org.bouncycastle.asn1.x509.TBSCertList.CRLEntry) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) ASN1BitString(org.bouncycastle.asn1.ASN1BitString)

Example 63 with OperatorCreationException

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

the class X509CRLStreamWriter method writeToEmptyCrl.

protected void writeToEmptyCrl(OutputStream out) throws IOException {
    ASN1InputStream asn1in = null;
    try {
        asn1in = new ASN1InputStream(crlIn);
        ASN1Sequence certListSeq = (ASN1Sequence) asn1in.readObject();
        CertificateList certList = CertificateList.getInstance(certListSeq);
        X509CRLHolder oldCrl = new X509CRLHolder(certList);
        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(oldCrl.getIssuer(), new Date());
        crlBuilder.addCRL(oldCrl);
        Date now = new Date();
        Date oldNextUpdate = certList.getNextUpdate().getDate();
        Date oldThisUpdate = certList.getThisUpdate().getDate();
        Date nextUpdate = new Date(now.getTime() + (oldNextUpdate.getTime() - oldThisUpdate.getTime()));
        crlBuilder.setNextUpdate(nextUpdate);
        for (Object o : oldCrl.getExtensionOIDs()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) o;
            Extension ext = oldCrl.getExtension(oid);
            if (oid.equals(Extension.cRLNumber)) {
                ASN1OctetString octet = ext.getExtnValue();
                ASN1Integer currentNumber = (ASN1Integer) new ASN1InputStream(octet.getOctets()).readObject();
                ASN1Integer nextNumber = new ASN1Integer(currentNumber.getValue().add(BigInteger.ONE));
                crlBuilder.addExtension(oid, ext.isCritical(), nextNumber);
            } else if (oid.equals(Extension.authorityKeyIdentifier)) {
                crlBuilder.addExtension(oid, ext.isCritical(), ext.getParsedValue());
            }
        }
        for (DERSequence entry : newEntries) {
            // XXX: This is all a bit messy considering the user already passed in the serial, date
            // and reason.
            BigInteger serial = ((ASN1Integer) entry.getObjectAt(0)).getValue();
            Date revokeDate = ((Time) entry.getObjectAt(1)).getDate();
            int reason = CRLReason.unspecified;
            if (entry.size() == 3) {
                Extensions extensions = (Extensions) entry.getObjectAt(2);
                Extension reasonExt = extensions.getExtension(Extension.reasonCode);
                if (reasonExt != null) {
                    reason = ((ASN1Enumerated) reasonExt.getParsedValue()).getValue().intValue();
                }
            }
            crlBuilder.addCRLEntry(serial, revokeDate, reason);
        }
        if (signingAlg == null) {
            signingAlg = oldCrl.toASN1Structure().getSignatureAlgorithm();
        }
        ContentSigner s;
        try {
            s = createContentSigner(signingAlg, key);
            X509CRLHolder newCrl = crlBuilder.build(s);
            out.write(newCrl.getEncoded());
        } catch (OperatorCreationException e) {
            throw new IOException("Could not sign CRL", e);
        }
    } finally {
        IOUtils.closeQuietly(asn1in);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) CertificateList(org.bouncycastle.asn1.x509.CertificateList) ContentSigner(org.bouncycastle.operator.ContentSigner) DERGeneralizedTime(org.bouncycastle.asn1.DERGeneralizedTime) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) Time(org.bouncycastle.asn1.x509.Time) ASN1UTCTime(org.bouncycastle.asn1.ASN1UTCTime) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) Date(java.util.Date) Extension(org.bouncycastle.asn1.x509.Extension) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1Enumerated(org.bouncycastle.asn1.ASN1Enumerated) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) BigInteger(java.math.BigInteger) X509v2CRLBuilder(org.bouncycastle.cert.X509v2CRLBuilder) ASN1Object(org.bouncycastle.asn1.ASN1Object) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 64 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project keystore-explorer by kaikramer.

the class X509CertificateGenerator method generateVersion1.

private X509Certificate generateVersion1(X500Name subject, X500Name issuer, Date validityStart, Date validityEnd, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber) throws CryptoException {
    Date notBefore = validityStart == null ? new Date() : validityStart;
    Date notAfter = validityEnd == null ? new Date(notBefore.getTime() + TimeUnit.DAYS.toMillis(365)) : validityEnd;
    JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(issuer, serialNumber, notBefore, notAfter, subject, publicKey);
    try {
        ContentSigner certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider("BC").build(privateKey);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBuilder.build(certSigner));
    } catch (CertificateException | IllegalStateException | OperatorCreationException ex) {
        throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
    }
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateException(java.security.cert.CertificateException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CryptoException(org.kse.crypto.CryptoException) Date(java.util.Date) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder)

Example 65 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project vespa by vespa-engine.

the class AthenzPrincipalFilterTest method createSelfSignedCertificate.

// TODO Move this to separate athenz module/bundle
private static X509Certificate createSelfSignedCertificate(AthenzIdentity identity) {
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(512);
        KeyPair keyPair = keyGen.genKeyPair();
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").build(keyPair.getPrivate());
        X500Name x500Name = new X500Name("CN=" + identity.getFullName());
        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(x500Name, BigInteger.ONE, new Date(), Date.from(Instant.now().plus(Duration.ofDays(30))), x500Name, keyPair.getPublic());
        return new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(certificateBuilder.build(contentSigner));
    } catch (CertificateException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new RuntimeException(e);
    }
}
Also used : KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateException(java.security.cert.CertificateException) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Date(java.util.Date) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)93 IOException (java.io.IOException)52 ContentSigner (org.bouncycastle.operator.ContentSigner)40 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)38 CertificateException (java.security.cert.CertificateException)32 X509Certificate (java.security.cert.X509Certificate)31 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)23 Date (java.util.Date)21 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)20 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17 CMSException (org.bouncycastle.cms.CMSException)17 X500Name (org.bouncycastle.asn1.x500.X500Name)16 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)16 GeneralName (org.bouncycastle.asn1.x509.GeneralName)15 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 CMSSignedData (org.bouncycastle.cms.CMSSignedData)12 GeneralSecurityException (java.security.GeneralSecurityException)11 BigInteger (java.math.BigInteger)10 NoSuchProviderException (java.security.NoSuchProviderException)10 CertificateEncodingException (java.security.cert.CertificateEncodingException)10