Search in sources :

Example 6 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder in project dcos-commons by mesosphere.

the class CertificateAuthorityClientTest method createCertificate.

private X509Certificate createCertificate() throws Exception {
    KeyPair keyPair = KEY_PAIR_GENERATOR.generateKeyPair();
    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X500Name issuer = new X500NameBuilder().addRDN(BCStyle.CN, "issuer").build();
    X500Name subject = new X500NameBuilder().addRDN(BCStyle.CN, "subject").build();
    ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate());
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509CertificateHolder certHolder = new X509v3CertificateBuilder(issuer, new BigInteger("1000"), Date.from(Instant.now()), Date.from(Instant.now().plusSeconds(100000)), subject, subjectPublicKeyInfo).build(signer);
    return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certHolder.getEncoded()));
}
Also used : KeyPair(java.security.KeyPair) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 7 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder in project drill by apache.

the class SslContextFactoryConfigurator method useAutoGeneratedSelfSignedCertificate.

private void useAutoGeneratedSelfSignedCertificate(SslContextFactory sslContextFactory) throws Exception {
    logger.info("Using generated self-signed SSL settings for web server");
    final SecureRandom random = new SecureRandom();
    // Generate a private-public key pair
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, random);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();
    // Create builder for certificate attributes
    final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.OU, "Apache Drill (auth-generated)").addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, drillbitEndpointAddress);
    final DateTime now = DateTime.now();
    final Date notBefore = now.minusMinutes(1).toDate();
    final Date notAfter = now.plusYears(5).toDate();
    final BigInteger serialNumber = new BigInteger(128, random);
    // Create a certificate valid for 5years from now.
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(// attributes
    nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());
    // Sign the certificate using the private key
    final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
    final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
    // Check the validity
    certificate.checkValidity(now.toDate());
    // Make sure the certificate is self-signed.
    certificate.verify(certificate.getPublicKey());
    // Generate a random password for keystore protection
    final String keyStorePasswd = RandomStringUtils.random(20);
    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate });
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePasswd);
}
Also used : KeyPair(java.security.KeyPair) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) KeyStore(java.security.KeyStore) DateTime(org.joda.time.DateTime) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger)

Example 8 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder in project kdeconnect-android by KDE.

the class SslHelper method initialiseCertificate.

public static void initialiseCertificate(Context context) {
    PrivateKey privateKey;
    PublicKey publicKey;
    try {
        privateKey = RsaHelper.getPrivateKey(context);
        publicKey = RsaHelper.getPublicKey(context);
    } catch (Exception e) {
        Log.e("SslHelper", "Error getting keys, can't create certificate");
        return;
    }
    String deviceId = DeviceHelper.getDeviceId(context);
    boolean needsToGenerateCertificate = false;
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    if (settings.contains("certificate")) {
        try {
            SharedPreferences globalSettings = PreferenceManager.getDefaultSharedPreferences(context);
            byte[] certificateBytes = Base64.decode(globalSettings.getString("certificate", ""), 0);
            X509CertificateHolder certificateHolder = new X509CertificateHolder(certificateBytes);
            X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateHolder);
            String certDeviceId = getCommonNameFromCertificate(cert);
            if (!certDeviceId.equals(deviceId)) {
                Log.e("KDE/SslHelper", "The certificate stored is from a different device id! (found: " + certDeviceId + " expected:" + deviceId + ")");
                needsToGenerateCertificate = true;
            } else {
                certificate = cert;
            }
        } catch (Exception e) {
            Log.e("KDE/SslHelper", "Exception reading own certificate", e);
            needsToGenerateCertificate = true;
        }
    } else {
        needsToGenerateCertificate = true;
    }
    if (needsToGenerateCertificate) {
        Log.i("KDE/SslHelper", "Generating a certificate");
        try {
            // Fix for https://issuetracker.google.com/issues/37095309
            Locale initialLocale = Locale.getDefault();
            setLocale(Locale.ENGLISH, context);
            X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
            nameBuilder.addRDN(BCStyle.CN, deviceId);
            nameBuilder.addRDN(BCStyle.OU, "KDE Connect");
            nameBuilder.addRDN(BCStyle.O, "KDE");
            final LocalDate localDate = LocalDate.now().minusYears(1);
            final Instant notBefore = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
            final Instant notAfter = localDate.plusYears(10).atStartOfDay(ZoneId.systemDefault()).toInstant();
            X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), BigInteger.ONE, Date.from(notBefore), Date.from(notAfter), nameBuilder.build(), publicKey);
            ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(privateKey);
            certificate = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateBuilder.build(contentSigner));
            SharedPreferences.Editor edit = settings.edit();
            edit.putString("certificate", Base64.encodeToString(certificate.getEncoded(), 0));
            edit.apply();
            setLocale(initialLocale, context);
        } catch (Exception e) {
            Log.e("KDE/initialiseCert", "Exception", e);
        }
    }
}
Also used : Locale(java.util.Locale) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.spongycastle.asn1.x500.X500NameBuilder) SharedPreferences(android.content.SharedPreferences) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.spongycastle.operator.jcajce.JcaContentSignerBuilder) Instant(java.time.Instant) ContentSigner(org.spongycastle.operator.ContentSigner) LocalDate(java.time.LocalDate) SocketException(java.net.SocketException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) JcaX509CertificateConverter(org.spongycastle.cert.jcajce.JcaX509CertificateConverter) X509v3CertificateBuilder(org.spongycastle.cert.X509v3CertificateBuilder) JcaX509v3CertificateBuilder(org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.spongycastle.cert.X509CertificateHolder) JcaX509v3CertificateBuilder(org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder)

Example 9 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, String issuerCommonName, String subjectCommonName, String domain, String signAlgoritm, Set<String> sanDnsNames) throws GeneralSecurityException, IOException {
    // subjectDN
    X500NameBuilder subjectBuilder = new X500NameBuilder();
    subjectBuilder.addRDN(BCStyle.CN, subjectCommonName);
    // issuerDN
    X500NameBuilder issuerBuilder = new X500NameBuilder();
    issuerBuilder.addRDN(BCStyle.CN, issuerCommonName);
    return createX509V3Certificate(kp, days, issuerBuilder, subjectBuilder, domain, signAlgoritm, sanDnsNames);
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder)

Example 10 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder in project ddf by codice.

the class PkiTools method convertDistinguishedName.

public static X500Name convertDistinguishedName(String... tuples) {
    Validate.isTrue(tuples != null && tuples.length > 0, "Distinguished name must consist of at least one component");
    Validate.isTrue(Arrays.stream(tuples).allMatch(t -> TUPLE_PATTERN.matcher(t).matches()), "Distinguished name components must be in the format symbol=value");
    AttributeNameChecker style = new AttributeNameChecker();
    Validate.isTrue(Arrays.stream(tuples).map(t -> t.split("[=]")[0]).map(String::trim).allMatch(style::isValidName));
    X500NameBuilder nameBuilder = new X500NameBuilder(RFC4519Style.INSTANCE);
    Arrays.stream(tuples).map(t -> t.split("[=]")).forEach(t -> nameBuilder.addRDN(style.lookupByName(t[0].trim()), t[1].trim()));
    return nameBuilder.build();
}
Also used : X509Certificate(java.security.cert.X509Certificate) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) CertificateFactory(org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory) LoggerFactory(org.slf4j.LoggerFactory) InetAddress(java.net.InetAddress) X500Name(org.bouncycastle.asn1.x500.X500Name) GeneralSecurityException(java.security.GeneralSecurityException) ByteArrayInputStream(java.io.ByteArrayInputStream) RFC4519Style(org.bouncycastle.asn1.x500.style.RFC4519Style) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) KeyPairGenerator(java.security.KeyPairGenerator) Logger(org.slf4j.Logger) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) KeyFactory(java.security.KeyFactory) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Key(java.security.Key) Base64(java.util.Base64) GeneralName(org.bouncycastle.asn1.x509.GeneralName) PrivateKey(java.security.PrivateKey) Pattern(java.util.regex.Pattern) Validate(org.apache.commons.lang.Validate) CertificateEncodingException(java.security.cert.CertificateEncodingException) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder)

Aggregations

X500NameBuilder (org.bouncycastle.asn1.x500.X500NameBuilder)28 X509Certificate (java.security.cert.X509Certificate)18 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)18 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)18 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)18 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)17 ContentSigner (org.bouncycastle.operator.ContentSigner)17 BigInteger (java.math.BigInteger)16 KeyPair (java.security.KeyPair)15 Date (java.util.Date)15 X500Name (org.bouncycastle.asn1.x500.X500Name)13 KeyStore (java.security.KeyStore)11 SecureRandom (java.security.SecureRandom)10 KeyPairGenerator (java.security.KeyPairGenerator)9 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)8 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)7 PrivateKey (java.security.PrivateKey)6 PublicKey (java.security.PublicKey)6 CertificateException (java.security.cert.CertificateException)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6