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);
}
}
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;
}
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();
}
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;
}
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();
}
}
}
Aggregations