Search in sources :

Example 21 with ExtensionsGenerator

use of com.github.zhenwei.core.asn1.x509.ExtensionsGenerator in project vcert-java by Venafi.

the class CertificateRequest method generateCSR.

public void generateCSR() throws VCertException {
    try {
        List<GeneralName> sans = new ArrayList<>();
        PKCS10CertificationRequestBuilder requestBuilder = new JcaPKCS10CertificationRequestBuilder(subject.toX500Principal(), keyPair.getPublic());
        JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm.standardName());
        ContentSigner signer = signerBuilder.build(keyPair.getPrivate());
        for (String san : dnsNames) {
            sans.add(new GeneralName(GeneralName.dNSName, san));
        }
        for (InetAddress san : ipAddresses) {
            sans.add(new GeneralName(GeneralName.iPAddress, new DEROctetString(san.getAddress())));
        }
        for (String san : emailAddresses) {
            sans.add(new GeneralName(GeneralName.rfc822Name, san));
        }
        if (!sans.isEmpty()) {
            GeneralNames names = new GeneralNames(sans.toArray(new GeneralName[] {}));
            ExtensionsGenerator extGen = new ExtensionsGenerator();
            extGen.addExtension(Extension.subjectAlternativeName, false, names);
            requestBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
        }
        PKCS10CertificationRequest certificationRequest = requestBuilder.build(signer);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write("-----BEGIN CERTIFICATE REQUEST-----".getBytes());
        outputStream.write(System.lineSeparator().getBytes());
        outputStream.write(Base64.getMimeEncoder().encode(certificationRequest.getEncoded()));
        outputStream.write(System.lineSeparator().getBytes());
        outputStream.write("-----END CERTIFICATE REQUEST-----".getBytes());
        csr = outputStream.toByteArray();
    } catch (Exception e) {
        throw new VCertException("Unable to generate CSR", e);
    }
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) DEROctetString(org.bouncycastle.asn1.DEROctetString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DEROctetString(org.bouncycastle.asn1.DEROctetString) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) IOException(java.io.IOException) VCertException(com.venafi.vcert.sdk.VCertException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) VCertException(com.venafi.vcert.sdk.VCertException) GeneralName(org.bouncycastle.asn1.x509.GeneralName) InetAddress(java.net.InetAddress)

Example 22 with ExtensionsGenerator

use of com.github.zhenwei.core.asn1.x509.ExtensionsGenerator in project athenz by AthenZ.

the class Crypto method generateX509CSR.

public static String generateX509CSR(PrivateKey privateKey, PublicKey publicKey, String x500Principal, GeneralName[] sanArray) throws OperatorCreationException, IOException {
    // Create Distinguished Name
    X500Principal subject = new X500Principal(x500Principal);
    // Create ContentSigner
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(Crypto.RSA_SHA256);
    ContentSigner signer = csBuilder.build(privateKey);
    // Create the CSR
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(subject, publicKey);
    // Add SubjectAlternativeNames (SAN) if specified
    if (sanArray != null) {
        ExtensionsGenerator extGen = new ExtensionsGenerator();
        GeneralNames subjectAltNames = new GeneralNames(sanArray);
        extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    }
    PKCS10CertificationRequest csr = p10Builder.build(signer);
    // write to openssl PEM format
    PemObject pemObject = new PemObject("CERTIFICATE REQUEST", csr.getEncoded());
    StringWriter strWriter;
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(strWriter = new StringWriter())) {
        pemWriter.writeObject(pemObject);
    }
    return strWriter.toString();
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) PemObject(org.bouncycastle.util.io.pem.PemObject) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Principal(javax.security.auth.x500.X500Principal) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 23 with ExtensionsGenerator

use of com.github.zhenwei.core.asn1.x509.ExtensionsGenerator in project ozone by apache.

the class TestDefaultProfile method getKeyUsageExtension.

/**
 * Returns a extension with Extended Key usage.
 * @param purposeId - Usage that we want to encode.
 * @param critical -  makes the extension critical.
 * @return Extensions.
 */
private Extensions getKeyUsageExtension(KeyPurposeId purposeId, boolean critical) throws IOException {
    ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(purposeId);
    ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
    extensionsGenerator.addExtension(Extension.extendedKeyUsage, critical, extendedKeyUsage);
    return extensionsGenerator.generate();
}
Also used : ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 24 with ExtensionsGenerator

use of com.github.zhenwei.core.asn1.x509.ExtensionsGenerator in project LinLong-Java by zhenwei1108.

the class PKCS10CertificationRequest method getRequestedExtensions.

public Extensions getRequestedExtensions() {
    Attribute[] attributes = getAttributes();
    for (int i = 0; i != attributes.length; i++) {
        Attribute encodable = attributes[i];
        if (encodable.getAttrType() == PKCSObjectIdentifiers.pkcs_9_at_extensionRequest) {
            ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
            ASN1Sequence extensionSequence = ASN1Sequence.getInstance(encodable.getAttrValues().getObjectAt(0));
            for (Enumeration en = extensionSequence.getObjects(); en.hasMoreElements(); ) {
                ASN1Sequence itemSeq = ASN1Sequence.getInstance(en.nextElement());
                boolean critical = itemSeq.size() == 3 && ASN1Boolean.getInstance(itemSeq.getObjectAt(1)).isTrue();
                if (itemSeq.size() == 2) {
                    extensionsGenerator.addExtension(ASN1ObjectIdentifier.getInstance(itemSeq.getObjectAt(0)), false, ASN1OctetString.getInstance(itemSeq.getObjectAt(1)).getOctets());
                } else if (itemSeq.size() == 3) {
                    extensionsGenerator.addExtension(ASN1ObjectIdentifier.getInstance(itemSeq.getObjectAt(0)), critical, ASN1OctetString.getInstance(itemSeq.getObjectAt(2)).getOctets());
                } else {
                    throw new IllegalArgumentException("incorrect sequence size of Extension get " + itemSeq.size() + " expected 2 or three");
                }
            }
            return extensionsGenerator.generate();
        }
    }
    return null;
}
Also used : ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) Enumeration(java.util.Enumeration) Attribute(com.github.zhenwei.core.asn1.pkcs.Attribute) ExtensionsGenerator(com.github.zhenwei.core.asn1.x509.ExtensionsGenerator)

Example 25 with ExtensionsGenerator

use of com.github.zhenwei.core.asn1.x509.ExtensionsGenerator in project LinLong-Java by zhenwei1108.

the class TimeStampTokenGenerator method generate.

/**
 * Generate a TimeStampToken for the passed in request and serialNumber marking it with the passed
 * in genTime.
 *
 * @param request              the originating request.
 * @param serialNumber         serial number for the TimeStampToken
 * @param genTime              token generation time.
 * @param additionalExtensions extra extensions to be added to the response token.
 * @return a TimeStampToken
 * @throws TSPException
 */
public TimeStampToken generate(TimeStampRequest request, BigInteger serialNumber, Date genTime, Extensions additionalExtensions) throws TSPException {
    AlgorithmIdentifier algID = request.getMessageImprintAlgID();
    MessageImprint messageImprint = new MessageImprint(algID, request.getMessageImprintDigest());
    Accuracy accuracy = null;
    if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0) {
        ASN1Integer seconds = null;
        if (accuracySeconds > 0) {
            seconds = new ASN1Integer(accuracySeconds);
        }
        ASN1Integer millis = null;
        if (accuracyMillis > 0) {
            millis = new ASN1Integer(accuracyMillis);
        }
        ASN1Integer micros = null;
        if (accuracyMicros > 0) {
            micros = new ASN1Integer(accuracyMicros);
        }
        accuracy = new Accuracy(seconds, millis, micros);
    }
    ASN1Boolean derOrdering = null;
    if (ordering) {
        derOrdering = ASN1Boolean.getInstance(ordering);
    }
    ASN1Integer nonce = null;
    if (request.getNonce() != null) {
        nonce = new ASN1Integer(request.getNonce());
    }
    ASN1ObjectIdentifier tsaPolicy = tsaPolicyOID;
    if (request.getReqPolicy() != null) {
        tsaPolicy = request.getReqPolicy();
    }
    Extensions respExtensions = request.getExtensions();
    if (additionalExtensions != null) {
        ExtensionsGenerator extGen = new ExtensionsGenerator();
        if (respExtensions != null) {
            for (Enumeration en = respExtensions.oids(); en.hasMoreElements(); ) {
                extGen.addExtension(respExtensions.getExtension(ASN1ObjectIdentifier.getInstance(en.nextElement())));
            }
        }
        for (Enumeration en = additionalExtensions.oids(); en.hasMoreElements(); ) {
            extGen.addExtension(additionalExtensions.getExtension(ASN1ObjectIdentifier.getInstance(en.nextElement())));
        }
        respExtensions = extGen.generate();
    }
    ASN1GeneralizedTime timeStampTime;
    if (resolution == R_SECONDS) {
        timeStampTime = (locale == null) ? new ASN1GeneralizedTime(genTime) : new ASN1GeneralizedTime(genTime, locale);
    } else {
        timeStampTime = createGeneralizedTime(genTime);
    }
    TSTInfo tstInfo = new TSTInfo(tsaPolicy, messageImprint, new ASN1Integer(serialNumber), timeStampTime, accuracy, derOrdering, nonce, tsa, respExtensions);
    try {
        CMSSignedDataGenerator signedDataGenerator = new CMSSignedDataGenerator();
        if (request.getCertReq()) {
            // TODO: do we need to check certs non-empty?
            signedDataGenerator.addCertificates(new CollectionStore(certs));
            signedDataGenerator.addAttributeCertificates(new CollectionStore(attrCerts));
        }
        signedDataGenerator.addCRLs(new CollectionStore(crls));
        if (!otherRevoc.isEmpty()) {
            for (Iterator it = otherRevoc.keySet().iterator(); it.hasNext(); ) {
                ASN1ObjectIdentifier format = (ASN1ObjectIdentifier) it.next();
                signedDataGenerator.addOtherRevocationInfo(format, new CollectionStore((Collection) otherRevoc.get(format)));
            }
        }
        signedDataGenerator.addSignerInfoGenerator(signerInfoGen);
        byte[] derEncodedTSTInfo = tstInfo.getEncoded(ASN1Encoding.DER);
        CMSSignedData signedData = signedDataGenerator.generate(new CMSProcessableByteArray(PKCSObjectIdentifiers.id_ct_TSTInfo, derEncodedTSTInfo), true);
        return new TimeStampToken(signedData);
    } catch (CMSException cmsEx) {
        throw new TSPException("Error generating time-stamp token", cmsEx);
    } catch (IOException e) {
        throw new TSPException("Exception encoding info", e);
    }
}
Also used : CMSSignedDataGenerator(com.github.zhenwei.pkix.cms.CMSSignedDataGenerator) CMSProcessableByteArray(com.github.zhenwei.pkix.cms.CMSProcessableByteArray) Enumeration(java.util.Enumeration) MessageImprint(com.github.zhenwei.pkix.util.asn1.tsp.MessageImprint) ASN1GeneralizedTime(com.github.zhenwei.core.asn1.ASN1GeneralizedTime) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) IOException(java.io.IOException) Extensions(com.github.zhenwei.core.asn1.x509.Extensions) CMSSignedData(com.github.zhenwei.pkix.cms.CMSSignedData) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) ExtensionsGenerator(com.github.zhenwei.core.asn1.x509.ExtensionsGenerator) Accuracy(com.github.zhenwei.pkix.util.asn1.tsp.Accuracy) TSTInfo(com.github.zhenwei.pkix.util.asn1.tsp.TSTInfo) Iterator(java.util.Iterator) Collection(java.util.Collection) ASN1Boolean(com.github.zhenwei.core.asn1.ASN1Boolean) CollectionStore(com.github.zhenwei.core.util.CollectionStore) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) CMSException(com.github.zhenwei.pkix.cms.CMSException)

Aggregations

ExtensionsGenerator (org.bouncycastle.asn1.x509.ExtensionsGenerator)23 JcaPKCS10CertificationRequestBuilder (org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder)16 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)14 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)14 GeneralName (org.bouncycastle.asn1.x509.GeneralName)13 ContentSigner (org.bouncycastle.operator.ContentSigner)13 PKCS10CertificationRequestBuilder (org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder)12 IOException (java.io.IOException)9 PKCS10CertificationRequest (org.bouncycastle.pkcs.PKCS10CertificationRequest)9 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)7 Enumeration (java.util.Enumeration)6 X500Principal (javax.security.auth.x500.X500Principal)5 X500Name (org.bouncycastle.asn1.x500.X500Name)5 JcaPEMWriter (org.bouncycastle.openssl.jcajce.JcaPEMWriter)4 ExtensionsGenerator (com.github.zhenwei.core.asn1.x509.ExtensionsGenerator)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 KeyPair (java.security.KeyPair)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 PrivateKey (java.security.PrivateKey)3 CertificateException (java.security.cert.CertificateException)3