public static ExtendedKeyUsage createExtendedUsage(Collection<ASN1ObjectIdentifier> usages) { if (CollectionUtil.isEmpty(usages)) { return null; } List<ASN1ObjectIdentifier> list = new ArrayList<>(usages); List<ASN1ObjectIdentifier> sortedUsages = sortOidList(list); KeyPurposeId[] kps = new KeyPurposeId[sortedUsages.size()]; int idx = 0; for (ASN1ObjectIdentifier oid : sortedUsages) { kps[idx++] = KeyPurposeId.getInstance(oid); } return new ExtendedKeyUsage(kps); }
@Test public void test_TrustManagerFactory_extendedKeyUsage() throws Exception { // anyExtendedKeyUsage should work for client or server test_TrustManagerFactory_extendedKeyUsage( KeyPurposeId.anyExtendedKeyUsage, false, true, true); test_TrustManagerFactory_extendedKeyUsage( KeyPurposeId.anyExtendedKeyUsage, true, true, true); // critical clientAuth should work for client test_TrustManagerFactory_extendedKeyUsage( KeyPurposeId.id_kp_clientAuth, false, true, false); test_TrustManagerFactory_extendedKeyUsage(KeyPurposeId.id_kp_clientAuth, true, true, false); // critical serverAuth should work for server test_TrustManagerFactory_extendedKeyUsage( KeyPurposeId.id_kp_serverAuth, false, false, true); test_TrustManagerFactory_extendedKeyUsage(KeyPurposeId.id_kp_serverAuth, true, false, true); // codeSigning should not work test_TrustManagerFactory_extendedKeyUsage( KeyPurposeId.id_kp_codeSigning, false, false, false); test_TrustManagerFactory_extendedKeyUsage( KeyPurposeId.id_kp_codeSigning, true, false, false); }
private static List<ExtensionHolder> getServerExtensions(X509Certificate issuerCertificate) throws CertificateEncodingException, NoSuchAlgorithmException, IOException { List<ExtensionHolder> extensions = new ArrayList<>(); // SSO forces us to allow data encipherment extensions.add(new ExtensionHolder(Extension.keyUsage, true, new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment))); extensions.add(new ExtensionHolder(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth))); Extension authorityKeyExtension = new Extension(Extension.authorityKeyIdentifier, false, new DEROctetString(new JcaX509ExtensionUtils() .createAuthorityKeyIdentifier(issuerCertificate))); extensions.add(new ExtensionHolder(authorityKeyExtension.getExtnId(), authorityKeyExtension.isCritical(), authorityKeyExtension.getParsedValue())); return extensions; }
/** * Get Extended Key Usage (2.5.29.37) extension value as a string. * * <pre> * ExtendedKeyUsage ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId * KeyPurposeId ::= OBJECT IDENTIFIER * </pre> * * @param bValue The octet string value * @return Extension value as a string * @throws IOException If an I/O problem occurs */ private String getExtendedKeyUsageStringValue(byte[] bValue) throws IOException { StringBuilder strBuff = new StringBuilder(); ExtendedKeyUsage eku = ExtendedKeyUsage.getInstance(bValue); KeyPurposeId[] usages = eku.getUsages(); for (KeyPurposeId usage : usages) { if (strBuff.length() != 0) { strBuff.append("<br><br>"); } String sOid = usage.getId(); String sEku = getRes(sOid, "UnrecognisedExtKeyUsageString"); strBuff.append(MessageFormat.format(sEku, sOid)); } return strBuff.toString(); }
private static byte[] generateCSR(KeyPair keyPair, CertificateNamesGenerator certificateNamesGenerator) throws IOException, OperatorCreationException { ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator(); extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); extensionsGenerator.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth } )); extensionsGenerator.addExtension(Extension.subjectAlternativeName, true, certificateNamesGenerator.getSANs()); PKCS10CertificationRequest csr = new JcaPKCS10CertificationRequestBuilder(certificateNamesGenerator.getSubject(), keyPair.getPublic()) .addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate()) .build(new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate())); return PEMUtils.toPEM(csr); }
@Test public void givenASelfSignedCertificate_setsCertificateFieldsCorrectly() { final String distinguishedName = "O=test-org, ST=Jupiter, C=MilkyWay, CN=test-common-name, OU=test-org-unit, L=Europa"; final GeneralNames generalNames = new GeneralNames( new GeneralName(GeneralName.dNSName, "SolarSystem")); CertificateReader certificateReader = new CertificateReader(CertificateStringConstants.BIG_TEST_CERT); assertThat(certificateReader.getSubjectName().toString(), equalTo(distinguishedName)); assertThat(certificateReader.getKeyLength(), equalTo(4096)); assertThat(certificateReader.getAlternativeNames(), equalTo(generalNames)); assertThat(asList(certificateReader.getExtendedKeyUsage().getUsages()), containsInAnyOrder(KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth)); assertThat(certificateReader.getKeyUsage().hasUsages(KeyUsage.digitalSignature), equalTo(true)); assertThat(certificateReader.getDurationDays(), equalTo(30)); assertThat(certificateReader.isSelfSigned(), equalTo(false)); assertThat(certificateReader.isCa(), equalTo(false)); }
@Test public void returnsParametersCorrectly() { final String distinguishedName = "O=test-org, ST=Jupiter, C=MilkyWay, CN=test-common-name, OU=test-org-unit, L=Europa"; final GeneralNames generalNames = new GeneralNames( new GeneralName(GeneralName.dNSName, "SolarSystem")); CertificateReader certificateReader = new CertificateReader(CertificateStringConstants.BIG_TEST_CERT); assertThat(certificateReader.getAlternativeNames(), equalTo(generalNames)); assertThat(asList(certificateReader.getExtendedKeyUsage().getUsages()), containsInAnyOrder(KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth)); assertThat(certificateReader.getKeyUsage().hasUsages(KeyUsage.digitalSignature), equalTo(true)); assertThat(certificateReader.getSubjectName().toString(), equalTo(distinguishedName)); }
/** * Generate a CertificateToken suitable for a TSA * * @param algorithm * @param keyPair * @param issuer * @param subject * @param notBefore * @param notAfter * @return * @throws OperatorCreationException * @throws CertificateException * @throws IOException */ private CertificateToken generateTspCertificate(final SignatureAlgorithm algorithm, KeyPair keyPair, X500Name issuer, X500Name subject, final Date notBefore, final Date notAfter) throws OperatorCreationException, CertificateException, IOException { final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, new BigInteger("" + new Random().nextInt(10) + System.currentTimeMillis()), notBefore, notAfter, subject, keyInfo); certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping)); final ContentSigner signer = new JcaContentSignerBuilder(algorithm.getJCEId()).setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(keyPair.getPrivate()); final X509CertificateHolder holder = certBuilder.build(signer); final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X509") .generateCertificate(new ByteArrayInputStream(holder.getEncoded())); return new CertificateToken(cert); }
private static X509Certificate generateCertificate(final String domain, final KeyPair pair) { try { final X500Name issuerName = new X500Name("CN=" + domain); final X500Name subjectName = issuerName; final BigInteger serial = BigInteger.valueOf(new Random().nextInt()); final Date notBefore = Date.from(LocalDateTime.of(2016, 1, 1, 0, 0).toInstant(ZoneOffset.UTC)); final Date notAfter = Date.from(LocalDateTime.of(2099, 1, 1, 0, 0).toInstant(ZoneOffset.UTC)); final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, pair.getPublic()); builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); final ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); return signCertificate(builder, pair.getPrivate()); } catch (final CertIOException ex) { throw new RuntimeException("Couldn't generate certificate", ex); } }
private static void addRequestedExtKeyusage(List<ASN1ObjectIdentifier> usages, Extensions requestedExtensions, Set<ExtKeyUsageControl> usageOccs) { Extension extension = requestedExtensions.getExtension(Extension.extendedKeyUsage); if (extension == null) { return; } ExtendedKeyUsage reqKeyUsage = ExtendedKeyUsage.getInstance(extension.getParsedValue()); for (ExtKeyUsageControl k : usageOccs) { if (k.isRequired()) { continue; } if (reqKeyUsage.hasKeyPurposeId(KeyPurposeId.getInstance(k.extKeyUsage()))) { usages.add(k.extKeyUsage()); } } }
private void generateDummySSLClientCertificate(KeyStore ks) throws Exception { LOG.info("Generating a Dummy SSL client certificate ..."); KeyPair pair = CertificateUtilities.generateRSAKeyPair(getCryptoStrength()); String DN = "CN=SSL dummy client cert, O=Dummy org., C=FR"; X509V3CertificateGenerator v3CertGen = CertificateUtilities.initCertificateGenerator(pair, DN, DN, true, CertificateUtilities.DEFAULT_VALIDITY_PERIOD); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(NetscapeCertType.sslClient)); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); X509Certificate cert = v3CertGen.generate(pair.getPrivate()); ks.setKeyEntry(DUMMY_SSL_CLIENT_ALIAS, pair.getPrivate(), KEYSTORE_PASSWORD, new Certificate[] {cert}); }
public void generateCA(String prettyName) { this.prettyName = prettyName; Subject = "CN=JQM-CA,OU=ServerProducts,O=Oxymores,C=FR"; size = 4096; EKU = new KeyPurposeId[4]; EKU[0] = KeyPurposeId.id_kp_codeSigning; EKU[1] = KeyPurposeId.id_kp_serverAuth; EKU[2] = KeyPurposeId.id_kp_clientAuth; EKU[3] = KeyPurposeId.id_kp_emailProtection; keyUsage = KeyUsage.cRLSign | KeyUsage.keyCertSign; generateAll(); }
/** * Validate the passed in certificate as being of the correct type to be used * for time stamping. To be valid it must have an ExtendedKeyUsage extension * which has a key purpose identifier of id-kp-timeStamping. * * @param cert the certificate of interest. * @throws TSPValidationException if the certicate fails on one of the check points. */ public static void validateCertificate( X509CertificateHolder cert) throws TSPValidationException { if (cert.toASN1Structure().getVersionNumber() != 3) { throw new IllegalArgumentException("Certificate must have an ExtendedKeyUsage extension."); } Extension ext = cert.getExtension(Extension.extendedKeyUsage); if (ext == null) { throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension."); } if (!ext.isCritical()) { throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical."); } ExtendedKeyUsage extKey = ExtendedKeyUsage.getInstance(ext.getParsedValue()); if (!extKey.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping) || extKey.size() != 1) { throw new TSPValidationException("ExtendedKeyUsage not solely time stamping."); } }
public ExtendedKeyUsageImpl(X509Certificate cert) throws IOException { keyPurposeIds = new ArrayList<>(); byte[] extVal = cert.getExtensionValue(Extension.extendedKeyUsage.getId()); if (extVal == null) return; org.bouncycastle.asn1.x509.ExtendedKeyUsage usage = org.bouncycastle.asn1.x509.ExtendedKeyUsage .getInstance(X509ExtensionUtil.fromExtensionValue(extVal)); KeyPurposeId[] usages = usage.getUsages(); for (int i = 0; i < usages.length; i++) { keyPurposeIds.add(usages[i].getId()); } }
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate */ public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
/** * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * * @param dn the distinguished name to use * @param publicKey the public key to issue the certificate to * @param extensions extensions extracted from the CSR * @param issuer the issuer's certificate * @param issuerKeyPair the issuer's keypair * @param signingAlgorithm the signing algorithm to use * @param days the number of days it should be valid for * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * @throws CertificateException if there is an error issuing the certificate */ public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic())); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // (3) subjectAlternativeName if(extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) { certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName)); } X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
public static KeyStore createKeyStore(KeyPair keyPair, BadRandom random) throws CertificateException, IOException, InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, OperatorCreationException { PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); X500Name issuerName = new X500Name("CN=127.0.0.1, O=TLS-Attacker, L=RUB, ST=NRW, C=DE"); X500Name subjectName = issuerName; BigInteger serial = BigInteger.valueOf(random.nextInt()); Date before = new Date(System.currentTimeMillis() - 5000); Date after = new Date(System.currentTimeMillis() + 600000); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, before, after, subjectName, publicKey); builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment); builder.addExtension(Extension.keyUsage, false, usage); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); String algorithm = createSigningAlgorithm(keyPair); X509Certificate cert = signCertificate(algorithm, builder, privateKey); cert.checkValidity(new Date()); cert.verify(publicKey); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry(ALIAS, privateKey, PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert }); return keyStore; }
/** * Validate the passed in certificate as being of the correct type to be used * for time stamping. To be valid it must have an ExtendedKeyUsage extension * which has a key purpose identifier of id-kp-timeStamping. * * @param cert the certificate of interest. * @throws TSPValidationException if the certificate fails on one of the check points. */ public static void validateCertificate( X509CertificateHolder cert) throws TSPValidationException { if (cert.toASN1Structure().getVersionNumber() != 3) { throw new IllegalArgumentException("Certificate must have an ExtendedKeyUsage extension."); } Extension ext = cert.getExtension(Extension.extendedKeyUsage); if (ext == null) { throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension."); } if (!ext.isCritical()) { throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical."); } ExtendedKeyUsage extKey = ExtendedKeyUsage.getInstance(ext.getParsedValue()); if (!extKey.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping) || extKey.size() != 1) { throw new TSPValidationException("ExtendedKeyUsage not solely time stamping."); } }
public static X509Certificate createCa( PublicKey publicKey, PrivateKey privateKey, String subject) { try { X500Principal principal = new X500Principal(subject); return createCertificate(publicKey, privateKey, principal, principal, 0, true, new ArrayList<KeyPurposeId>(), new ArrayList<Boolean>(), new ArrayList<GeneralName>(), new ArrayList<GeneralSubtree>(), new ArrayList<GeneralSubtree>(), null /* serialNumber, generated randomly */); } catch (Exception e) { throw new RuntimeException(e); } }
public static KeyStore createRootCertificate(Authority authority, String keyStoreType) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, IOException, OperatorCreationException, CertificateException, KeyStoreException { KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, authority.commonName()); nameBuilder.addRDN(BCStyle.O, authority.organization()); nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName()); X500Name issuer = nameBuilder.build(); BigInteger serial = BigInteger.valueOf(initRandomSerial()); X500Name subject = issuer; PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey); generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey)); generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign); generator.addExtension(Extension.keyUsage, false, usage); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); X509Certificate cert = signCertificate(generator, keyPair.getPrivate()); KeyStore result = KeyStore.getInstance(keyStoreType/* , PROVIDER_NAME */); result.load(null, null); result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert }); return result; }
private static void addASN1AndKeyUsageExtensions(JcaX509v3CertificateBuilder certificateBuilder) throws CertIOException { ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); KeyUsage keyUsage = new KeyUsage(keyCertSign | digitalSignature | keyEncipherment | dataEncipherment | cRLSign); certificateBuilder.addExtension(Extension.keyUsage, false, keyUsage); }
public void initializeKeyStore() throws GeneralSecurityException, IOException { KeyPair keyPair = generateKeyPair(1024); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, commonName); nameBuilder.addRDN(BCStyle.O, organization); nameBuilder.addRDN(BCStyle.OU, organizationalUnitName); X500Name issuer = nameBuilder.build(); BigInteger serial = BigInteger.valueOf(initRandomSerial()); X500Name subject = issuer; PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey); generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey)); generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign); generator.addExtension(Extension.keyUsage, false, usage); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); X509Certificate cert = signCertificate(generator, keyPair.getPrivate()); KeyStore keystore = KeyStore.getInstance(KEY_STORE_TYPE); keystore.load(null, null); keystore.setKeyEntry(alias, keyPair.getPrivate(), password, new Certificate[] { cert }); try (OutputStream os = new FileOutputStream(aliasFile(KEY_STORE_FILE_EXTENSION))) { keystore.store(os, password); } exportPem(aliasFile(".pem"), cert); }
private static List<ExtensionHolder> getClientExtensions() { List<ExtensionHolder> extensions = new ArrayList<>(); extensions.add(new ExtensionHolder(Extension.basicConstraints, true, new BasicConstraints(false))); extensions.add(new ExtensionHolder(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature))); extensions.add(new ExtensionHolder(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth))); return extensions; }
protected void addExtendedKeyUsage(X509v3CertificateBuilder certificateBuilder) throws CertIOException { certificateBuilder.addExtension( Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[]{ KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth } ) ); }
private ExtendedKeyUsage buildExtendedKeyUsage(CertificateGenerationRequestParameters params) { String[] extendedKeyUsageList = params.getExtendedKeyUsage(); if (extendedKeyUsageList == null){ return null; } KeyPurposeId[] keyPurposeIds = new KeyPurposeId[extendedKeyUsageList.length]; for (int i = 0; i < extendedKeyUsageList.length; i++) { switch (extendedKeyUsageList[i]) { case SERVER_AUTH: keyPurposeIds[i] = KeyPurposeId.id_kp_serverAuth; break; case CLIENT_AUTH: keyPurposeIds[i] = KeyPurposeId.id_kp_clientAuth; break; case CODE_SIGNING: keyPurposeIds[i] = KeyPurposeId.id_kp_codeSigning; break; case EMAIL_PROTECTION: keyPurposeIds[i] = KeyPurposeId.id_kp_emailProtection; break; case TIMESTAMPING: keyPurposeIds[i] = KeyPurposeId.id_kp_timeStamping; break; default: throw new ParameterizedValidationException("error.invalid_extended_key_usage", extendedKeyUsageList[i]); } } return new ExtendedKeyUsage(keyPurposeIds); }
private String getExtendedKeyUsageStringValue(byte[] value) throws IOException { // @formatter:off /* * ExtendedKeyUsage ::= ASN1Sequence SIZE (1..MAX) OF KeyPurposeId * * KeyPurposeId ::= OBJECT IDENTIFIER */ // @formatter:on StringBuilder sb = new StringBuilder(); ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance(value); for (KeyPurposeId keyPurposeId : extendedKeyUsage.getUsages()) { String oid = keyPurposeId.getId(); ExtendedKeyUsageType type = ExtendedKeyUsageType.resolveOid(oid); if (type != null) { sb.append(type.friendly()); } else { // Unrecognised key purpose ID sb.append(oid); } sb.append(NEWLINE); } return sb.toString(); }
private void prepopulateWithValue(byte[] value) throws IOException { ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance(value); for (KeyPurposeId keyPurposeId : extendedKeyUsage.getUsages()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) keyPurposeId.toASN1Primitive(); ExtendedKeyUsageType type = ExtendedKeyUsageType.resolveOid(oid.getId()); if (type == SERVER_AUTH) { jcbTlsWebServerAuthentication.setSelected(true); } else if (type == CLIENT_AUTH) { jcbTlsWebClientAuthentication.setSelected(true); } else if (type == CODE_SIGNING) { jcbCodeSigning.setSelected(true); } else if (type == DOCUMENT_SIGNING) { jcbDocumentSigning.setSelected(true); } else if (type == ADOBE_PDF_SIGNING) { jcbAdobePDFSigning.setSelected(true); } else if (type == EMAIL_PROTECTION) { jcbEmailProtection.setSelected(true); } else if (type == ENCRYPTED_FILE_SYSTEM) { jcbEncryptedFileSystem.setSelected(true); } else if (type == IPSEC_END_SYSTEM) { jcbIpSecurityEndSystem.setSelected(true); } else if (type == IPSEC_TUNNEL) { jcbIpSecurityTunnelTermination.setSelected(true); } else if (type == IPSEC_USER) { jcbIpSecurityUser.setSelected(true); } else if (type == SMARTCARD_LOGON) { jcbSmartcardLogon.setSelected(true); } else if (type == TIME_STAMPING) { jcbTimeStamping.setSelected(true); } else if (type == OCSP_SIGNING) { jcbOcspStamping.setSelected(true); } else if (type == ANY_EXTENDED_KEY_USAGE) { jcbAnyExtendedKeyUsage.setSelected(true); } } }
public X509Certificate generateV3Certificate(KeyPair keyPair, String issuer, String signatureAlgorithm, Long expirationTime) throws CertIOException, OperatorCreationException, CertificateException { PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); // Signers name X500Name issuerName = new X500Name(issuer); // Subjects name - the same as we are self signed. X500Name subjectName = new X500Name(issuer); // Serial BigInteger serial = new BigInteger(256, new SecureRandom()); // Not before Date notBefore = new Date(System.currentTimeMillis() - 10000); Date notAfter = new Date(expirationTime); // Create the certificate - version 3 JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, publicKey); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); ASN1ObjectIdentifier extendedKeyUsage = new ASN1ObjectIdentifier("2.5.29.37").intern(); builder.addExtension(extendedKeyUsage, false, new DERSequence(purposes)); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(privateKey); X509CertificateHolder holder = builder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder); return cert; }
public static X509Certificate generateClientCert(String subject, PublicKey entityKey, PrivateKey caKey, X509Certificate caCert, String... sans) throws NoSuchAlgorithmException, CertIOException, OperatorCreationException, CertificateException { X509v3CertificateBuilder certBldr = new JcaX509v3CertificateBuilder( caCert.getSubjectX500Principal(), BigInteger.valueOf(Math.abs(RANDOM.nextLong())), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + EXPIRATION.get() * 24 * 60 * 60 * 1000), new X500Principal("CN=" + subject), entityKey); List<GeneralName> sanNameList = new ArrayList<>(); for (String san : sans) { if (san.startsWith("IP:")) { sanNameList.add(new GeneralName(GeneralName.iPAddress, san.substring(3))); sanNameList.add(new GeneralName(GeneralName.dNSName, san.substring(3))); } else { sanNameList.add(new GeneralName(GeneralName.dNSName, san)); } } GeneralName[] sanNames = sanNameList.toArray(new GeneralName[sanNameList.size()]); certBldr.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(sanNames)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(false)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)) .addExtension(Extension.extendedKeyUsage, true, ExtendedKeyUsage.getInstance(new DERSequence(new ASN1Encodable[]{ KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })) ); ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(caKey); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); }
private static Set<String> getExtKeyUsage(byte[] extensionValue) { Set<String> usages = new HashSet<>(); org.bouncycastle.asn1.x509.ExtendedKeyUsage reqKeyUsage = org.bouncycastle.asn1.x509.ExtendedKeyUsage.getInstance(extensionValue); for (KeyPurposeId usage : reqKeyUsage.getUsages()) { usages.add(usage.getId()); } return usages; }
private void generateSSLServerCertificate(KeyStore store, X500PrivateCredential rootCredential) throws Exception { LOG.info("Generating SSL server certificate ..."); KeyPair pair = CertificateUtilities.generateRSAKeyPair(getCryptoStrength()); String DN = "CN=localhost, " + DN_ROOT; X509V3CertificateGenerator v3CertGen = CertificateUtilities.initCertificateGenerator(pair, rootCredential .getCertificate().getSubjectX500Principal().getName(), DN, false, CertificateUtilities.DEFAULT_VALIDITY_PERIOD); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(NetscapeCertType.sslServer | NetscapeCertType.sslClient)); // Firefox 2 disallows these extensions in an SSL server cert. IE7 doesn't care. // v3CertGen.addExtension(X509Extensions.KeyUsage, // true, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.keyAgreement | // KeyUsage.keyEncipherment)); Vector<KeyPurposeId> typicalSSLServerExtendedKeyUsages = new Vector<KeyPurposeId>(); typicalSSLServerExtendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); typicalSSLServerExtendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(typicalSSLServerExtendedKeyUsages)); X509Certificate publicKeyCertificate = v3CertGen.generate(pair.getPrivate()); store.setKeyEntry(MAILSTER_SSL_ALIAS, pair.getPrivate(), KEYSTORE_PASSWORD, new Certificate[] {publicKeyCertificate, rootCredential.getCertificate()}); CertificateUtilities.exportCertificate(publicKeyCertificate, SSL_CERT_FULL_PATH, false); }
/** * Forges a certificate with given certificate's attributes and signs it with CA of proxy. */ private static KeyCertPair imitatePeerCertificate(X509Certificate cert2Imitate) throws Exception { // TODO imitate key algorithm also // (cert2Imitate.getPublicKey().getAlgorithm()) KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); SecureRandom secureRandom = new SecureRandom(); byte[] serial = new byte[16]; secureRandom.nextBytes(serial); BigInteger serialNumber = new BigInteger(serial); if (serialNumber.signum() < 0) { serialNumber = serialNumber.negate(); } v3CertGen.setSerialNumber(serialNumber); v3CertGen.setIssuerDN(((X509Certificate) issuerCA.getCertificate()).getIssuerX500Principal()); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); v3CertGen.setSubjectDN(cert2Imitate.getSubjectX500Principal()); ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, extendedKeyUsage); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm("SHA1WithRSA"); Certificate pkCertificate = v3CertGen.generateX509Certificate((PrivateKey) issuerCA.getKey()); return new KeyCertPair(pkCertificate, keyPair.getPrivate()); }
/** * Validate the passed in certificate as being of the correct type to be used * for time stamping. To be valid it must have an ExtendedKeyUsage extension * which has a key purpose identifier of id-kp-timeStamping. * * @param cert the certificate of interest. * @throws TSPValidationException if the certicate fails on one of the check points. */ public static void validateCertificate( X509Certificate cert) throws TSPValidationException { if (cert.getVersion() != 3) { throw new IllegalArgumentException("Certificate must have an ExtendedKeyUsage extension."); } byte[] ext = cert.getExtensionValue(X509Extensions.ExtendedKeyUsage.getId()); if (ext == null) { throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension."); } if (!cert.getCriticalExtensionOIDs().contains(X509Extensions.ExtendedKeyUsage.getId())) { throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical."); } ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(ext)); try { aIn = new ASN1InputStream(new ByteArrayInputStream(((ASN1OctetString)aIn.readObject()).getOctets())); ExtendedKeyUsage extKey = ExtendedKeyUsage.getInstance(aIn.readObject()); if (!extKey.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping) || extKey.size() != 1) { throw new TSPValidationException("ExtendedKeyUsage not solely time stamping."); } } catch (IOException e) { throw new TSPValidationException("cannot process ExtendedKeyUsage extension"); } }