Search in sources :

Example 1 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerBuilder     IssuerDN builder
     * @param subjectBuilder    SubjectDN builder
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new //
    JcaX509v3CertificateBuilder(//
    issuerDN, //
    serial, //
    new Date(), //
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
    subjectDN, //
    pubKey);
    // add subjectAlternativeName extension
    boolean critical = subjectDN.getRDNs().length == 0;
    ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertException(org.bouncycastle.cert.CertException) Date(java.util.Date) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 2 with OperatorCreationException

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

the class CMSSignedDataGenerator method generate.

/**
     * Similar method to the other generate methods. The additional argument
     * addDefaultAttributes indicates whether or not a default set of signed attributes
     * need to be added automatically. If the argument is set to false, no
     * attributes will get added at all.
     * @deprecated use setDirectSignature() on SignerInformationGenerator.
     */
public CMSSignedData generate(String eContentType, final CMSProcessable content, boolean encapsulate, Provider sigProvider, boolean addDefaultAttributes) throws NoSuchAlgorithmException, CMSException {
    boolean isCounterSignature = (eContentType == null);
    final ASN1ObjectIdentifier contentTypeOID = isCounterSignature ? null : new ASN1ObjectIdentifier(eContentType);
    for (Iterator it = signerInfs.iterator(); it.hasNext(); ) {
        SignerInf signer = (SignerInf) it.next();
        try {
            signerGens.add(signer.toSignerInfoGenerator(rand, sigProvider, addDefaultAttributes));
        } catch (OperatorCreationException e) {
            throw new CMSException("exception creating signerInf", e);
        } catch (IOException e) {
            throw new CMSException("exception encoding attributes", e);
        } catch (CertificateEncodingException e) {
            throw new CMSException("error creating sid.", e);
        }
    }
    signerInfs.clear();
    if (content != null) {
        return generate(new CMSTypedData() {

            public ASN1ObjectIdentifier getContentType() {
                return contentTypeOID;
            }

            public void write(OutputStream out) throws IOException, CMSException {
                content.write(out);
            }

            public Object getContent() {
                return content.getContent();
            }
        }, encapsulate);
    } else {
        return generate(new CMSAbsentContent(contentTypeOID), encapsulate);
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 3 with OperatorCreationException

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

the class SignerInformation method doVerify.

private boolean doVerify(SignerInformationVerifier verifier) throws CMSException {
    String encName = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID());
    ContentVerifier contentVerifier;
    try {
        contentVerifier = verifier.getContentVerifier(encryptionAlgorithm, info.getDigestAlgorithm());
    } catch (OperatorCreationException e) {
        throw new CMSException("can't create content verifier: " + e.getMessage(), e);
    }
    try {
        OutputStream sigOut = contentVerifier.getOutputStream();
        if (resultDigest == null) {
            DigestCalculator calc = verifier.getDigestCalculator(this.getDigestAlgorithmID());
            if (content != null) {
                OutputStream digOut = calc.getOutputStream();
                if (signedAttributeSet == null) {
                    if (contentVerifier instanceof RawContentVerifier) {
                        content.write(digOut);
                    } else {
                        OutputStream cOut = new TeeOutputStream(digOut, sigOut);
                        content.write(cOut);
                        cOut.close();
                    }
                } else {
                    content.write(digOut);
                    sigOut.write(this.getEncodedSignedAttributes());
                }
                digOut.close();
            } else if (signedAttributeSet != null) {
                sigOut.write(this.getEncodedSignedAttributes());
            } else {
                // TODO Get rid of this exception and just treat content==null as empty not missing?
                throw new CMSException("data not encapsulated in signature - use detached constructor.");
            }
            resultDigest = calc.getDigest();
        } else {
            if (signedAttributeSet == null) {
                if (content != null) {
                    content.write(sigOut);
                }
            } else {
                sigOut.write(this.getEncodedSignedAttributes());
            }
        }
        sigOut.close();
    } catch (IOException e) {
        throw new CMSException("can't process mime object to create signature.", e);
    } catch (OperatorCreationException e) {
        throw new CMSException("can't create digest calculator: " + e.getMessage(), e);
    }
    // RFC 3852 11.1 Check the content-type attribute is correct
    {
        ASN1Primitive validContentType = getSingleValuedSignedAttribute(CMSAttributes.contentType, "content-type");
        if (validContentType == null) {
            if (!isCounterSignature && signedAttributeSet != null) {
                throw new CMSException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
            }
        } else {
            if (isCounterSignature) {
                throw new CMSException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
            }
            if (!(validContentType instanceof ASN1ObjectIdentifier)) {
                throw new CMSException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
            }
            ASN1ObjectIdentifier signedContentType = (ASN1ObjectIdentifier) validContentType;
            if (!signedContentType.equals(contentType)) {
                throw new CMSException("content-type attribute value does not match eContentType");
            }
        }
    }
    // RFC 3852 11.2 Check the message-digest attribute is correct
    {
        ASN1Primitive validMessageDigest = getSingleValuedSignedAttribute(CMSAttributes.messageDigest, "message-digest");
        if (validMessageDigest == null) {
            if (signedAttributeSet != null) {
                throw new CMSException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
            }
        } else {
            if (!(validMessageDigest instanceof ASN1OctetString)) {
                throw new CMSException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
            }
            ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest;
            if (!Arrays.constantTimeAreEqual(resultDigest, signedMessageDigest.getOctets())) {
                throw new CMSSignerDigestMismatchException("message-digest attribute value does not match calculated value");
            }
        }
    }
    // RFC 3852 11.4 Validate countersignature attribute(s)
    {
        AttributeTable signedAttrTable = this.getSignedAttributes();
        if (signedAttrTable != null && signedAttrTable.getAll(CMSAttributes.counterSignature).size() > 0) {
            throw new CMSException("A countersignature attribute MUST NOT be a signed attribute");
        }
        AttributeTable unsignedAttrTable = this.getUnsignedAttributes();
        if (unsignedAttrTable != null) {
            ASN1EncodableVector csAttrs = unsignedAttrTable.getAll(CMSAttributes.counterSignature);
            for (int i = 0; i < csAttrs.size(); ++i) {
                Attribute csAttr = (Attribute) csAttrs.get(i);
                if (csAttr.getAttrValues().size() < 1) {
                    throw new CMSException("A countersignature attribute MUST contain at least one AttributeValue");
                }
            // Note: We don't recursively validate the countersignature value
            }
        }
    }
    try {
        if (signedAttributeSet == null && resultDigest != null) {
            if (contentVerifier instanceof RawContentVerifier) {
                RawContentVerifier rawVerifier = (RawContentVerifier) contentVerifier;
                if (encName.equals("RSA")) {
                    DigestInfo digInfo = new DigestInfo(new AlgorithmIdentifier(digestAlgorithm.getAlgorithm(), DERNull.INSTANCE), resultDigest);
                    return rawVerifier.verify(digInfo.getEncoded(ASN1Encoding.DER), this.getSignature());
                }
                return rawVerifier.verify(resultDigest, this.getSignature());
            }
        }
        return contentVerifier.verify(this.getSignature());
    } catch (IOException e) {
        throw new CMSException("can't process mime object to create signature.", e);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) Attribute(org.bouncycastle.asn1.cms.Attribute) ContentVerifier(org.bouncycastle.operator.ContentVerifier) RawContentVerifier(org.bouncycastle.operator.RawContentVerifier) OutputStream(java.io.OutputStream) TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) DigestCalculator(org.bouncycastle.operator.DigestCalculator) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) RawContentVerifier(org.bouncycastle.operator.RawContentVerifier) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 4 with OperatorCreationException

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

the class JcaContentVerifierProviderBuilder method createSignatureStream.

private SignatureOutputStream createSignatureStream(AlgorithmIdentifier algorithm, PublicKey publicKey) throws OperatorCreationException {
    try {
        Signature sig = helper.createSignature(algorithm);
        sig.initVerify(publicKey);
        return new SignatureOutputStream(sig);
    } catch (GeneralSecurityException e) {
        throw new OperatorCreationException("exception on setup: " + e, e);
    }
}
Also used : Signature(java.security.Signature) GeneralSecurityException(java.security.GeneralSecurityException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 5 with OperatorCreationException

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

the class JcaDigestCalculatorProviderBuilder method build.

public DigestCalculatorProvider build() throws OperatorCreationException {
    return new DigestCalculatorProvider() {

        public DigestCalculator get(final AlgorithmIdentifier algorithm) throws OperatorCreationException {
            final DigestOutputStream stream;
            try {
                MessageDigest dig = helper.createDigest(algorithm);
                stream = new DigestOutputStream(dig);
            } catch (GeneralSecurityException e) {
                throw new OperatorCreationException("exception on setup: " + e, e);
            }
            return new DigestCalculator() {

                public AlgorithmIdentifier getAlgorithmIdentifier() {
                    return algorithm;
                }

                public OutputStream getOutputStream() {
                    return stream;
                }

                public byte[] getDigest() {
                    return stream.getDigest();
                }
            };
        }
    };
}
Also used : DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) GeneralSecurityException(java.security.GeneralSecurityException) DigestCalculator(org.bouncycastle.operator.DigestCalculator) MessageDigest(java.security.MessageDigest) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

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