Search in sources :

Example 81 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames in project milo by eclipse.

the class CertificateUtil method generateCsr.

/**
 * Generate a {@link PKCS10CertificationRequest}.
 *
 * @param keyPair            the {@link KeyPair} containing Public and Private keys.
 * @param subject            the subject name {@link X500Name}.
 * @param sanUri             the URI to request in the SAN.
 * @param sanDnsNames        the DNS names to request in the SAN.
 * @param sanIpAddresses     the IP addresses to request in the SAN.
 * @param signatureAlgorithm the signature algorithm to use when generating the signature to validate the
 *                           certificate.
 * @return a {@link PKCS10CertificationRequest}.
 * @throws Exception if creating the signing request fails for any reason.
 */
public static PKCS10CertificationRequest generateCsr(KeyPair keyPair, X500Name subject, String sanUri, List<String> sanDnsNames, List<String> sanIpAddresses, String signatureAlgorithm) throws Exception {
    PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(subject, SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
    List<GeneralName> generalNames = new ArrayList<>();
    generalNames.add(new GeneralName(SUBJECT_ALT_NAME_URI, sanUri));
    sanDnsNames.stream().map(n -> new GeneralName(SUBJECT_ALT_NAME_DNS_NAME, n)).forEach(generalNames::add);
    sanIpAddresses.stream().map(n -> new GeneralName(SUBJECT_ALT_NAME_IP_ADDRESS, n)).forEach(generalNames::add);
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(generalNames.toArray(new GeneralName[0])));
    builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);
    ContentSigner signer = signerBuilder.build(keyPair.getPrivate());
    return builder.build(signer);
}
Also used : X509Certificate(java.security.cert.X509Certificate) KeyPair(java.security.KeyPair) DigestUtil.sha1(org.eclipse.milo.opcua.stack.core.util.DigestUtil.sha1) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertificateFactory(java.security.cert.CertificateFactory) PKCSObjectIdentifiers(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers) Extension(org.bouncycastle.asn1.x509.Extension) ContentSigner(org.bouncycastle.operator.ContentSigner) IETFUtils(org.bouncycastle.asn1.x500.style.IETFUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) CertificateParsingException(java.security.cert.CertificateParsingException) ArrayList(java.util.ArrayList) X500Name(org.bouncycastle.asn1.x500.X500Name) ByteArrayInputStream(java.io.ByteArrayInputStream) RFC4519Style(org.bouncycastle.asn1.x500.style.RFC4519Style) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) StringWriter(java.io.StringWriter) Collection(java.util.Collection) MiscPEMGenerator(org.bouncycastle.openssl.MiscPEMGenerator) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Collectors(java.util.stream.Collectors) Bytes(com.google.common.primitives.Bytes) Objects(java.util.Objects) List(java.util.List) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Certificate(java.security.cert.Certificate) PemWriter(org.bouncycastle.util.io.pem.PemWriter) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) UaException(org.eclipse.milo.opcua.stack.core.UaException) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Collections(java.util.Collections) InputStream(java.io.InputStream) CertificateEncodingException(java.security.cert.CertificateEncodingException) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) 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) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 82 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames in project milo by eclipse.

the class CertificateUtil method generateCsr.

/**
 * Generate a {@link PKCS10CertificationRequest} for the provided {@code certificate} and {@code keyPair}.
 *
 * @param keyPair     the {@link KeyPair} for {@code certificate}.
 * @param certificate the {@link X509Certificate} to request signing for.
 * @return a {@link PKCS10CertificationRequest}.
 * @throws Exception if creating the signing request fails for any reason.
 */
public static PKCS10CertificationRequest generateCsr(KeyPair keyPair, X509Certificate certificate) throws Exception {
    PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(certificate.getSubjectX500Principal(), certificate.getPublicKey());
    GeneralNames subjectAltNames = new GeneralNames(getSubjectAltNames(certificate).toArray(new GeneralName[0]));
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(certificate.getSigAlgName());
    ContentSigner signer = signerBuilder.build(keyPair.getPrivate());
    return builder.build(signer);
}
Also used : JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 83 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames in project tez by apache.

the class TestSecureShuffle method generateCertificate.

/**
 * This is a copied version of hadoop's KeyStoreTestUtil.generateCertificate, which takes care of setting
 * IP address as a SSL Subject Alternative Name (SAN). Without this, SSL shuffle failed with async http client.
 * Introduced by TEZ-4342.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws Exception {
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());
    KeyPair keyPair = pair;
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    String hostName = InetAddress.getLocalHost().getHostName();
    String hostAddress = InetAddress.getLocalHost().getHostAddress();
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.iPAddress, hostAddress), new GeneralName(GeneralName.dNSName, hostName), new GeneralName(GeneralName.dNSName, "localhost") }));
    X500Principal dnName = new X500Principal(dn);
    certGen.setSerialNumber(sn);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(from);
    certGen.setNotAfter(to);
    certGen.setSubjectDN(dnName);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(algorithm);
    X509Certificate cert = certGen.generate(pair.getPrivate());
    return cert;
}
Also used : KeyPair(java.security.KeyPair) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) BigInteger(java.math.BigInteger) SecureRandom(java.security.SecureRandom) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 84 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames in project xipki by xipki.

the class XijsonExtensions method createRequestedSubjectAltNames.

// method toOidList
GeneralNames createRequestedSubjectAltNames(X500Name requestedSubject, X500Name grantedSubject, Map<ASN1ObjectIdentifier, Extension> requestedExtensions) throws BadCertTemplateException {
    Extension extn = (requestedExtensions == null) ? null : requestedExtensions.get(Extension.subjectAlternativeName);
    ASN1Encodable extValue = (extn == null) ? null : extn.getParsedValue();
    if (extValue == null && subjectToSubjectAltNameModes == null) {
        return null;
    }
    GeneralNames reqNames = (extValue == null) ? null : GeneralNames.getInstance(extValue);
    if (subjectAltNameModes == null && subjectToSubjectAltNameModes == null) {
        return reqNames;
    }
    List<GeneralName> grantedNames = new LinkedList<>();
    // copy the required attributes of Subject
    if (subjectToSubjectAltNameModes != null) {
        for (Entry<ASN1ObjectIdentifier, GeneralNameTag> entry : subjectToSubjectAltNameModes.entrySet()) {
            ASN1ObjectIdentifier attrType = entry.getKey();
            GeneralNameTag tag = entry.getValue();
            RDN[] rdns = grantedSubject.getRDNs(attrType);
            if (rdns == null || rdns.length == 0) {
                rdns = requestedSubject.getRDNs(attrType);
            }
            if (rdns == null || rdns.length == 0) {
                continue;
            }
            for (RDN rdn : rdns) {
                String rdnValue = X509Util.rdnValueToString(rdn.getFirst().getValue());
                GeneralName gn;
                switch(tag) {
                    case rfc822Name:
                        gn = new GeneralName(tag.getTag(), rdnValue.toLowerCase());
                        break;
                    case IPAddress:
                        gn = new GeneralName(tag.getTag(), rdnValue);
                        break;
                    case uniformResourceIdentifier:
                        gn = new GeneralName(tag.getTag(), rdnValue);
                        break;
                    case DNSName:
                    case directoryName:
                    case registeredID:
                        gn = new GeneralName(tag.getTag(), rdnValue);
                        break;
                    default:
                        throw new IllegalStateException("unsupported GeneralName tag " + tag);
                }
                if (!grantedNames.contains(gn)) {
                    grantedNames.add(gn);
                }
            }
        }
    }
    // copy the requested SubjectAltName entries
    if (reqNames != null) {
        GeneralName[] reqL = reqNames.getNames();
        for (GeneralName generalName : reqL) {
            GeneralName gn = BaseCertprofile.createGeneralName(generalName, subjectAltNameModes);
            if (!grantedNames.contains(gn)) {
                grantedNames.add(gn);
            }
        }
    }
    return grantedNames.isEmpty() ? null : new GeneralNames(grantedNames.toArray(new GeneralName[0]));
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) RDN(org.bouncycastle.asn1.x500.RDN)

Example 85 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames in project service-proxy by membrane.

the class SoapAndInternalProxyTest method generateKeyAndCert.

private void generateKeyAndCert() throws NoSuchAlgorithmException, OperatorCreationException, CertificateException, IOException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    KeyPair keypair = keyGen.generateKeyPair();
    PublicKey publicKey = keypair.getPublic();
    PrivateKey privateKey = keypair.getPrivate();
    String signerAlgo = "SHA256withRSA";
    ContentSigner signGen = new JcaContentSignerBuilder(signerAlgo).build(privateKey);
    X500Name subject = X500Name.getInstance(new X500Principal("CN=predic8 GmbH, OU=Demo, O=Demo, C=DE").getEncoded());
    SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(subject, new BigInteger("1"), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000), subject, keyInfo);
    List<GeneralName> namesList = new ArrayList<>();
    namesList.add(new GeneralName(2, "localhost"));
    GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[] {}));
    certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(certBuilder.build(signGen));
    StringWriter sw = new StringWriter();
    try (JcaPEMWriter pw = new JcaPEMWriter(sw)) {
        pw.writeObject(cert);
    }
    certificate = sw.toString();
    sw = new StringWriter();
    JcaPEMWriter writer2 = new JcaPEMWriter(sw);
    writer2.writeObject(privateKey);
    writer2.close();
    key = sw.toString();
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ArrayList(java.util.ArrayList) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) StringWriter(java.io.StringWriter) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)140 GeneralName (org.bouncycastle.asn1.x509.GeneralName)124 IOException (java.io.IOException)68 X509Certificate (java.security.cert.X509Certificate)46 X500Name (org.bouncycastle.asn1.x500.X500Name)45 ContentSigner (org.bouncycastle.operator.ContentSigner)41 ArrayList (java.util.ArrayList)40 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)40 BigInteger (java.math.BigInteger)33 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)32 List (java.util.List)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)27 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)27 Date (java.util.Date)26 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)26 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)25 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)23 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)23 X500Principal (javax.security.auth.x500.X500Principal)22 DERIA5String (org.bouncycastle.asn1.DERIA5String)20