Search in sources :

Example 51 with GeneralName

use of com.android.org.bouncycastle.asn1.x509.GeneralName in project apiRecord by tobecoder2015.

the class CertUtil method genCert.

/**
 * 动态生成服务器证书,并进行CA签授
 *
 * @param issuer       颁发机构
 * @param serverPubKey
 * @param caPriKey
 * @param caPubKey
 * @param host
 * @return
 * @throws Exception
 */
public static X509Certificate genCert(String issuer, PublicKey serverPubKey, PrivateKey caPriKey, PublicKey caPubKey, String host) throws Exception {
    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
    /* String issuer = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=ProxyeeRoot";
        String subject = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + host;*/
    // 根据CA证书subject来动态生成目标服务器证书的issuer和subject
    String subject = Arrays.stream(issuer.split(", ")).map((dn) -> {
        String[] temp = dn.split("=");
        if (temp[0].equalsIgnoreCase("CN")) {
            return temp[0] + "=" + host;
        }
        return dn;
    }).collect(Collectors.joining(", "));
    v3CertGen.reset();
    v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    v3CertGen.setIssuerDN(new X509Principal(issuer));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 10 * ONE_DAY));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 3650 * ONE_DAY));
    v3CertGen.setSubjectDN(new X509Principal(subject));
    v3CertGen.setPublicKey(serverPubKey);
    // SHA256 Chrome需要此哈希算法否则会出现不安全提示
    v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    // SAN扩展 Chrome需要此扩展否则会出现不安全提示
    GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.dNSName, host));
    v3CertGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
    X509Certificate cert = v3CertGen.generateX509Certificate(caPriKey);
    cert.checkValidity(new Date());
    cert.verify(caPubKey);
    return cert;
}
Also used : X509Certificate(java.security.cert.X509Certificate) IntStream(java.util.stream.IntStream) java.security(java.security) X509Principal(org.bouncycastle.jce.X509Principal) Arrays(java.util.Arrays) EncodedKeySpec(java.security.spec.EncodedKeySpec) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CertificateFactory(java.security.cert.CertificateFactory) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) Files(java.nio.file.Files) Date(java.util.Date) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) FileInputStream(java.io.FileInputStream) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) GeneralName(org.bouncycastle.asn1.x509.GeneralName) List(java.util.List) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Paths(java.nio.file.Paths) BigInteger(java.math.BigInteger) URI(java.net.URI) InputStream(java.io.InputStream) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509Principal(org.bouncycastle.jce.X509Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 52 with GeneralName

use of com.android.org.bouncycastle.asn1.x509.GeneralName in project Bytecoder by mirkosertic.

the class ForwardState method updateState.

/**
 * Update the state with the next certificate added to the path.
 *
 * @param cert the certificate which is used to update the state
 */
@Override
public void updateState(X509Certificate cert) throws CertificateException, IOException, CertPathValidatorException {
    if (cert == null)
        return;
    X509CertImpl icert = X509CertImpl.toImpl(cert);
    /* see if certificate key has null parameters */
    if (PKIX.isDSAPublicKeyWithoutParams(icert.getPublicKey())) {
        keyParamsNeededFlag = true;
    }
    /* update certificate */
    this.cert = icert;
    /* update issuer DN */
    issuerDN = cert.getIssuerX500Principal();
    if (!X509CertImpl.isSelfIssued(cert)) {
        /*
             * update traversedCACerts only if this is a non-self-issued
             * intermediate CA cert
             */
        if (!init && cert.getBasicConstraints() != -1) {
            traversedCACerts++;
        }
    }
    /* update subjectNamesTraversed only if this is the EE cert or if
           this cert is not self-issued */
    if (init || !X509CertImpl.isSelfIssued(cert)) {
        X500Principal subjName = cert.getSubjectX500Principal();
        subjectNamesTraversed.add(X500Name.asX500Name(subjName));
        try {
            SubjectAlternativeNameExtension subjAltNameExt = icert.getSubjectAlternativeNameExtension();
            if (subjAltNameExt != null) {
                GeneralNames gNames = subjAltNameExt.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
                for (GeneralName gName : gNames.names()) {
                    subjectNamesTraversed.add(gName.getName());
                }
            }
        } catch (IOException e) {
            if (debug != null) {
                debug.println("ForwardState.updateState() unexpected " + "exception");
                e.printStackTrace();
            }
            throw new CertPathValidatorException(e);
        }
    }
    init = false;
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) GeneralNames(sun.security.x509.GeneralNames) SubjectAlternativeNameExtension(sun.security.x509.SubjectAlternativeNameExtension) X509CertImpl(sun.security.x509.X509CertImpl) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(sun.security.x509.GeneralName) IOException(java.io.IOException)

Example 53 with GeneralName

use of com.android.org.bouncycastle.asn1.x509.GeneralName in project candlepin by candlepin.

the class BouncyCastlePKIUtility method createX509Certificate.

@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {
    X509Certificate caCert = reader.getCACert();
    byte[] publicKeyEncoded = clientKeyPair.getPublic().getEncoded();
    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()), serialNumber, startDate, endDate, new X500Name(dn), SubjectPublicKeyInfo.getInstance(publicKeyEncoded));
    // set key usage - required for proper x509 function
    KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);
    // add SSL extensions - required for proper x509 function
    NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);
    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, certType);
    certGen.addExtension(Extension.keyUsage, false, keyUsage);
    JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
    AuthorityKeyIdentifier aki = extensionUtil.createAuthorityKeyIdentifier(caCert);
    certGen.addExtension(Extension.authorityKeyIdentifier, false, aki.getEncoded());
    certGen.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
    certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    // Add an additional alternative name if provided.
    if (alternateName != null) {
        /*
             Why add the certificate subject again as an alternative name?  RFC 6125 Section 6.4.4
             stipulates that if SANs are provided, a validator MUST use them instead of the certificate
             subject.  If no SANs are present, the RFC allows the validator to use the subject field.  So,
             if we do have an SAN to add, we need to add the subject field again as an SAN.

             See http://stackoverflow.com/questions/5935369 and
             https://tools.ietf.org/html/rfc6125#section-6.4.4 and

             NB: These extensions should *not* be marked critical since the subject field is not empty.
            */
        GeneralName subject = new GeneralName(GeneralName.directoryName, dn);
        GeneralName name = new GeneralName(GeneralName.directoryName, "CN=" + alternateName);
        ASN1Encodable[] altNameArray = { subject, name };
        GeneralNames altNames = GeneralNames.getInstance(new DERSequence(altNameArray));
        certGen.addExtension(Extension.subjectAlternativeName, false, altNames);
    }
    if (extensions != null) {
        for (X509ExtensionWrapper wrapper : extensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            String value = wrapper.getValue() == null ? "" : wrapper.getValue();
            certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DERUTF8String(value));
        }
    }
    if (byteExtensions != null) {
        for (X509ByteExtensionWrapper wrapper : byteExtensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
            certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DEROctetString(value));
        }
    }
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNATURE_ALGO).setProvider(BC_PROVIDER);
    ContentSigner signer;
    try {
        signer = builder.build(reader.getCaKey());
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
    // Generate the certificate
    return new JcaX509CertificateConverter().getCertificate(certGen.build(signer));
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERSequence(org.bouncycastle.asn1.DERSequence) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) NetscapeCertType(org.bouncycastle.asn1.misc.NetscapeCertType) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509ByteExtensionWrapper(org.candlepin.pki.X509ByteExtensionWrapper) X509ExtensionWrapper(org.candlepin.pki.X509ExtensionWrapper) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 54 with GeneralName

use of com.android.org.bouncycastle.asn1.x509.GeneralName in project credhub by cloudfoundry-incubator.

the class CertificateReaderTest method returnsParametersCorrectly.

@Test
public void returnsParametersCorrectly() {
    final String distinguishedName = "O=test-org, ST=Jupiter, C=MilkyWay, CN=test-common-name, OU=test-org-unit, L=Europa";
    final GeneralNames generalNames = new GeneralNames(new GeneralName(GeneralName.dNSName, "SolarSystem"));
    CertificateReader certificateReader = new CertificateReader(CertificateStringConstants.BIG_TEST_CERT);
    assertThat(certificateReader.getAlternativeNames(), equalTo(generalNames));
    assertThat(asList(certificateReader.getExtendedKeyUsage().getUsages()), containsInAnyOrder(KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth));
    assertThat(certificateReader.getKeyUsage().hasUsages(KeyUsage.digitalSignature), equalTo(true));
    assertThat(certificateReader.getSubjectName().toString(), equalTo(distinguishedName));
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Test(org.junit.Test)

Example 55 with GeneralName

use of com.android.org.bouncycastle.asn1.x509.GeneralName in project jruby-openssl by jruby.

the class X509Cert method uniqueExtensions.

private Collection<X509Extension> uniqueExtensions() {
    final Map<ASN1ObjectIdentifier, X509Extension> unique = new LinkedHashMap<ASN1ObjectIdentifier, X509Extension>();
    for (X509Extension current : this.extensions) {
        final ASN1ObjectIdentifier oid = current.getRealObjectID();
        final X509Extension existing = unique.get(oid);
        if (existing == null) {
            unique.put(oid, current);
            continue;
        }
        // commonly used e.g. with subjectAltName || issuserAltName :
        if ("2.5.29.17".equals(oid.getId()) || "2.5.29.18".equals(oid.getId())) {
            final ASN1EncodableVector vec = new ASN1EncodableVector();
            try {
                GeneralName[] n1 = extRealNames(existing);
                for (int i = 0; i < n1.length; i++) vec.add(n1[i]);
                GeneralName[] n2 = extRealNames(current);
                for (int i = 0; i < n2.length; i++) vec.add(n2[i]);
                GeneralNames nn = GeneralNames.getInstance(new DLSequence(vec));
                final X509Extension existingDup = existing.clone();
                existingDup.setRealValue(nn);
                unique.put(oid, existingDup);
            } catch (IOException ex) {
                throw getRuntime().newIOErrorFromException(ex);
            }
            continue;
        }
        // TODO do we need special care for any others here ?!?
        final ASN1EncodableVector vec = new ASN1EncodableVector();
        try {
            final ASN1Encodable existingValue = existing.getRealValue();
            if (existingValue instanceof ASN1Sequence) {
                final ASN1Sequence seq = (ASN1Sequence) existingValue;
                for (int i = 0; i < seq.size(); i++) {
                    vec.add(seq.getObjectAt(i));
                }
            } else {
                vec.add(existingValue);
            }
            vec.add(current.getRealValue());
            // existing.setRealValue( new DLSequence(vec) );
            final X509Extension existingDup = existing.clone();
            existingDup.setRealValue(new DLSequence(vec));
            unique.put(oid, existingDup);
        } catch (IOException ex) {
            throw getRuntime().newIOErrorFromException(ex);
        }
    }
    return unique.values();
}
Also used : IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) DLSequence(org.bouncycastle.asn1.DLSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

GeneralName (org.bouncycastle.asn1.x509.GeneralName)149 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)72 IOException (java.io.IOException)53 DERIA5String (org.bouncycastle.asn1.DERIA5String)38 ArrayList (java.util.ArrayList)37 X500Name (org.bouncycastle.asn1.x500.X500Name)35 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)35 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)34 X509Certificate (java.security.cert.X509Certificate)32 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)28 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)23 BigInteger (java.math.BigInteger)20 List (java.util.List)20 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)19 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)19 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19 GeneralName (org.apache.harmony.security.x509.GeneralName)18 DERSequence (org.bouncycastle.asn1.DERSequence)18 DirectoryString (org.bouncycastle.asn1.x500.DirectoryString)18