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:eu.optimis.ics.Credentials.CACredentials.java

License:Open Source License

protected X509CertificateHolder genCACertificate(KeyPair CAKP) {
    BigInteger serial = BigInteger.valueOf(new SecureRandom().nextLong()).abs();

    Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
    Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365));

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(CAKP.getPublic().getEncoded());

    // Same issuer and subject for the self-signed CA certificate
    X500Name issuer = new X500Name(
            "C=UK, ST=Suffolk, L=Ipswich, O=BT, OU=R&T, CN=CloudShadow, Name=Ali, emailAddress=ali.sajjad@bt.com");
    X500Name subject = new X500Name(
            "C=UK, ST=Suffolk, L=Ipswich, O=BT, OU=R&T, CN=CloudShadow, Name=Ali, emailAddress=ali.sajjad@bt.com");

    X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter,
            subject, publicKeyInfo);//from  w  ww .j  a  v  a2  s .  c  o m

    GeneralNames gNames = new GeneralNames(new GeneralName(issuer));
    v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
            new SubjectKeyIdentifier(publicKeyInfo));
    v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifier(publicKeyInfo, gNames, serial));
    v3CertBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));

    ContentSigner sigGen = null;

    try {
        sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(CAKP.getPrivate());
    } catch (OperatorCreationException e) {
        e.printStackTrace();
    }
    return v3CertBuilder.build(sigGen);
}

From source file:fathom.x509.X509Utils.java

License:Apache License

/**
 * Creates a new SSL certificate signed by the CA private key and stored in
 * keyStore.//  ww w. j  a  va  2  s. c o m
 *
 * @param sslMetadata
 * @param caPrivateKey
 * @param caCert
 * @param targetStoreFile
 * @param x509log
 */
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey,
        X509Certificate caCert, File targetStoreFile, X509Log x509log) {
    try {
        KeyPair pair = newKeyPair();

        X500Name webDN = buildDistinguishedName(sslMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN,
                BigInteger.valueOf(System.currentTimeMillis()), sslMetadata.notBefore, sslMetadata.notAfter,
                webDN, pair.getPublic());

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
                extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));

        // support alternateSubjectNames for SSL certificates
        List<GeneralName> altNames = new ArrayList<GeneralName>();
        if (isIpAddress(sslMetadata.commonName)) {
            altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
        }
        if (altNames.size() > 0) {
            GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }

        ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC)
                .build(caPrivateKey);
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
                .getCertificate(certBuilder.build(caSigner));

        cert.checkValidity(new Date());
        cert.verify(caCert.getPublicKey());

        // Save to keystore
        KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password);
        serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(),
                new Certificate[] { cert, caCert });
        saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);

        x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(),
                cert.getSubjectDN().getName()));

        // update serial number in metadata object
        sslMetadata.serialNumber = cert.getSerialNumber().toString();

        return cert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate SSL certificate!", t);
    }
}

From source file:fathom.x509.X509Utils.java

License:Apache License

/**
 * Creates a new client certificate PKCS#12 and PEM store.  Any existing
 * stores are destroyed.//ww  w .  jav  a 2  s .c  o  m
 *
 * @param clientMetadata a container for dynamic parameters needed for generation
 * @param caPrivateKey
 * @param caCert
 * @param targetFolder
 * @return
 */
public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey,
        X509Certificate caCert, File targetFolder) {
    try {
        KeyPair pair = newKeyPair();

        X500Name userDN = buildDistinguishedName(clientMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

        // create a new certificate signed by the Fathom CA certificate
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN,
                BigInteger.valueOf(System.currentTimeMillis()), clientMetadata.notBefore,
                clientMetadata.notAfter, userDN, pair.getPublic());

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
                extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        certBuilder.addExtension(X509Extension.keyUsage, true,
                new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        if (!Strings.isNullOrEmpty(clientMetadata.emailAddress)) {
            GeneralNames subjectAltName = new GeneralNames(
                    new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }

        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC)
                .build(caPrivateKey);

        X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC)
                .getCertificate(certBuilder.build(signer));
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                extUtils.createSubjectKeyIdentifier(pair.getPublic()));

        // confirm the validity of the user certificate
        userCert.checkValidity();
        userCert.verify(caCert.getPublicKey());
        userCert.getIssuerDN().equals(caCert.getSubjectDN());

        // verify user certificate chain
        verifyChain(userCert, caCert);

        targetFolder.mkdirs();

        // save certificate, stamped with unique name
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String id = date;
        File certFile = new File(targetFolder, id + ".cer");
        int count = 0;
        while (certFile.exists()) {
            id = date + "_" + Character.toString((char) (0x61 + count));
            certFile = new File(targetFolder, id + ".cer");
            count++;
        }

        // save user private key, user certificate and CA certificate to a PKCS#12 store
        File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
        if (p12File.exists()) {
            p12File.delete();
        }
        KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
        userStore.setKeyEntry(
                MessageFormat.format("Fathom ({0}) {1} {2}", clientMetadata.serverHostname,
                        clientMetadata.userDisplayname, id),
                pair.getPrivate(), null, new Certificate[] { userCert });
        userStore.setCertificateEntry(
                MessageFormat.format("Fathom ({0}) Certificate Authority", clientMetadata.serverHostname),
                caCert);
        saveKeyStore(p12File, userStore, clientMetadata.password);

        // save user private key, user certificate, and CA certificate to a PEM store
        File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
        if (pemFile.exists()) {
            pemFile.delete();
        }
        PEMWriter pemWriter = new PEMWriter(new FileWriter(pemFile));
        pemWriter.writeObject(pair.getPrivate(), "DES-EDE3-CBC", clientMetadata.password.toCharArray(),
                new SecureRandom());
        pemWriter.writeObject(userCert);
        pemWriter.writeObject(caCert);
        pemWriter.flush();
        pemWriter.close();

        // save certificate after successfully creating the key stores
        saveCertificate(userCert, certFile);

        // update serial number in metadata object
        clientMetadata.serialNumber = userCert.getSerialNumber().toString();

        return userCert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate client certificate!", t);
    }
}

From source file:g4mfs.impl.org.peertrust.security.credentials.CryptTools.java

License:Open Source License

/**
 * Generate a Certificate that holds a Credential as a critical Extension in it.
 * @param pubKey the public key of the subject of the credential. This
 * is needed to create a valid X509Certificate and might be usefull to
 * improve security, when a public key infrastructure is used in this
 * prototype environment.//from w  w  w  .j  a v a 2  s.  co  m
 * @param subject the distinguished name of the subject of this 
 * credential. Important: There exists a certain format for distinguished 
 * names. For example "CN=alice" is a valid DN.
 * @param credential the String Representation of the credential
 * @param issuer the name of the signer of the credential. This should
 * be the person the caPrivKey belongs to.
 * @param caPrivKey the key that is used to sign the credential
 * @return A X.509Certificate 
 */
public static X509Certificate createCert(String subject, String credential, PublicKey pubKey, String issuer,
        PrivateKey caPrivKey) throws Exception {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    // create the certificate - version 3 (only v3 allows usage of extensions)
    v3CertGen.reset();
    // TODO: Eindeutige Serialno
    v3CertGen.setSerialNumber(java.math.BigInteger.valueOf(3));
    v3CertGen.setIssuerDN(new X509Principal(issuer));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)));
    v3CertGen.setSubjectDN(new X509Principal(subject));
    v3CertGen.setPublicKey(pubKey);
    v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    // add the extensions
    // - the credential as an extension
    //   - try to create a "SubjectAlternativeName" Extension in the othername field
    //     - create an OtherName (there is no OtherName class, so I have to improvise)
    int tag = 2; // Tag-Class 'Universal', BIT STRING: 2(works fine), OCTET STRING: 3
    DERObject derO = new DERPrintableString(credential);

    //     - create a GeneralName
    GeneralName gn = new GeneralName(derO, tag);

    //     - create a GeneralNames set of it:
    DERSequence ders = new DERSequence(gn);
    GeneralNames gns = new GeneralNames(ders);

    v3CertGen.addExtension(X509Extensions.SubjectAlternativeName, true, gns);

    // generate the cert
    X509Certificate cert = v3CertGen.generateX509Certificate(caPrivKey);

    // Testing:
    cert.checkValidity(new Date());

    return cert;
}

From source file:hu.akarnokd.utils.crypto.KeystoreManager.java

License:Apache License

/**
 * Generate a X509 certificate for the given keypair.
 * The distinguished names must be in format: CN=cName, OU=orgUnit, O=org, L=city, S=state, C=countryCode
 * use backslash to escape a comma//  w w w  .  j  a va2  s  .c  om
 * @param keypair the keypair
 * @param months the validity length in months
 * @param issuerDN the issuer distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param subjectDN the subject distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param domain domain of the server to store in the subject alternative name extension
 * @param signAlgorithm the signing algorithm to use
 * @return the generated X509 certificate
 */
public X509Certificate createX509Certificate(KeyPair keypair, int months, String issuerDN, String subjectDN,
        String domain, String signAlgorithm) {
    try {
        // calendar for date calculations
        GregorianCalendar cal = new GregorianCalendar();

        // extract keypair components
        PublicKey pubKey = keypair.getPublic();
        PrivateKey privKey = keypair.getPrivate();

        // generate a random serial number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
        byte[] serialNo = new byte[8];
        random.nextBytes(serialNo);
        BigInteger serial = new BigInteger(serialNo).abs();

        // create the certificate generator
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.reset();

        // set certificate attributes
        certGen.setSerialNumber(serial);
        cal.setTimeInMillis(System.currentTimeMillis());
        certGen.setNotBefore(cal.getTime());
        cal.add(GregorianCalendar.MONTH, months);
        certGen.setNotAfter(cal.getTime());
        certGen.setPublicKey(pubKey);
        certGen.setSignatureAlgorithm(signAlgorithm);
        certGen.setIssuerDN(new X509Name(issuerDN));
        certGen.setSubjectDN(new X509Name(subjectDN));

        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));

        // create subject alternative name
        boolean isCritical = subjectDN == null || "".equals(subjectDN.trim());
        DERSequence othernameSeq = new DERSequence(
                new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                        new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
        GeneralName othernameGen = new GeneralName(GeneralName.otherName, othernameSeq);
        GeneralNames subjectAlternatives = new GeneralNames(othernameGen);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, isCritical, subjectAlternatives);

        // finally generate the certificate
        X509Certificate cert = certGen.generateX509Certificate(privKey, BC_PROVIDER.getName(),
                new SecureRandom());
        cert.checkValidity(new Date());
        cert.verify(pubKey);

        return cert;
    } catch (NoSuchAlgorithmException ex) {
        throw new KeystoreFault(ex);
    } catch (CertificateException ex) {
        throw new KeystoreFault(ex);
    } catch (SignatureException ex) {
        throw new KeystoreFault(ex);
    } catch (NoSuchProviderException ex) {
        throw new KeystoreFault(ex);
    } catch (InvalidKeyException ex) {
        throw new KeystoreFault(ex);
    }
}

From source file:io.aos.crypto.spl06.PKCS10ExtensionExample.java

License:Apache License

public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception {
    // create a SubjectAlternativeName extension value
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"));

    // create the extensions object and add it as an attribute
    Vector oids = new Vector();
    Vector values = new Vector();

    oids.add(X509Extensions.SubjectAlternativeName);
    values.add(new X509Extension(false, new DEROctetString(subjectAltNames)));

    X509Extensions extensions = new X509Extensions(oids, values);

    Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            new DERSet(extensions));

    return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"),
            pair.getPublic(), new DERSet(attribute), pair.getPrivate());
}

From source file:io.aos.crypto.spl06.X509V3CreateExample.java

License:Apache License

public static X509Certificate generateV3Certificate(KeyPair pair)
        throws InvalidKeyException, NoSuchProviderException, SignatureException {
    // generate the certificate
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    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")));

    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}

From source file:io.spikex.core.Main.java

License:Apache License

private void createKeyStore(final YamlDocument conf) {

    YamlDocument confKeyStore = conf.getDocument(CONF_KEY_KEYSTORE);
    boolean generate = confKeyStore.getValue(CONF_KEY_GENERATE, DEF_GENERATE_KEYSTORE);

    if (generate) {

        Path keyStorePath = Paths
                .get(confKeyStore.getValue(CONF_KEY_PATH, m_confPath.resolve(DEF_KEYSTORE_PATH).toString()))
                .toAbsolutePath().normalize();

        if (!Files.exists(keyStorePath)) {

            Provider bcProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
            if (bcProvider == null) {
                Security.addProvider(new BouncyCastleProvider());
            }//from w ww .j a va 2 s. c  o m

            String password = confKeyStore.getValue(CONF_KEY_PASSWORD, DEF_KEYSTORE_PASSWORD);
            String hostFqdn = confKeyStore.getValue(CONF_KEY_HOST_FQDN, HostOs.hostName());
            List<String> subjAltNames = confKeyStore.getValue(CONF_KEY_SUBJECT_ALT_NAME, new ArrayList());

            try (FileOutputStream out = new FileOutputStream(keyStorePath.toFile())) {

                m_logger.info("Generating keystore: {}", keyStorePath);

                KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA",
                        BouncyCastleProvider.PROVIDER_NAME);

                SecureRandom rnd = new SecureRandom();
                generator.initialize(2048, rnd);
                KeyPair pair = generator.generateKeyPair();

                // DN
                X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
                nameBuilder.addRDN(BCStyle.C, System.getProperty("user.country.format", "NU"));
                nameBuilder.addRDN(BCStyle.OU, "Self-signed test certificate");
                nameBuilder.addRDN(BCStyle.OU, "For testing purposes only");
                nameBuilder.addRDN(BCStyle.O, "Spike.x");
                nameBuilder.addRDN(BCStyle.CN, hostFqdn);

                long oneDay = 24 * 60 * 60 * 1000;
                Date notBefore = new Date(System.currentTimeMillis() - oneDay); // Yesterday
                Date notAfter = new Date(System.currentTimeMillis() + (oneDay * 3 * 365)); // 3 years

                BigInteger serialNum = BigInteger.valueOf(rnd.nextLong());
                X509v3CertificateBuilder x509v3Builder = new JcaX509v3CertificateBuilder(nameBuilder.build(),
                        serialNum, notBefore, notAfter, nameBuilder.build(), pair.getPublic());

                //
                // Extensions
                //
                x509v3Builder.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                x509v3Builder.addExtension(X509Extensions.KeyUsage, true,
                        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
                x509v3Builder.addExtension(X509Extensions.ExtendedKeyUsage, true,
                        new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

                GeneralName[] dnsNames = new GeneralName[subjAltNames.size()];
                for (int i = 0; i < subjAltNames.size(); i++) {
                    String name = subjAltNames.get(i);
                    m_logger.info("Adding subject alt name: {}", name);
                    dnsNames[i] = new GeneralName(GeneralName.dNSName, name);
                }
                x509v3Builder.addExtension(X509Extensions.SubjectAlternativeName, false,
                        new GeneralNames(dnsNames));

                ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(pair.getPrivate());

                X509Certificate cert = new JcaX509CertificateConverter()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .getCertificate(x509v3Builder.build(signer));

                // Validate
                cert.checkValidity(new Date());
                cert.verify(cert.getPublicKey());

                // Save in keystore
                KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(null);
                ks.setKeyEntry(hostFqdn, pair.getPrivate(), password.toCharArray(), new Certificate[] { cert });

                m_logger.info("Created self-signed certificate: {}", hostFqdn);
                ks.store(out, password.toCharArray());

            } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
                    | NoSuchProviderException | OperatorCreationException | InvalidKeyException
                    | SignatureException e) {
                throw new RuntimeException("Failed to create keystore: " + keyStorePath, e);
            }
        }
    }
}

From source file:io.vertx.config.vault.utils.Certificates.java

License:Apache License

/**
 * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder
 *
 * @param keyPair The RSA keypair with which to generate the certificate
 * @param issuer  The issuer (and subject) to use for the certificate
 * @return An X509 certificate/*w  ww.j  ava  2 s  .c  om*/
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
private static X509Certificate generateCert(final KeyPair keyPair, final String issuer)
        throws IOException, OperatorCreationException, CertificateException, NoSuchProviderException,
        NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    final String subject = issuer;
    final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(new X500Name(issuer),
            BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(subject),
            SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
    certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false,
            subjectAltNames);

    final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
            .find("SHA1WithRSAEncryption");
    final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
    final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    final ContentSigner signer = signerBuilder.build(keyp);
    final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);

    final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder);
    certificate.checkValidity(new Date());
    certificate.verify(keyPair.getPublic());
    return certificate;
}

From source file:it.trento.comune.j4sign.cms.ExternalSignatureSignerInfoGenerator.java

License:Open Source License

/**
 * Builds the SignerCertificateV2 attribute according to RFC2634(Enhanced
 * Security Services (ESS)) + RFC5035(ESS Update: AddingCertID Algorithm
 * Agility).<br>/*from  ww w.  j  av a 2  s.com*/
 * This signed attribute is mandatory for CAdES-BES (ETSI TS 101 733)
 * compliancy.
 * 
 * @param sigProvider
 *            the provider to use for digest calculation.
 * @return the SignerCertificateV2 attribute calculated from to the current
 *         certificate and digest algorithm.
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CertificateEncodingException
 * @throws IOException
 */
private Attribute buildSigningCertificateV2Attribute(String sigProvider)
        throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, IOException {

    X509Certificate cert = this.getCertificate();

    MessageDigest dig = MessageDigest.getInstance(this.getDigestAlgOID(), sigProvider);
    byte[] certHash = dig.digest(cert.getEncoded());

    // ricavo issuerandserialnumber (ID) del certificato
    // byte[] encodedCert = this.cert.getEncoded();
    // ASN1InputStream ais = new ASN1InputStream(encodedCert);
    // DERObject derObj = ais.readObject();
    // ASN1Sequence asn1Seq = (ASN1Sequence) derObj;
    // ais.close();
    // X509CertificateStructure x509CStructure = new
    // X509CertificateStructure(
    // asn1Seq);
    // X509Name x509Name = x509CStructure.getIssuer();
    // DERInteger serialNum = x509CStructure.getSerialNumber();
    // GeneralName generalName = new GeneralName(x509Name);
    // GeneralNames generalNames = new GeneralNames(generalName);

    // ROB: more directly
    JcaX509CertificateHolder holder = new JcaX509CertificateHolder(cert);
    X500Name x500name = holder.getIssuer();

    GeneralName generalName = new GeneralName(x500name);
    GeneralNames generalNames = new GeneralNames(generalName);
    DERInteger serialNum = new DERInteger(holder.getSerialNumber());

    IssuerSerial issuerserial = new IssuerSerial(generalNames, serialNum);
    // ---

    ESSCertIDv2 essCert = new ESSCertIDv2(new AlgorithmIdentifier(getDigestAlgOID()), certHash, issuerserial);
    // ESSCertIDv2 essCert = new ESSCertIDv2(new AlgorithmIdentifier(
    // getDigestAlgOID()), certHash);

    SigningCertificateV2 scv2 = new SigningCertificateV2(new ESSCertIDv2[] { essCert });

    return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(scv2));
}