Example usage for org.bouncycastle.cert X509v1CertificateBuilder X509v1CertificateBuilder

List of usage examples for org.bouncycastle.cert X509v1CertificateBuilder X509v1CertificateBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.cert X509v1CertificateBuilder X509v1CertificateBuilder.

Prototype

public X509v1CertificateBuilder(X500Name issuer, BigInteger serial, Time notBefore, Time notAfter,
        X500Name subject, SubjectPublicKeyInfo publicKeyInfo) 

Source Link

Document

Create a builder for a version 1 certificate.

Usage

From source file:beta01.SimpleRootCA.java

/**
 * Build a sample V1 certificate to use as a CA root certificate
 * @param keyPair/*  w ww. j a  v a  2  s. co m*/
 */
public static X509CertificateHolder buildRootCert(org.bouncycastle.crypto.AsymmetricCipherKeyPair keyPair)
        throws Exception {
    X509v1CertificateBuilder certBldr = new X509v1CertificateBuilder(new X500Name("CN=Test Root Certificate"),
            BigInteger.valueOf(1), new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), new X500Name("CN=Test Root Certificate"),
            SubjectPublicKeyInfoFactory
                    .createSubjectPublicKeyInfo((AsymmetricKeyParameter) keyPair.getPublic()));

    AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg)
            .build((AsymmetricKeyParameter) keyPair.getPrivate());

    return certBldr.build(signer);
}

From source file:com.android.builder.internal.packaging.sign.SignatureTestUtils.java

License:Apache License

/**
 * Generates a private key / certificate.
 *
 * @param sign the asymmetric cypher, <em>e.g.</em>, {@code RSA}
 * @param full the full signature algorithm name, <em>e.g.</em>, {@code SHA1withRSA}
 * @return the pair with the private key and certificate
 * @throws Exception failed to generate the signature data
 */// w  w w. j a v  a2 s. c o m
@NonNull
public static Pair<PrivateKey, X509Certificate> generateSignature(@NonNull String sign, @NonNull String full)
        throws Exception {
    // http://stackoverflow.com/questions/28538785/
    // easy-way-to-generate-a-self-signed-certificate-for-java-security-keystore-using

    KeyPairGenerator generator = null;
    try {
        generator = KeyPairGenerator.getInstance(sign);
    } catch (NoSuchAlgorithmException e) {
        Assume.assumeNoException("Algorithm " + sign + " not supported.", e);
    }

    assertNotNull(generator);
    KeyPair keyPair = generator.generateKeyPair();

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

    X500Name issuer = new X500Name(new X500Principal("cn=Myself").getName());

    SubjectPublicKeyInfo publicKeyInfo;

    if (keyPair.getPublic() instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        publicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(
                new RSAKeyParameters(false, rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent()));
    } else if (keyPair.getPublic() instanceof ECPublicKey) {
        publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    } else {
        fail();
        publicKeyInfo = null;
    }

    X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter,
            issuer, publicKeyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(full).setProvider(new BouncyCastleProvider())
            .build(keyPair.getPrivate());
    X509CertificateHolder holder = builder.build(signer);

    JcaX509CertificateConverter converter = new JcaX509CertificateConverter()
            .setProvider(new BouncyCastleProvider());

    return Pair.of(keyPair.getPrivate(), converter.getCertificate(holder));
}

From source file:com.android.ide.common.signing.KeystoreHelper.java

License:Apache License

/**
 * Generates a key and self-signed certificate pair.
 * @param asymmetric the asymmetric encryption algorithm (<em>e.g.,</em> {@code RSA})
 * @param sign the signature algorithm (<em>e.g.,</em> {@code SHA1withRSA})
 * @param validityYears number of years the certificate should be valid, must be greater than
 * zero// ww  w .j  a  v a 2  s.c  o m
 * @param dn the distinguished name of the issuer and owner of the certificate
 * @return a pair with the private key and the corresponding certificate
 * @throws KeytoolException failed to generate the pair
 */
private static Pair<PrivateKey, X509Certificate> generateKeyAndCertificate(@NonNull String asymmetric,
        @NonNull String sign, int validityYears, @NonNull String dn) throws KeytoolException {
    Preconditions.checkArgument(validityYears > 0, "validityYears <= 0");

    KeyPair keyPair;
    try {
        keyPair = KeyPairGenerator.getInstance(asymmetric).generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new KeytoolException(
                "Failed to generate key and certificate pair for " + "algorithm '" + asymmetric + "'.", e);
    }

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

    X500Name issuer = new X500Name(new X500Principal(dn).getName());

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter,
            issuer, publicKeyInfo);

    ContentSigner signer;
    try {
        signer = new JcaContentSignerBuilder(sign).setProvider(new BouncyCastleProvider())
                .build(keyPair.getPrivate());
    } catch (OperatorCreationException e) {
        throw new KeytoolException("Failed to build content signer with signature algorithm '" + sign + "'.",
                e);
    }

    X509CertificateHolder holder = builder.build(signer);

    JcaX509CertificateConverter converter = new JcaX509CertificateConverter()
            .setProvider(new BouncyCastleProvider());

    X509Certificate certificate;
    try {
        certificate = converter.getCertificate(holder);
    } catch (CertificateException e) {
        throw new KeytoolException("Failed to obtain the self-signed certificate.", e);
    }

    return Pair.of(keyPair.getPrivate(), certificate);
}

From source file:com.formkiq.core.service.crypto.KeyGenerator.java

License:Apache License

/**
 * Build {@link X509v1CertificateBuilder}.
 * @param publicKey {@link PublicKey}/* w w w .ja  va  2  s .  com*/
 * @param issuer {@link X500Name}
 * @return {@link X509v1CertificateBuilder}.
 */
private X509v1CertificateBuilder getCertificateBuilder(final PublicKey publicKey, final X500Name issuer) {
    X500Name subject = issuer;

    try {
        Date notafter = new SimpleDateFormat("yyyy-MM-dd").parse("3000-01-01");

        Date notbefore = new SimpleDateFormat("yyyy-MM-dd").parse("2000-01-01");

        return new X509v1CertificateBuilder(issuer, SERIAL, notbefore, notafter, subject,
                getPublicKeyInfo(publicKey));
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.ambry.commons.TestSSLUtils.java

License:Open Source License

/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn the X.509 Distinguished Name, eg "CN(commonName)=Test, O(organizationName)=Org"
 * @param pair the KeyPair//from w  ww .j  a  va  2s. c o m
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws java.security.cert.CertificateException thrown if a security error or an IO error ocurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
        throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory
                .createKey(pair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());

        X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name,
                subPubKeyInfo);
        X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}

From source file:com.linkedin.kafka.clients.utils.tests.TestSslUtils.java

/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn        the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair      the KeyPair/* w w  w  . j av a2s .c o  m*/
 * @param days      how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws CertificateException thrown if a security error or an IO error occurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
        throws CertificateException {

    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory
                .createKey(pair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());

        X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name,
                subPubKeyInfo);
        X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}

From source file:com.msopentech.thali.utilities.universal.ThaliCryptoUtilities.java

License:Open Source License

/**
 * Creates a PKCS12 keystore and puts into it the submitted public/private key pair under the submitted
 * Key Alias using the submitted passphrase to 'secure' the file.
 *
 * Right now we only generate large RSA keys because I'm paranoid that the curves used in
 * Elliptic Curve crypto may have been designed by folks for whom security was not the paramount
 * concern. Once this issue is put to rest I would expect to switch to Elliptic Curve because
 * it is considered (with appropriate curves) to be more secure and is certainly faster.
 * @param keyPair/*from w  w w .  j a v a2s . c  om*/
 * @param keyAlias
 * @param passphrase
 * @return
 */
public static KeyStore CreatePKCS12KeyStoreWithPublicPrivateKeyPair(KeyPair keyPair, String keyAlias,
        char[] passphrase) {
    try {
        byte[] publicKeyAsByteArray = keyPair.getPublic().getEncoded();

        // Generate a cert for the public key
        Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
        Date endDate = new Date(
                System.currentTimeMillis() + (ExpirationPeriodForCertsInDays * 24L * 60L * 60L * 1000L));

        // Thali security is based on keys NOT on cert values. That is we are not trying to bind a name (like a DNS
        // address) to a key. The key IS the identity. But the X509 standard requires names so we stick something
        // in.
        X500Name x500Name = new X500Name(X500Name);

        SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
                ASN1Sequence.getInstance(publicKeyAsByteArray));

        // Note that by not specify .setProvider("BC") we are using the default provider, this is because bouncy castle as
        // previously mentioned is installed on Android but is a challenge for the applet so I'll just use the default for now.
        ContentSigner contentSigner = new JcaContentSignerBuilder(SignerAlgorithm).build(keyPair.getPrivate());

        X509v1CertificateBuilder x509v1CertificateBuilder = new X509v1CertificateBuilder(x500Name,
                BigInteger.ONE, startDate, endDate, x500Name, subjectPublicKeyInfo);
        X509CertificateHolder x509CertificateHolder = x509v1CertificateBuilder.build(contentSigner);
        JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        X509Certificate x509Certificate = jcaX509CertificateConverter.getCertificate(x509CertificateHolder);

        // Store the private key and the cert in the keystore
        KeyStore.PrivateKeyEntry privateKeyEntry = new KeyStore.PrivateKeyEntry(keyPair.getPrivate(),
                new Certificate[] { x509Certificate });

        KeyStore keyStore = KeyStore.getInstance(PrivateKeyHolderFormat);
        // Keystore has to be initialized before being used
        keyStore.load(null, null);

        keyStore.setEntry(keyAlias, privateKeyEntry, new KeyStore.PasswordProtection(passphrase));

        return keyStore;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:eu.betaas.taas.securitymanager.common.certificate.utils.GWCertificateUtilsBc.java

License:Apache License

/**
 * //from  w  w w . j  a  v  a  2 s  . c  o  m
 * @param keyPair
 * @return
 * @throws Exception
 */
public static X509CertificateHolder buildRootCert(X500Name subject, AsymmetricCipherKeyPair keyPair)
        throws Exception {
    if (subject == null)
        subject = new X500Name("CN = BETaaS Instance Root Certificate");

    X509v1CertificateBuilder certBldr = new X509v1CertificateBuilder(subject, BigInteger.valueOf(1),
            new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
            subject, SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(keyPair.getPublic()));

    AlgorithmIdentifier sigAlg = algFinder.find(ALG_NAME);
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    ContentSigner signer = new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(keyPair.getPrivate());

    return certBldr.build(signer);
}

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

License:Open Source License

protected X509v1CertificateBuilder createX509v1CertificateBuilder(X509Certificate issuerCertificate)
        throws IOException {
    X500Principal issuerPrincipal = getIssuer();

    if (issuerCertificate != null) {
        issuerPrincipal = issuerCertificate.getSubjectX500Principal();
    }/*from  w w  w  .j  a  v a2  s .  c om*/

    X509v1CertificateBuilder builder = new X509v1CertificateBuilder(
            X500PrincipalUtils.toX500Name(issuerPrincipal), serialNumber, notBefore, notAfter,
            X500PrincipalUtils.toX500Name(subject), SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()));

    /*
     *  X509 V1 certificates do not support extensions
     */
    return builder;
}

From source file:org.keycloak.common.util.CertificateUtils.java

License:Apache License

public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject,
        BigInteger serialNumber) {
    try {/*  w  w w . j ava2s  . com*/
        X500Name subjectDN = new X500Name("CN=" + subject);
        Date validityStartDate = new Date(System.currentTimeMillis() - 100000);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 10);
        Date validityEndDate = new Date(calendar.getTime().getTime());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo
                .getInstance(caKeyPair.getPublic().getEncoded());

        X509v1CertificateBuilder builder = new X509v1CertificateBuilder(subjectDN, serialNumber,
                validityStartDate, validityEndDate, subjectDN, subPubKeyInfo);
        X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate()));

        return new JcaX509CertificateConverter().getCertificate(holder);
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v1Certificate.", e);
    }
}