Example usage for org.bouncycastle.asn1.x509 GeneralNames GeneralNames

List of usage examples for org.bouncycastle.asn1.x509 GeneralNames GeneralNames

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 GeneralNames GeneralNames.

Prototype

private GeneralNames(ASN1Sequence seq) 

Source Link

Usage

From source file:it.zero11.acme.utils.X509Utils.java

License:Apache License

public static PKCS10CertificationRequest generateCSR(String[] commonNames, KeyPair pair)
        throws OperatorCreationException, IOException {
    X500NameBuilder namebuilder = new X500NameBuilder(X500Name.getDefaultStyle());
    namebuilder.addRDN(BCStyle.CN, commonNames[0]);

    List<GeneralName> subjectAltNames = new ArrayList<>(commonNames.length);
    for (String cn : commonNames)
        subjectAltNames.add(new GeneralName(GeneralName.dNSName, cn));
    GeneralNames subjectAltName = new GeneralNames(subjectAltNames.toArray(new GeneralName[0]));

    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName.toASN1Primitive());

    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),
            pair.getPublic());//from  w ww.  ja  va2s .  c  o m
    p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    PKCS10CertificationRequest request = p10Builder.build(signer);
    return request;
}

From source file:krypto.KryptoService.java

License:Apache License

/**
 * Erzeugt ein x509 v3-Zertifikat, das 1 Tag lang gltig ist.
 * @return/*from  w w  w  .ja  v  a2 s .  com*/
 * @throws Exception
 */
public static X509Certificate generateCertificate(String algorithm) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    KeyPair pair = null;

    try {
        pair = generateKeyPair(algorithm, 1024);
    } catch (Exception e) {
        try {
            pair = generateKeyPair(algorithm, 512);
        } catch (Exception e2) {
            System.out.println(e2.getMessage());
        }
    }

    long day = 24 * 60 * 60 * 1000; // 1 Tag gltig

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X509Name(new X500Principal("CN=Test Certificate").getName()));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 500000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + day));
    certGen.setSubjectDN(new X509Name(new X500Principal("CN=Test Certificate").getName()));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

    X509Certificate cert = null;
    try {
        cert = certGen.generate(pair.getPrivate(), "BC");
    } catch (CertificateEncodingException e) {
        System.out.println("CertificateEncodingException");
    } catch (InvalidKeyException e2) {
        System.out.println("InvalidKeyException: " + e2.getMessage());
    } catch (Exception e3) {
        // do nothing
    }

    return cert;

}

From source file:mitm.common.security.certificate.impl.StandardX509CertificateBuilder.java

License:Open Source License

protected AuthorityKeyIdentifier getAuthorityKeyIdentifier(X509Certificate issuerCertificate)
        throws CertificateParsingException, IOException {
    X509CertificateInspector inspector = new X509CertificateInspector(issuerCertificate);

    /*//from   ww  w  .ja v  a2 s . c  o m
     * We must add the issuer of the issuer certificate! not the subject of the issuer certificate
     * The subject / serial number is already contained in the certificate to be issued. The 
     * issuer of the issuer is added to identify multiple paths if an intermediate can be signed
     * by multiple ca's
     */
    GeneralNames names = new GeneralNames(new GeneralName(inspector.getIssuerX500Name()));

    AuthorityKeyIdentifier authorityKeyIdentifier;

    byte[] subjectKeyIdentifier = inspector.getSubjectKeyIdentifier();

    if (subjectKeyIdentifier != null) {
        authorityKeyIdentifier = new AuthorityKeyIdentifier(subjectKeyIdentifier, names,
                issuerCertificate.getSerialNumber());
    } else {
        authorityKeyIdentifier = new AuthorityKeyIdentifier(names, issuerCertificate.getSerialNumber());
    }

    return authorityKeyIdentifier;
}

From source file:net.java.bd.tools.security.SecurityUtil.java

License:Open Source License

GeneralNames getRfc822Name(String name) {
    GeneralName gn = new GeneralName(GeneralName.rfc822Name, new DERIA5String(name));
    DERConstructedSequence seq = new DERConstructedSequence();
    seq.addObject(gn);/*from  w w w .  j a v a2  s  .  com*/
    return new GeneralNames(seq);
}

From source file:net.laubenberger.bogatyr.service.crypto.CertificateProviderImpl.java

License:Open Source License

@Override
public X509Certificate generateCertificate(final KeyPair pair, final String issuerDN, final String subjectDN,
        final String generalName, final Date start, final Date end)
        throws NoSuchAlgorithmException, IllegalStateException, CertificateEncodingException,
        InvalidKeyException, NoSuchProviderException, SecurityException, SignatureException { //$JUnit$
    if (null == pair) {
        throw new RuntimeExceptionIsNull("pair"); //$NON-NLS-1$
    }// w  ww . jav  a  2s.c o  m
    if (null == issuerDN) {
        throw new RuntimeExceptionIsNull("issuerDN"); //$NON-NLS-1$
    }
    if (!HelperString.isValid(issuerDN)) {
        throw new RuntimeExceptionIsEmpty("issuerDN"); //$NON-NLS-1$
    }
    if (null == subjectDN) {
        throw new RuntimeExceptionIsNull("subjectDN"); //$NON-NLS-1$
    }
    if (!HelperString.isValid(subjectDN)) {
        throw new RuntimeExceptionIsEmpty("subjectDN"); //$NON-NLS-1$
    }
    if (null == generalName) {
        throw new RuntimeExceptionIsNull("generalName"); //$NON-NLS-1$
    }
    if (!HelperString.isValid(generalName)) {
        throw new RuntimeExceptionIsEmpty("generalName"); //$NON-NLS-1$
    }
    if (null == start) {
        throw new RuntimeExceptionIsNull("start"); //$NON-NLS-1$
    }
    if (null == end) {
        throw new RuntimeExceptionIsNull("end"); //$NON-NLS-1$
    }
    if (start.after(end)) {
        throw new RuntimeExceptionMustBeBefore("start", start, end); //$NON-NLS-1$
    }

    // generate the certificate
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal(issuerDN));
    certGen.setNotBefore(start);
    certGen.setNotAfter(end);
    certGen.setSubjectDN(new X500Principal(subjectDN));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //$NON-NLS-1$

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, generalName)));

    return certGen.generate(pair.getPrivate(), provider.getName());
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

License:Apache License

/**
 * Builds and signs a certificate. The certificate will be build on the given subject-public-key and signed with
 * the given issuer-private-key. The issuer and subject will be identified in the strings provided.
 *
 * @return A signed X509Certificate//from ww  w  .  ja v  a  2  s  .  co  m
 * @throws Exception
 */
public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey,
        PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject,
        Map<String, String> customAttrs, String type) throws Exception {
    // Dates are converted to GMT/UTC inside the cert builder 
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    Date expire = new GregorianCalendar(CERT_EXPIRE_YEAR, 0, 1).getTime();
    X509v3CertificateBuilder certV3Bldr = new JcaX509v3CertificateBuilder(issuer, serialNumber, now, // Valid from now...
            expire, // until CERT_EXPIRE_YEAR
            subject, subjectPublicKey);
    JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
    // Create certificate extensions
    if ("ROOTCA".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else if ("INTERMEDIATE".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else {
        // Subject Alternative Name
        GeneralName[] genNames = null;
        if (customAttrs != null && !customAttrs.isEmpty()) {
            genNames = new GeneralName[customAttrs.size()];
            Iterator<Map.Entry<String, String>> it = customAttrs.entrySet().iterator();
            int idx = 0;
            while (it.hasNext()) {
                Map.Entry<String, String> pair = it.next();
                //genNames[idx] = new GeneralName(GeneralName.otherName, new DERUTF8String(pair.getKey() + ";" + pair.getValue()));
                DERSequence othernameSequence = new DERSequence(
                        new ASN1Encodable[] { new ASN1ObjectIdentifier(pair.getKey()),
                                new DERTaggedObject(true, 0, new DERUTF8String(pair.getValue())) });
                genNames[idx] = new GeneralName(GeneralName.otherName, othernameSequence);
                idx++;
            }
        }
        if (genNames != null) {
            certV3Bldr = certV3Bldr.addExtension(Extension.subjectAlternativeName, false,
                    new GeneralNames(genNames));
        }
    }
    // Basic extension setup
    certV3Bldr = certV3Bldr
            .addExtension(Extension.authorityKeyIdentifier, false,
                    extensionUtil.createAuthorityKeyIdentifier(signerPublicKey))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extensionUtil.createSubjectKeyIdentifier(subjectPublicKey));
    // CRL Distribution Points
    DistributionPointName distPointOne = new DistributionPointName(
            new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, CRL_URL)));
    DistributionPoint[] distPoints = new DistributionPoint[1];
    distPoints[0] = new DistributionPoint(distPointOne, null, null);
    certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints));
    // OCSP endpoint
    GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, OCSP_URL);
    AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
            X509ObjectIdentifiers.ocspAccessMethod, ocspName);
    certV3Bldr.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    // Create the key signer
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNER_ALGORITHM);
    builder.setProvider(BC_PROVIDER_NAME);
    ContentSigner signer = builder.build(signerPrivateKey);
    return new JcaX509CertificateConverter().setProvider(BC_PROVIDER_NAME)
            .getCertificate(certV3Bldr.build(signer));
}

From source file:net.maritimecloud.pki.CertificateBuilder.java

License:Apache License

/**
 * Builds and signs a certificate. The certificate will be build on the given subject-public-key and signed with
 * the given issuer-private-key. The issuer and subject will be identified in the strings provided.
 *
 * @param serialNumber The serialnumber of the new certificate.
 * @param signerPrivateKey Private key for signing the certificate
 * @param signerPublicKey Public key of the signing certificate
 * @param subjectPublicKey Public key for the new certificate
 * @param issuer DN of the signing certificate
 * @param subject DN of the new certificate
 * @param customAttrs The custom MC attributes to include in the certificate
 * @param type Type of certificate, can be "ROOT", "INTERMEDIATE" or "ENTITY".
 * @param ocspUrl OCSP endpoint//from w ww. jav  a2s . c  o m
 * @param crlUrl CRL endpoint - can be null
 * @return A signed X509Certificate
 * @throws Exception Throws exception on certificate generation errors.
 */
public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey,
        PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject,
        Map<String, String> customAttrs, String type, String ocspUrl, String crlUrl) throws Exception {
    // Dates are converted to GMT/UTC inside the cert builder
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    Date expire = new GregorianCalendar(CERT_EXPIRE_YEAR, 0, 1).getTime();
    X509v3CertificateBuilder certV3Bldr = new JcaX509v3CertificateBuilder(issuer, serialNumber, now, // Valid from now...
            expire, // until CERT_EXPIRE_YEAR
            subject, subjectPublicKey);
    JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
    // Create certificate extensions
    if ("ROOTCA".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else if ("INTERMEDIATE".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else {
        // Subject Alternative Name
        GeneralName[] genNames = null;
        if (customAttrs != null && !customAttrs.isEmpty()) {
            genNames = new GeneralName[customAttrs.size()];
            Iterator<Map.Entry<String, String>> it = customAttrs.entrySet().iterator();
            int idx = 0;
            while (it.hasNext()) {
                Map.Entry<String, String> pair = it.next();
                if (PKIConstants.X509_SAN_DNSNAME.equals(pair.getKey())) {
                    genNames[idx] = new GeneralName(GeneralName.dNSName, pair.getValue());
                } else {
                    //genNames[idx] = new GeneralName(GeneralName.otherName, new DERUTF8String(pair.getKey() + ";" + pair.getValue()));
                    DERSequence othernameSequence = new DERSequence(
                            new ASN1Encodable[] { new ASN1ObjectIdentifier(pair.getKey()),
                                    new DERTaggedObject(true, 0, new DERUTF8String(pair.getValue())) });
                    genNames[idx] = new GeneralName(GeneralName.otherName, othernameSequence);
                }
                idx++;
            }
        }
        if (genNames != null) {
            certV3Bldr = certV3Bldr.addExtension(Extension.subjectAlternativeName, false,
                    new GeneralNames(genNames));
        }
    }
    // Basic extension setup
    certV3Bldr = certV3Bldr
            .addExtension(Extension.authorityKeyIdentifier, false,
                    extensionUtil.createAuthorityKeyIdentifier(signerPublicKey))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extensionUtil.createSubjectKeyIdentifier(subjectPublicKey));
    // CRL Distribution Points
    DistributionPointName distPointOne = new DistributionPointName(
            new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, crlUrl)));
    DistributionPoint[] distPoints = new DistributionPoint[1];
    distPoints[0] = new DistributionPoint(distPointOne, null, null);
    certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints));
    // OCSP endpoint - is not available for the CAs
    if (ocspUrl != null) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUrl);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certV3Bldr.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }
    // Create the key signer
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNER_ALGORITHM);
    builder.setProvider(BC_PROVIDER_NAME);
    ContentSigner signer = builder.build(signerPrivateKey);
    return new JcaX509CertificateConverter().setProvider(BC_PROVIDER_NAME)
            .getCertificate(certV3Bldr.build(signer));
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateBuilderHelper.java

License:BSD License

/**
 * Generate a single distribution point where the names contains each URI.
 *//*from w ww  .j a va2  s  .co  m*/
private CRLDistPoint convertToCrlDistributionPoint(URI[] uris) {
    GeneralName[] seq = new GeneralName[uris.length];
    for (int i = 0; i < uris.length; ++i) {
        seq[i] = new GeneralName(GeneralName.uniformResourceIdentifier, uris[i].toString());
    }
    GeneralNames names = new GeneralNames(seq);
    DistributionPointName distributionPoint = new DistributionPointName(names);
    DistributionPoint[] dps = { new DistributionPoint(distributionPoint, null, null) };
    return new CRLDistPoint(dps);
}

From source file:net.sf.keystore_explorer.gui.crypto.generalname.JGeneralNames.java

License:Open Source License

/**
 * Get general names./*w w w  . ja v a  2s .c  om*/
 *
 * @return General names
 */
public GeneralNames getGeneralNames() {
    return new GeneralNames(getGeneralNamesTableModel().getData().toArray(new GeneralName[0]));
}

From source file:net.sf.keystore_explorer.gui.dialogs.extensions.DAuthorityKeyIdentifier.java

License:Open Source License

@SuppressWarnings("unchecked")
private void prepopulateWithAuthorityCertDetails(X500Name authorityCertName,
        BigInteger authorityCertSerialNumber) {
    if (authorityCertName != null) {
        try {/*from   ww w .  j  a va  2 s  .co m*/
            GeneralName generalName = new GeneralName(GeneralName.directoryName, authorityCertName);
            GeneralNames generalNames = new GeneralNames(generalName);

            jgnAuthorityCertIssuer.setGeneralNames(generalNames);
        } catch (Exception ex) {
            DError dError = new DError(this, ex);
            dError.setLocationRelativeTo(this);
            dError.setVisible(true);
            return;
        }
    }

    if (authorityCertSerialNumber != null) {
        jtfAuthorityCertSerialNumber.setText("" + authorityCertSerialNumber.toString());
        jtfAuthorityCertSerialNumber.setCaretPosition(0);
    }
}