use of org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder 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);
}
}
}
Aggregations