List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name
public X500Name(String dirName)
From source file:com.gitblit.utils.X509Utils.java
License:Apache License
/** * Revoke a certificate.//from w w w . j ava 2 s. c o m * * @param cert * @param reason * @param caRevocationList * @param caPrivateKey * @param x509log * @return true if the certificate has been revoked */ public static boolean revoke(X509Certificate cert, RevocationReason reason, File caRevocationList, PrivateKey caPrivateKey, X509Log x509log) { try { X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(cert).getName()); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date()); if (caRevocationList.exists()) { byte[] data = FileUtils.readContent(caRevocationList); X509CRLHolder crl = new X509CRLHolder(data); crlBuilder.addCRL(crl); } crlBuilder.addCRLEntry(cert.getSerialNumber(), new Date(), reason.ordinal()); // build and sign CRL with CA private key ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(caPrivateKey); X509CRLHolder crl = crlBuilder.build(signer); File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp"); FileOutputStream fos = null; try { fos = new FileOutputStream(tmpFile); fos.write(crl.getEncoded()); fos.flush(); fos.close(); if (caRevocationList.exists()) { caRevocationList.delete(); } tmpFile.renameTo(caRevocationList); } finally { if (fos != null) { fos.close(); } if (tmpFile.exists()) { tmpFile.delete(); } } x509log.log(MessageFormat.format("Revoked certificate {0,number,0} reason: {1} [{2}]", cert.getSerialNumber(), reason.toString(), cert.getSubjectDN().getName())); return true; } catch (IOException | OperatorCreationException | CertificateEncodingException e) { logger.error(MessageFormat.format("Failed to revoke certificate {0,number,0} [{1}] in {2}", cert.getSerialNumber(), cert.getSubjectDN().getName(), caRevocationList)); } return false; }
From source file:com.github.ambry.commons.TestSSLUtils.java
License:Open Source License
/** * Create a self-signed X.509 Certificate. * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html. * * @param dn the X.509 Distinguished Name, eg "CN(commonName)=Test, O(organizationName)=Org" * @param pair the KeyPair/*from w w w .j a v a 2s . co m*/ * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate * @throws java.security.cert.CertificateException thrown if a security error or an IO error ocurred. */ public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException { try { Security.addProvider(new BouncyCastleProvider()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory .createKey(pair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); X500Name name = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000L); BigInteger sn = new BigInteger(64, new SecureRandom()); X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo); X509CertificateHolder certificateHolder = v1CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); } catch (CertificateException ce) { throw ce; } catch (Exception e) { throw new CertificateException(e); } }
From source file:com.github.spyhunter99.simplejks.CertGenBouncy.java
public static java.security.cert.Certificate selfSign(KeyPair keyPair, String subjectDN) throws OperatorCreationException, CertificateException, IOException { Provider bcProvider = new BouncyCastleProvider(); Security.addProvider(bcProvider); long now = System.currentTimeMillis(); Date startDate = new Date(now); X500Name dnName = new X500Name(subjectDN); BigInteger certSerialNumber = new BigInteger(Long.toString(now)); // <-- Using the current timestamp as the certificate serial number Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate);//from w w w.j a v a 2 s .c o m calendar.add(Calendar.YEAR, 30); // <-- 1 Yr validity Date endDate = calendar.getTime(); String signatureAlgorithm = "SHA256WithRSA"; // <-- Use appropriate signature algorithm based on your keyPair algorithm. ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate()); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic()); // Extensions -------------------------- // Basic Constraints BasicConstraints basicConstraints = new BasicConstraints(true); // <-- true for CA, false for EndEntity certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); // Basic Constraints is usually marked as critical. ASN1Encodable[] subjectAlternativeNames = new ASN1Encodable[] { new GeneralName(GeneralName.dNSName, "server"), new GeneralName(GeneralName.dNSName, "server.mydomain.com") }; DERSequence subjectAlternativeNamesExtension = new DERSequence(subjectAlternativeNames); certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAlternativeNamesExtension); // ------------------------------------- return new JcaX509CertificateConverter().setProvider(bcProvider) .getCertificate(certBuilder.build(contentSigner)); }
From source file:com.google.api.auth.TestUtils.java
License:Open Source License
/** * Generate a PEM-encoded X509 using the given {@link RsaJsonWebKey}. *///from ww w. j a va2 s. c om public static String generateX509Cert(RsaJsonWebKey rsaJsonWebKey) { try { Provider provider = new BouncyCastleProvider(); String providerName = provider.getName(); Security.addProvider(provider); long currentTimeMillis = System.currentTimeMillis(); Date start = new Date(currentTimeMillis - TimeUnit.DAYS.toMillis(1)); Date end = new Date(currentTimeMillis + TimeUnit.DAYS.toMillis(1)); X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( new X500Name("cn=example"), BigInteger.valueOf(currentTimeMillis), start, end, new X500Name("cn=example"), SubjectPublicKeyInfo.getInstance(rsaJsonWebKey.getPublicKey().getEncoded())); ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1WithRSAEncryption") .setProvider(providerName).build(rsaJsonWebKey.getPrivateKey()); X509CertificateHolder x509CertHolder = x509v3CertificateBuilder.build(contentSigner); X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertHolder); Security.removeProvider(providerName); return String.format("%s%n%s%n%s", DefaultJwksSupplier.X509_CERT_PREFIX, new X509Util().toPem(certificate), DefaultJwksSupplier.X509_CERT_SUFFIX); } catch (Exception exception) { throw new RuntimeException(exception); } }
From source file:com.google.bitcoin.protocols.payments.PaymentSession.java
License:Apache License
/** * Uses the provided PKI method to find the corresponding public key and verify the provided signature. * Returns null if no PKI method was specified in the {@link Protos.PaymentRequest}. *//* w ww . j a v a2 s . c om*/ public @Nullable PkiVerificationData verifyPki() throws PaymentRequestException { try { if (pkiVerificationData != null) return pkiVerificationData; if (paymentRequest.getPkiType().equals("none")) // Nothing to verify. Everything is fine. Move along. return null; String algorithm; if (paymentRequest.getPkiType().equals("x509+sha256")) algorithm = "SHA256withRSA"; else if (paymentRequest.getPkiType().equals("x509+sha1")) algorithm = "SHA1withRSA"; else throw new PaymentRequestException.InvalidPkiType( "Unsupported PKI type: " + paymentRequest.getPkiType()); Protos.X509Certificates protoCerts = Protos.X509Certificates.parseFrom(paymentRequest.getPkiData()); if (protoCerts.getCertificateCount() == 0) throw new PaymentRequestException.InvalidPkiData( "No certificates provided in message: server config error"); // Parse the certs and turn into a certificate chain object. Cert factories can parse both DER and base64. // The ordering of certificates is defined by the payment protocol spec to be the same as what the Java // crypto API requires - convenient! CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); List<X509Certificate> certs = Lists.newArrayList(); for (ByteString bytes : protoCerts.getCertificateList()) certs.add((X509Certificate) certificateFactory.generateCertificate(bytes.newInput())); CertPath path = certificateFactory.generateCertPath(certs); // Retrieves the most-trusted CAs from keystore. PKIXParameters params = new PKIXParameters(createKeyStore(trustStorePath)); // Revocation not supported in the current version. params.setRevocationEnabled(false); // Now verify the certificate chain is correct and trusted. This let's us get an identity linked pubkey. CertPathValidator validator = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(path, params); PublicKey publicKey = result.getPublicKey(); // OK, we got an identity, now check it was used to sign this message. Signature signature = Signature.getInstance(algorithm); // Note that we don't use signature.initVerify(certs.get(0)) here despite it being the most obvious // way to set it up, because we don't care about the constraints specified on the certificates: any // cert that links a key to a domain name or other identity will do for us. signature.initVerify(publicKey); Protos.PaymentRequest.Builder reqToCheck = paymentRequest.toBuilder(); reqToCheck.setSignature(ByteString.EMPTY); signature.update(reqToCheck.build().toByteArray()); if (!signature.verify(paymentRequest.getSignature().toByteArray())) throw new PaymentRequestException.PkiVerificationException( "Invalid signature, this payment request is not valid."); // Signature verifies, get the names from the identity we just verified for presentation to the user. final X509Certificate cert = certs.get(0); X500Principal principal = cert.getSubjectX500Principal(); // At this point the Java crypto API falls flat on its face and dies - there's no clean way to get the // different parts of the certificate name except for parsing the string. That's hard because of various // custom escaping rules and the usual crap. So, use Bouncy Castle to re-parse the string into binary form // again and then look for the names we want. Fail! org.bouncycastle.asn1.x500.X500Name name = new X500Name(principal.getName()); String entityName = null, orgName = null; for (RDN rdn : name.getRDNs()) { AttributeTypeAndValue pair = rdn.getFirst(); if (pair.getType().equals(RFC4519Style.cn)) entityName = ((ASN1String) pair.getValue()).getString(); else if (pair.getType().equals(RFC4519Style.o)) orgName = ((ASN1String) pair.getValue()).getString(); } if (entityName == null && orgName == null) { // This cert might not be an SSL cert. Just grab the first "subject alt name" if present, e.g. for // S/MIME certs. final Iterator<List<?>> it = cert.getSubjectAlternativeNames().iterator(); List<?> list; // email addresses have a type code of one. if (it.hasNext() && (list = it.next()) != null && (Integer) list.get(0) == 1) entityName = (String) list.get(1); if (entityName == null) throw new PaymentRequestException.PkiVerificationException( "Could not extract name from certificate"); } // Everything is peachy. Return some useful data to the caller. PkiVerificationData data = new PkiVerificationData(entityName, orgName, publicKey, result.getTrustAnchor()); // Cache the result so we don't have to re-verify if this method is called again. pkiVerificationData = data; return data; } catch (InvalidProtocolBufferException e) { // Data structures are malformed. throw new PaymentRequestException.InvalidPkiData(e); } catch (CertificateException e) { // The X.509 certificate data didn't parse correctly. throw new PaymentRequestException.PkiVerificationException(e); } catch (NoSuchAlgorithmException e) { // Should never happen so don't make users have to think about it. PKIX is always present. throw new RuntimeException(e); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } catch (CertPathValidatorException e) { // The certificate chain isn't known or trusted, probably, the server is using an SSL root we don't // know about and the user needs to upgrade to a new version of the software (or import a root cert). throw new PaymentRequestException.PkiVerificationException(e); } catch (InvalidKeyException e) { // Shouldn't happen if the certs verified correctly. throw new PaymentRequestException.PkiVerificationException(e); } catch (SignatureException e) { // Something went wrong during hashing (yes, despite the name, this does not mean the sig was invalid). throw new PaymentRequestException.PkiVerificationException(e); } catch (IOException e) { throw new PaymentRequestException.PkiVerificationException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } }
From source file:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfigTestUtil.java
License:Open Source License
private static X509Certificate generateCertificate(KeyPair keyPair) throws OperatorCreationException, CertificateException { Calendar endCalendar = Calendar.getInstance(); endCalendar.add(Calendar.YEAR, 10); X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( new X500Name("CN=localhost"), BigInteger.valueOf(1), Calendar.getInstance().getTime(), endCalendar.getTime(), new X500Name("CN=localhost"), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate()); X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(x509CertificateHolder); }
From source file:com.helger.ebinterface.signature.CreateCertHelper.java
License:Apache License
@Nonnull public static X500Name x500(@Nonnull @Nonempty final String sCommonName, @Nonnull @Nonempty final String sOrganization, @Nonnull @Nonempty final String sCountry) { return new X500Name("CN=" + sCommonName + ", O=" + sOrganization + ", C=" + sCountry); }
From source file:com.helger.ebinterface.signature.CreateCertHelper.java
License:Apache License
@Nonnull public static PKCS10CertificationRequest createCSR(final X509Certificate cert, final KeyPair keyPair) throws Exception { final Principal principal = cert.getSubjectDN(); // generate certification request final X500Name x500Name = new X500Name(principal.toString()); final PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(x500Name, keyPair.getPublic());/*from w ww . j a v a 2 s .com*/ final JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(SIGNING_ALGO); final ContentSigner signer = csBuilder.build(keyPair.getPrivate()); return p10Builder.build(signer); }
From source file:com.ipseorama.webapp.baddtls.CertHolder.java
License:Open Source License
private void mkSelfSignedCert() throws Exception { //Security.addProvider(PROVIDER); SecureRandom random = new SecureRandom(); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA"); kpGen.initialize(1024, random);//from w w w . j a va2 s . c om KeyPair keypair = kpGen.generateKeyPair(); PrivateKey key = keypair.getPrivate(); Date notBefore = new Date(System.currentTimeMillis() - 10000); Date notAfter = new Date(System.currentTimeMillis() + 100000); // Prepare the information required for generating an X.509 certificate. X500Name owner = new X500Name("CN=" + "evil@baddtls.com"); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(owner, new BigInteger(64, random), notBefore, notAfter, owner, keypair.getPublic()); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(key); X509CertificateHolder certHolder = builder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder); cert.verify(keypair.getPublic()); org.bouncycastle.asn1.x509.Certificate carry[] = new org.bouncycastle.asn1.x509.Certificate[1]; carry[0] = org.bouncycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()); _cert = new Certificate(carry); }
From source file:com.liferay.sync.util.SyncUtil.java
License:Open Source License
public static void enableLanSync(long companyId) throws Exception { String lanServerUuid = PrefsPropsUtil.getString(companyId, SyncConstants.SYNC_LAN_SERVER_UUID); if (Validator.isNotNull(lanServerUuid)) { return;/*from w w w . j a v a 2 s. c om*/ } lanServerUuid = PortalUUIDUtil.generate(); X500Name x500Name = new X500Name("CN=" + lanServerUuid); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X509v3CertificateBuilder x509v3CertificateBuilder = new JcaX509v3CertificateBuilder(x500Name, new BigInteger(64, new SecureRandom()), new Date(System.currentTimeMillis() - Time.YEAR), new Date(System.currentTimeMillis() + Time.YEAR * 1000), x500Name, keyPair.getPublic()); PrivateKey privateKey = keyPair.getPrivate(); JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder("SHA256WithRSAEncryption"); JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); jcaX509CertificateConverter.setProvider(_provider); X509Certificate x509Certificate = jcaX509CertificateConverter .getCertificate(x509v3CertificateBuilder.build(jcaContentSignerBuilder.build(privateKey))); x509Certificate.verify(keyPair.getPublic()); PortletPreferences portletPreferences = PrefsPropsUtil.getPreferences(companyId); portletPreferences.setValue(SyncConstants.SYNC_LAN_CERTIFICATE, Base64.encode(x509Certificate.getEncoded())); portletPreferences.setValue(SyncConstants.SYNC_LAN_KEY, Base64.encode(privateKey.getEncoded())); portletPreferences.setValue(SyncConstants.SYNC_LAN_SERVER_UUID, lanServerUuid); portletPreferences.store(); }