Search in sources :

Example 1 with X500NameBuilder

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

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerBuilder     IssuerDN builder
     * @param subjectBuilder    SubjectDN builder
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new //
    JcaX509v3CertificateBuilder(//
    issuerDN, //
    serial, //
    new Date(), //
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
    subjectDN, //
    pubKey);
    // add subjectAlternativeName extension
    boolean critical = subjectDN.getRDNs().length == 0;
    ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertException(org.bouncycastle.cert.CertException) Date(java.util.Date) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 2 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project syncany by syncany.

the class CipherUtil method generateSelfSignedCertificate.

/**
	 * Generates a self-signed certificate, given a public/private key pair.
	 *
	 * @see <a href="https://code.google.com/p/gitblit/source/browse/src/com/gitblit/MakeCertificate.java?r=88598bb2f779b73479512d818c675dea8fa72138">Original source of this method</a>
	 */
public static X509Certificate generateSelfSignedCertificate(String commonName, KeyPair keyPair) throws OperatorCreationException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    // Certificate CN, O and OU
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.CN, commonName);
    builder.addRDN(BCStyle.O, CipherParams.CERTIFICATE_ORGANIZATION);
    builder.addRDN(BCStyle.OU, CipherParams.CERTIFICATE_ORGUNIT);
    // Dates and serial
    Date notBefore = new Date(System.currentTimeMillis() - 1 * 24 * 60 * 60 * 1000L);
    Date notAfter = new Date(System.currentTimeMillis() + 5 * 365 * 24 * 60 * 60 * 1000L);
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    // Issuer and subject (identical, because self-signed)
    X500Name issuer = builder.build();
    X500Name subject = issuer;
    X509v3CertificateBuilder certificateGenerator = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, keyPair.getPublic());
    ContentSigner signatureGenerator = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(CipherParams.CRYPTO_PROVIDER).build(keyPair.getPrivate());
    X509Certificate certificate = new JcaX509CertificateConverter().setProvider(CipherParams.CRYPTO_PROVIDER).getCertificate(certificateGenerator.build(signatureGenerator));
    certificate.checkValidity(new Date());
    certificate.verify(certificate.getPublicKey());
    return certificate;
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 3 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project XobotOS by xamarin.

the class IETFUtils method rDNsFromString.

public static RDN[] rDNsFromString(String name, X500NameStyle x500Style) {
    X500NameTokenizer nTok = new X500NameTokenizer(name);
    X500NameBuilder builder = new X500NameBuilder(x500Style);
    while (nTok.hasMoreTokens()) {
        String token = nTok.nextToken();
        int index = token.indexOf('=');
        if (index == -1) {
            throw new IllegalArgumentException("badly formated directory string");
        }
        String attr = token.substring(0, index);
        String value = token.substring(index + 1);
        ASN1ObjectIdentifier oid = x500Style.attrNameToOID(attr);
        if (value.indexOf('+') > 0) {
            X500NameTokenizer vTok = new X500NameTokenizer(value, '+');
            String v = vTok.nextToken();
            Vector oids = new Vector();
            Vector values = new Vector();
            oids.addElement(oid);
            values.addElement(v);
            while (vTok.hasMoreTokens()) {
                String sv = vTok.nextToken();
                int ndx = sv.indexOf('=');
                String nm = sv.substring(0, ndx);
                String vl = sv.substring(ndx + 1);
                oids.addElement(x500Style.attrNameToOID(nm));
                values.addElement(vl);
            }
            builder.addMultiValuedRDN(toOIDArray(oids), toValueArray(values));
        } else {
            builder.addRDN(oid, value);
        }
    }
    return builder.build().getRDNs();
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) Vector(java.util.Vector) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 4 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project zaproxy by zaproxy.

the class SslCertificateServiceImpl method createCertForHost.

@Override
public KeyStore createCertForHost(String hostname) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {
    if (hostname == null) {
        throw new IllegalArgumentException("Error, 'hostname' is not allowed to be null!");
    }
    if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
        throw new MissingRootCertificateException(this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
    }
    final KeyPair mykp = this.createKeyPair();
    final PrivateKey privKey = mykp.getPrivate();
    final PublicKey pubKey = mykp.getPublic();
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, hostname);
    namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
    namebld.addRDN(BCStyle.O, "OWASP");
    namebld.addRDN(BCStyle.C, "xx");
    namebld.addRDN(BCStyle.EmailAddress, "owasp-zed-attack-proxy@lists.owasp.org");
    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + 100 * (1000L * 60 * 60 * 24 * 30)), namebld.build(), pubKey);
    certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
    certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
    certGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.dNSName, hostname)));
    ContentSigner sigGen;
    try {
        sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
    } catch (OperatorCreationException e) {
        throw new CertificateException(e);
    }
    final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(caPubKey);
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    final Certificate[] chain = new Certificate[2];
    chain[1] = this.caCert;
    chain[0] = cert;
    ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
    return ks;
}
Also used : KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateException(java.security.cert.CertificateException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 5 with X500NameBuilder

use of org.spongycastle.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;
    }
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    if (!settings.contains("certificate")) {
        try {
            X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
            nameBuilder.addRDN(BCStyle.CN, DeviceHelper.getDeviceId(context));
            nameBuilder.addRDN(BCStyle.OU, "KDE Connect");
            nameBuilder.addRDN(BCStyle.O, "KDE");
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.YEAR, -1);
            Date notBefore = calendar.getTime();
            calendar.add(Calendar.YEAR, 10);
            Date notAfter = calendar.getTime();
            X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), BigInteger.ONE, notBefore, 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();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("KDE/initialiseCert", "Exception");
            return;
        }
    } else {
        try {
            SharedPreferences globalSettings = PreferenceManager.getDefaultSharedPreferences(context);
            byte[] certificateBytes = Base64.decode(globalSettings.getString("certificate", ""), 0);
            X509CertificateHolder certificateHolder = new X509CertificateHolder(certificateBytes);
            certificate = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateHolder);
        } catch (Exception e) {
            Log.e("KDE/SslHelper", "Exception reading own certificate");
            e.printStackTrace();
        }
    }
}
Also used : PrivateKey(java.security.PrivateKey) X500NameBuilder(org.spongycastle.asn1.x500.X500NameBuilder) SharedPreferences(android.content.SharedPreferences) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.spongycastle.operator.jcajce.JcaContentSignerBuilder) Calendar(java.util.Calendar) ContentSigner(org.spongycastle.operator.ContentSigner) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Date(java.util.Date) JcaX509v3CertificateBuilder(org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.spongycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.spongycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.spongycastle.cert.X509CertificateHolder)

Aggregations

X500NameBuilder (org.bouncycastle.asn1.x500.X500NameBuilder)12 Date (java.util.Date)9 X509Certificate (java.security.cert.X509Certificate)8 KeyPair (java.security.KeyPair)6 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)6 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)6 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)6 ContentSigner (org.bouncycastle.operator.ContentSigner)6 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)6 BigInteger (java.math.BigInteger)5 KeyPairGenerator (java.security.KeyPairGenerator)5 PrivateKey (java.security.PrivateKey)5 X500Name (org.bouncycastle.asn1.x500.X500Name)5 IOException (java.io.IOException)4 PublicKey (java.security.PublicKey)4 SecureRandom (java.security.SecureRandom)4 CertificateException (java.security.cert.CertificateException)4 GeneralSecurityException (java.security.GeneralSecurityException)3 KeyStore (java.security.KeyStore)3 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)3