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); }
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); }
/** * 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 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}); }
/** * 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."); } }
/** * 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); } }
/** * 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."); } }
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 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 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); }
/** * Adds an extended key usage extension to the certificate. */ protected void addExtendedKeyUsageExtension() { if (_ekus.isEmpty()) return; ExtendedKeyUsage eku = new ExtendedKeyUsage(_ekus); _generator.addExtension(X509Extensions.ExtendedKeyUsage, false, eku); }
/** * Open up the ability to add additional extensions that aren't * EKU or SubjectAltName (which we manage). */ public void addExtension( String oid, boolean critical, byte [] value) { if (null == oid) throw new IllegalArgumentException("OID cannot be null!"); DERObjectIdentifier derOID = new DERObjectIdentifier(oid); if ((derOID.equals(X509Extensions.ExtendedKeyUsage)) || (derOID.equals(X509Extensions.SubjectAlternativeName)) || (derOID.equals(X509Extensions.AuthorityKeyIdentifier))) { throw new IllegalArgumentException("Cannot use addExtension to set ExtendedKeyUsage or SubjectAlternativeName or AuthorityKeyIdentifier!"); } _generator.addExtension(derOID, critical, value); }
/** * 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"); } }
public ExtendedKeyUsage getExtendedKeyUsage() { return ExtendedKeyUsage.fromExtensions(certificateHolder.getExtensions()); }
public ExtendedKeyUsage getExtendedKeyUsage() { return extendedKeyUsage; }
private static void addCertificateExtensions(PublicKey pubKey, PublicKey caPubKey, X509V3CertificateGenerator certGen) throws IOException, InvalidKeyException { // CertificateExtensions ext = new CertificateExtensions(); // // ext.set(SubjectKeyIdentifierExtension.NAME, // new SubjectKeyIdentifierExtension(new KeyIdentifier(pubKey) // .getIdentifier())); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); // // ext.set(AuthorityKeyIdentifierExtension.NAME, // new AuthorityKeyIdentifierExtension( // new KeyIdentifier(caPubKey), null, null)); // certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caPubKey)); // // Basic Constraints // ext.set(BasicConstraintsExtension.NAME, new // BasicConstraintsExtension( // /* isCritical */true, /* isCA */false, /* pathLen */5)); // certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); // Netscape Cert Type Extension // boolean[] ncteOk = new boolean[8]; // ncteOk[0] = true; // SSL_CLIENT // ncteOk[1] = true; // SSL_SERVER // NetscapeCertTypeExtension ncte = new // NetscapeCertTypeExtension(ncteOk); // ncte = new NetscapeCertTypeExtension(false, // ncte.getExtensionValue()); // ext.set(NetscapeCertTypeExtension.NAME, ncte); // Key Usage Extension // boolean[] kueOk = new boolean[9]; // kueOk[0] = true; // kueOk[2] = true; // "digitalSignature", // (0), // "nonRepudiation", // (1) // "keyEncipherment", // (2), // "dataEncipherment", // (3), // "keyAgreement", // (4), // "keyCertSign", // (5), // "cRLSign", // (6), // "encipherOnly", // (7), // "decipherOnly", // (8) // "contentCommitment" // also (1) // KeyUsageExtension kue = new KeyUsageExtension(kueOk); // ext.set(KeyUsageExtension.NAME, kue); certGen.addExtension(X509Extensions.KeyUsage, true, new X509KeyUsage( X509KeyUsage.digitalSignature + X509KeyUsage.keyEncipherment)); // Extended Key Usage Extension // int[] serverAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 1 }; // ObjectIdentifier serverAuthOid = new // ObjectIdentifier(serverAuthOidData); // int[] clientAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 2 }; // ObjectIdentifier clientAuthOid = new // ObjectIdentifier(clientAuthOidData); // Vector<ObjectIdentifier> v = new Vector<ObjectIdentifier>(); // v.add(serverAuthOid); // v.add(clientAuthOid); // ExtendedKeyUsageExtension ekue = new ExtendedKeyUsageExtension(false, // v); // ext.set(ExtendedKeyUsageExtension.NAME, ekue); // ExtendedKeyUsage extendedKeyUsage = new // ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage); Vector<KeyPurposeId> usages = new Vector<KeyPurposeId>(); usages.add(KeyPurposeId.id_kp_serverAuth); usages.add(KeyPurposeId.id_kp_clientAuth); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(usages)); }
ExtKeyUsageExtension(final ExtendedKeyUsage extendedKeyUsage) { super(Extension.extendedKeyUsage, false, extendedKeyUsage); }
ExtKeyUsageExtension(final KeyPurposeId usage) { this(new ExtendedKeyUsage(usage)); }
ExtKeyUsageExtension(final KeyPurposeId[] usages) { this(new ExtendedKeyUsage(usages)); }
private void generateX509() throws Exception { SecureRandom random = new SecureRandom(); X500Name dnName = new X500Name(Subject); Calendar endValidity = Calendar.getInstance(); endValidity.add(Calendar.YEAR, validityYear); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); X509v3CertificateBuilder gen = new X509v3CertificateBuilder( authorityCertificate == null ? dnName : authorityCertificate.getSubject(), BigIntegers.createRandomInRange(BigInteger.ZERO, BigInteger.valueOf(Long.MAX_VALUE), random), new Date(), endValidity.getTime(), dnName, publicKeyInfo); // Public key ID DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc); gen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo)); // EKU gen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU)); // Basic constraints (is CA?) if (authorityCertificate == null) { gen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); } // Key usage gen.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage)); // Subject Alt names ? // Authority if (authorityCertificate != null) { gen.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(authorityCertificate.getSubjectPublicKeyInfo())); } // Signer ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").setProvider(Constants.JCA_PROVIDER) .build(authorityKey == null ? privateKey : authorityKey); // Go holder = gen.build(signer); }
public static X509Certificate makeCertificate(KeyPair _subKP, String _subDN, KeyPair _issKP, String _issDN, boolean _ca) throws GeneralSecurityException, IOException { PublicKey _subPub = _subKP.getPublic(); PrivateKey _issPriv = _issKP.getPrivate(); PublicKey _issPub = _issKP.getPublic(); X509V3CertificateGenerator _v3CertGen = new X509V3CertificateGenerator(); _v3CertGen.reset(); _v3CertGen.setSerialNumber(allocateSerialNumber()); _v3CertGen.setIssuerDN(new X509Name(_issDN)); _v3CertGen.setNotBefore(new Date(System.currentTimeMillis())); _v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100))); _v3CertGen.setSubjectDN(new X509Name(_subDN)); _v3CertGen.setPublicKey(_subPub); _v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption"); _v3CertGen.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(_subPub)); _v3CertGen.addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(_issPub)); if (_ca) { _v3CertGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(_ca)); } else { _v3CertGen.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping)); } X509Certificate _cert = _v3CertGen.generate(_issPriv); _cert.checkValidity(new Date()); _cert.verify(_issPub); return _cert; }