Search in sources :

Example 1 with Extensions

use of org.bouncycastle.asn1.x509.Extensions 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 Extensions

use of org.bouncycastle.asn1.x509.Extensions in project nhin-d by DirectProject.

the class TrustChainValidator method downloadCertFromAIA.

/**
	 * Downloads a cert from the AIA URL and returns the result as certificate.
	 * <br>
	 * AIA extensions may refer to collection files such as P7b or P7c.  For this reason, this method
	 * has been deprecated.
	 * @param url The URL of the certificate that will be downloaded.
	 * @return The certificate downloaded from the AIA extension URL
	 * @deprecated As of 2.1, replaced by {@link #downloadCertsFromAIA(String)}
	 */
protected X509Certificate downloadCertFromAIA(String url) throws NHINDException {
    InputStream inputStream = null;
    X509Certificate retVal = null;
    try {
        // in this case the cert is a binary representation
        // of the CERT URL... transform to a string
        final URL certURL = new URL(url);
        final URLConnection connection = certURL.openConnection();
        // the connection is not actually made until the input stream
        // is open, so set the timeouts before getting the stream
        connection.setConnectTimeout(DEFAULT_URL_CONNECTION_TIMEOUT);
        connection.setReadTimeout(DEFAULT_URL_READ_TIMEOUT);
        // open the URL as in input stream
        inputStream = connection.getInputStream();
        retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inputStream);
    } catch (Exception e) {
        throw new NHINDException("Failed to download certificate from AIA extension.", e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return retVal;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) URL(java.net.URL) URLConnection(java.net.URLConnection) CertificateParsingException(java.security.cert.CertificateParsingException) AddressException(javax.mail.internet.AddressException) PolicyProcessException(org.nhindirect.policy.PolicyProcessException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 3 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project poi by apache.

the class PkiTestUtils method createOcspResp.

public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
    CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
    // request
    //create a nonce to avoid replay attack
    BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
    DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
    Extensions exts = new Extensions(ext);
    OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(certId);
    ocspReqBuilder.setRequestExtensions(exts);
    OCSPReq ocspReq = ocspReqBuilder.build();
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
    basicOCSPRespBuilder.setResponseExtensions(exts);
    // request processing
    Req[] requestList = ocspReq.getRequestList();
    for (Req ocspRequest : requestList) {
        CertificateID certificateID = ocspRequest.getCertID();
        CertificateStatus certificateStatus = CertificateStatus.GOOD;
        if (revoked) {
            certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
        }
        basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
    }
    // basic response generation
    X509CertificateHolder[] chain = null;
    if (!ocspResponderCertificate.equals(issuerCertificate)) {
        // TODO: HorribleProxy can't convert array input params yet
        chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
    }
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
    BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
    OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
    OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
    return ocspResp;
}
Also used : BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Example 4 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project robovm by robovm.

the class X509CRLEntryObject method toString.

public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = System.getProperty("line.separator");
    buf.append("      userCertificate: ").append(this.getSerialNumber()).append(nl);
    buf.append("       revocationDate: ").append(this.getRevocationDate()).append(nl);
    buf.append("       certificateIssuer: ").append(this.getCertificateIssuer()).append(nl);
    Extensions extensions = c.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        if (e.hasMoreElements()) {
            buf.append("   crlEntryExtensions:").append(nl);
            while (e.hasMoreElements()) {
                ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                Extension ext = extensions.getExtension(oid);
                if (ext.getExtnValue() != null) {
                    byte[] octs = ext.getExtnValue().getOctets();
                    ASN1InputStream dIn = new ASN1InputStream(octs);
                    buf.append("                       critical(").append(ext.isCritical()).append(") ");
                    try {
                        if (oid.equals(X509Extension.reasonCode)) {
                            buf.append(CRLReason.getInstance(ASN1Enumerated.getInstance(dIn.readObject()))).append(nl);
                        } else if (oid.equals(X509Extension.certificateIssuer)) {
                            buf.append("Certificate issuer: ").append(GeneralNames.getInstance(dIn.readObject())).append(nl);
                        } else {
                            buf.append(oid.getId());
                            buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
                        }
                    } catch (Exception ex) {
                        buf.append(oid.getId());
                        buf.append(" value = ").append("*****").append(nl);
                    }
                } else {
                    buf.append(nl);
                }
            }
        }
    }
    return buf.toString();
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) X509Extension(org.bouncycastle.asn1.x509.X509Extension) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) Extensions(org.bouncycastle.asn1.x509.Extensions) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) IOException(java.io.IOException) CRLException(java.security.cert.CRLException)

Example 5 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project robovm by robovm.

the class CRLBag method toASN1Primitive.

/**
     * <pre>
     CRLBag ::= SEQUENCE {
     crlId  BAG-TYPE.&id ({CRLTypes}),
     crlValue  [0] EXPLICIT BAG-TYPE.&Type ({CRLTypes}{@crlId})
     }

     x509CRL BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}
     -- DER-encoded X.509 CRL stored in OCTET STRING

     CRLTypes BAG-TYPE ::= {
     x509CRL,
     ... -- For future extensions
     }
       </pre>
     */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(crlId);
    v.add(new DERTaggedObject(0, crlValue));
    return new DERSequence(v);
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector)

Aggregations

ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)67 Extensions (org.bouncycastle.asn1.x509.Extensions)58 Extension (org.bouncycastle.asn1.x509.Extension)54 IOException (java.io.IOException)44 DEROctetString (org.bouncycastle.asn1.DEROctetString)38 HashSet (java.util.HashSet)35 Enumeration (java.util.Enumeration)34 X500Name (org.bouncycastle.asn1.x500.X500Name)31 Date (java.util.Date)29 BigInteger (java.math.BigInteger)27 DERIA5String (org.bouncycastle.asn1.DERIA5String)26 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)25 X509Certificate (java.security.cert.X509Certificate)24 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)23 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)23 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)23 GeneralName (org.bouncycastle.asn1.x509.GeneralName)23 ContentSigner (org.bouncycastle.operator.ContentSigner)22 ArrayList (java.util.ArrayList)21 Set (java.util.Set)21