Search in sources :

Example 1 with JcaX509CertificateConverter

use of org.spongycastle.cert.jcajce.JcaX509CertificateConverter in project fdroidclient by f-droid.

the class LocalRepoKeyStore method generateSelfSignedCertChain.

private Certificate generateSelfSignedCertChain(KeyPair kp, X500Name subject, String hostname) throws CertificateException, OperatorCreationException, IOException {
    SecureRandom rand = new SecureRandom();
    PrivateKey privKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();
    ContentSigner sigGen = new JcaContentSignerBuilder(DEFAULT_SIG_ALG).build(privKey);
    SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(pubKey.getEncoded()));
    // now
    Date now = new Date();
    /* force it to use a English/Gregorian dates for the cert, hardly anyone
           ever looks at the cert metadata anyway, and its very likely that they
           understand English/Gregorian dates */
    Calendar c = new GregorianCalendar(Locale.ENGLISH);
    c.setTime(now);
    c.add(Calendar.YEAR, 1);
    Time startTime = new Time(now, Locale.ENGLISH);
    Time endTime = new Time(c.getTime(), Locale.ENGLISH);
    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(subject, BigInteger.valueOf(rand.nextLong()), startTime, endTime, subject, subPubKeyInfo);
    if (hostname != null) {
        GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.iPAddress, hostname));
        v3CertGen.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
    }
    X509CertificateHolder certHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.spongycastle.operator.jcajce.JcaContentSignerBuilder) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) ContentSigner(org.spongycastle.operator.ContentSigner) GregorianCalendar(java.util.GregorianCalendar) SecureRandom(java.security.SecureRandom) Time(org.spongycastle.asn1.x509.Time) SubjectPublicKeyInfo(org.spongycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) GeneralNames(org.spongycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.spongycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.spongycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.spongycastle.cert.X509CertificateHolder) GeneralName(org.spongycastle.asn1.x509.GeneralName)

Example 2 with JcaX509CertificateConverter

use of org.spongycastle.cert.jcajce.JcaX509CertificateConverter 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 3 with JcaX509CertificateConverter

use of org.spongycastle.cert.jcajce.JcaX509CertificateConverter in project kdeconnect-android by KDE.

the class SslHelper method getSslContext.

private static SSLContext getSslContext(Context context, String deviceId, boolean isDeviceTrusted) {
    // TODO: Cache
    try {
        // Get device private key
        PrivateKey privateKey = RsaHelper.getPrivateKey(context);
        // Get remote device certificate if trusted
        X509Certificate remoteDeviceCertificate = null;
        if (isDeviceTrusted) {
            SharedPreferences devicePreferences = context.getSharedPreferences(deviceId, Context.MODE_PRIVATE);
            byte[] certificateBytes = Base64.decode(devicePreferences.getString("certificate", ""), 0);
            X509CertificateHolder certificateHolder = new X509CertificateHolder(certificateBytes);
            remoteDeviceCertificate = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateHolder);
        }
        // Setup keystore
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("key", privateKey, "".toCharArray(), new Certificate[] { certificate });
        // Set certificate if device trusted
        if (remoteDeviceCertificate != null) {
            keyStore.setCertificateEntry(deviceId, remoteDeviceCertificate);
        }
        // Setup key manager factory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "".toCharArray());
        // Setup default trust manager
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        // Setup custom trust manager if device not trusted
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Newer TLS versions are only supported on API 16+
        SSLContext tlsContext = SSLContext.getInstance("TLSv1");
        if (isDeviceTrusted) {
            tlsContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), RandomHelper.secureRandom);
        } else {
            tlsContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, RandomHelper.secureRandom);
        }
        return tlsContext;
    } catch (Exception e) {
        Log.e("KDE/SslHelper", "Error creating tls context", e);
    }
    return null;
}
Also used : PrivateKey(java.security.PrivateKey) SharedPreferences(android.content.SharedPreferences) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) SocketException(java.net.SocketException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) JcaX509CertificateConverter(org.spongycastle.cert.jcajce.JcaX509CertificateConverter) X509TrustManager(javax.net.ssl.X509TrustManager) X509CertificateHolder(org.spongycastle.cert.X509CertificateHolder) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Aggregations

PrivateKey (java.security.PrivateKey)3 X509CertificateHolder (org.spongycastle.cert.X509CertificateHolder)3 JcaX509CertificateConverter (org.spongycastle.cert.jcajce.JcaX509CertificateConverter)3 SharedPreferences (android.content.SharedPreferences)2 IOException (java.io.IOException)2 SocketException (java.net.SocketException)2 PublicKey (java.security.PublicKey)2 CertificateException (java.security.cert.CertificateException)2 X509Certificate (java.security.cert.X509Certificate)2 X509v3CertificateBuilder (org.spongycastle.cert.X509v3CertificateBuilder)2 ContentSigner (org.spongycastle.operator.ContentSigner)2 JcaContentSignerBuilder (org.spongycastle.operator.jcajce.JcaContentSignerBuilder)2 KeyStore (java.security.KeyStore)1 SecureRandom (java.security.SecureRandom)1 Instant (java.time.Instant)1 LocalDate (java.time.LocalDate)1 Calendar (java.util.Calendar)1 Date (java.util.Date)1 GregorianCalendar (java.util.GregorianCalendar)1 Locale (java.util.Locale)1