org.bouncycastle.asn1.x509.KeyPurposeId Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.KeyPurposeId. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractKeyStoreManager.java    From DeviceConnect-Android with MIT License 7 votes vote down vote up
private X509Certificate generateX509V3Certificate(final KeyPair keyPair,
                                                  final X500Principal subject,
                                                  final X500Principal issuer,
                                                  final Date notBefore,
                                                  final Date notAfter,
                                                  final BigInteger serialNumber,
                                                  final GeneralNames generalNames,
                                                  final boolean isCA) throws GeneralSecurityException {
    X509V3CertificateGenerator generator = new X509V3CertificateGenerator();
    generator.setSerialNumber(serialNumber);
    generator.setIssuerDN(issuer);
    generator.setSubjectDN(subject);
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setPublicKey(keyPair.getPublic());
    generator.setSignatureAlgorithm("SHA256WithRSAEncryption");
    generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isCA));
    generator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(160));
    generator.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
    if (generalNames != null) {
        generator.addExtension(X509Extensions.SubjectAlternativeName, false, generalNames);
    }
    return generator.generateX509Certificate(keyPair.getPrivate(), SecurityUtil.getSecurityProvider());
}
 
Example #2
Source File: DefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * This function validates that the KeyUsage Bits are subset of the Bits
 * permitted by the ozone profile.
 *
 * @param ext - KeyUsage Extension.
 * @param profile - PKI Profile - In this case this profile.
 * @return True, if the request key usage is a subset, false otherwise.
 */
private static Boolean validateExtendedKeyUsage(Extension ext,
    PKIProfile profile) {
  if (ext.isCritical()) {
    // https://tools.ietf.org/html/rfc5280#section-4.2.1.12
    // Ozone profile opts to mark this extension as non-critical.
    LOG.error("Extended Key usage marked as critical.");
    return false;
  }
  ExtendedKeyUsage extendedKeyUsage =
      ExtendedKeyUsage.getInstance(ext.getParsedValue());
  for (KeyPurposeId id : extendedKeyUsage.getUsages()) {
    if (!profile.validateExtendedKeyUsage(id)) {
      return false;
    }
  }
  return true;
}
 
Example #3
Source File: IdentityController.java    From Spark with Apache License 2.0 6 votes vote down vote up
public X509Certificate createSelfSignedCertificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, OperatorCreationException, CertificateException {

        long serial = System.currentTimeMillis();
        SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        X500Name name = new X500Name(createX500NameString());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(name, 
                                                                            BigInteger.valueOf(serial), 
                                                                            new Date(System.currentTimeMillis() - 1000000000), 
                                                                            new Date(System.currentTimeMillis() + 1000000000),
                                                                            name, 
                                                                            keyInfo
                                                                            );
        certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); 
        certBuilder.addExtension(Extension.keyUsage,         true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
        ContentSigner signer = csBuilder.build(keyPair.getPrivate());
        X509CertificateHolder certHolder = certBuilder.build(signer);
        X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
        
        return cert;
    }
 
Example #4
Source File: CertificateRequest.java    From jqm with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #5
Source File: IdentifiedCertprofile.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static void addRequestedExtKeyusage(List<ASN1ObjectIdentifier> usages,
    Map<ASN1ObjectIdentifier, Extension> requestedExtensions, Set<ExtKeyUsageControl> usageOccs) {
  Extension extension = requestedExtensions.get(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.getExtKeyUsage()))) {
      usages.add(k.getExtKeyUsage());
    }
  }
}
 
Example #6
Source File: X509Util.java    From xipki with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #7
Source File: CertificateReaderTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void returnsParametersCorrectly() {
  final String distinguishedName =
    "L=Europa, OU=test-org-unit, CN=test-common-name, C=MilkyWay, ST=Jupiter, O=test-org";
  final GeneralNames generalNames = new GeneralNames(
    new GeneralName(GeneralName.dNSName, "SolarSystem"));

  final CertificateReader certificateReader = new CertificateReader(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));
}
 
Example #8
Source File: CertificateReaderTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void givenASelfSignedCertificate_setsCertificateFieldsCorrectly() {
  final String distinguishedName =
    "L=Europa, OU=test-org-unit, CN=test-common-name, C=MilkyWay, ST=Jupiter, O=test-org";
  final GeneralNames generalNames = new GeneralNames(
    new GeneralName(GeneralName.dNSName, "SolarSystem"));

  final CertificateReader certificateReader = new CertificateReader(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));
}
 
Example #9
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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
 */
private String getExtendedKeyUsageStringValue(byte[] bValue)
{
	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();
}
 
Example #10
Source File: TPMAuthenticator.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
@Override
public X509Certificate createAttestationCertificate(AttestationStatementRequest attestationStatementRequest, AttestationOption attestationOption) {
    AttestationCertificateBuilder builder =
            new AttestationCertificateBuilder(
                    getAttestationIssuerCertificate(),
                    new X500Principal(attestationOption.getSubjectDN()),
                    this.getAttestationKeyPair().getPublic());

    builder.addSubjectAlternativeNamesExtension("2.23.133.2.3=#0c0b69643a3030303230303030,2.23.133.2.2=#0c03535054,2.23.133.2.1=#0c0b69643a3439344535343433");

    if (attestationOption.isCAFlagInBasicConstraints()) {
        builder.addBasicConstraintsExtension();
    }
    if (attestationOption instanceof TPMAttestationOption) {
        TPMAttestationOption tpmAttestationOption = (TPMAttestationOption) attestationOption;
        if (tpmAttestationOption.isTcgKpAIKCertificateFlagInExtendedKeyUsage()) {
            builder.addExtendedKeyUsageExtension(KeyPurposeId.getInstance(new ASN1ObjectIdentifier("2.23.133.8.3")));
        }
    }
    return builder.build(this.getAttestationIssuerPrivateKey());
}
 
Example #11
Source File: CertificateGenerator.java    From NetBare with MIT License 5 votes vote down vote up
/**
 * Generate a root keystore by a given {@link JKS}.
 *
 * @param jks A java keystore object.
 * @return A root {@link KeyStore}.
 */
public KeyStore generateRoot(JKS jks)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, OperatorCreationException {
    KeyPair keyPair = generateKeyPair(ROOT_KEY_SIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, jks.commonName());
    nameBuilder.addRDN(BCStyle.O, jks.organization());
    nameBuilder.addRDN(BCStyle.OU, jks.organizationalUnitName());
    X500Name issuer = nameBuilder.build();

    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, BigInteger.valueOf(randomSerial()), NOT_BEFORE, NOT_AFTER, issuer, 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(KEY_STORE_TYPE);
    result.load(null, null);
    result.setKeyEntry(jks.alias(), keyPair.getPrivate(), jks.password(),
            new Certificate[] { cert });
    return result;
}
 
Example #12
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a extension with Extended Key usage.
 * @param purposeId - Usage that we want to encode.
 * @param critical -  makes the extension critical.
 * @return Extensions.
 */
private Extensions getKeyUsageExtension(KeyPurposeId purposeId,
    boolean critical) throws IOException {
  ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(purposeId);
  ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
  extensionsGenerator.addExtension(
      Extension.extendedKeyUsage, critical, extendedKeyUsage);
  return extensionsGenerator.generate();
}
 
Example #13
Source File: OxAuthCryptoProvider.java    From oxAuth with MIT License 5 votes vote down vote up
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;
}
 
Example #14
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that Invalid Extended Key usage works as expected, that is rejected.
 * @throws IOException - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testInValidExtendedKeyUsage() throws IOException,
    OperatorCreationException {
  Extensions extendedExtension =
      getKeyUsageExtension(KeyPurposeId.id_kp_clientAuth, true);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, extendedExtension);
  assertFalse(testApprover.verfiyExtensions(csr));

  extendedExtension = getKeyUsageExtension(KeyPurposeId.id_kp_OCSPSigning,
      false);
  csr = getInvalidCSR(keyPair, extendedExtension);
  assertFalse(testApprover.verfiyExtensions(csr));
}
 
Example #15
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getExtendedKeyUsageStringValue(byte[] value)  {
	// @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();
}
 
Example #16
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #17
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that valid Extended Key usage works as expected.
 * @throws IOException - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testValidExtendedKeyUsage() throws IOException,
    OperatorCreationException {
  Extensions extendedExtension =
      getKeyUsageExtension(KeyPurposeId.id_kp_clientAuth, false);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, extendedExtension);
  assertTrue(testApprover.verfiyExtensions(csr));

  extendedExtension = getKeyUsageExtension(KeyPurposeId.id_kp_serverAuth,
      false);
  csr = getInvalidCSR(keyPair, extendedExtension);
  assertTrue(testApprover.verfiyExtensions(csr));
}
 
Example #18
Source File: CertificateUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #19
Source File: CertificateUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #20
Source File: TLSArtifactsGenerator.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("checkstyle:ThrowsCount")
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);
}
 
Example #21
Source File: OcspCertificateValidatorTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a signed certificate with a specific keypair.
 *
 * @param dn      the DN
 * @param keyPair the public key will be included in the certificate and the the private key is used to sign the certificate
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateCertificate(String dn, KeyPair keyPair) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException,
        InvalidKeyException, OperatorCreationException {
    PrivateKey privateKey = keyPair.getPrivate();
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(privateKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
            new X500Name(dn),
            BigInteger.valueOf(System.currentTimeMillis()),
            startDate, endDate,
            new X500Name(dn),
            subPubKeyInfo);

    // Set certificate extensions
    // (1) digitalSignature extension
    certBuilder.addExtension(X509Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement));

    // (2) extendedKeyUsage extension
    Vector<KeyPurposeId> ekUsages = new Vector<>();
    ekUsages.add(KeyPurposeId.id_kp_clientAuth);
    ekUsages.add(KeyPurposeId.id_kp_serverAuth);
    certBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(ekUsages));

    // Sign the certificate
    X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example #22
Source File: TLSCertificateBuilder.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
ExtendedKeyUsage keyUsage() {
    KeyPurposeId[] kpid = new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth};
    if (this.ordinal() == 1) {
        kpid[0] = KeyPurposeId.id_kp_serverAuth;
    }
    return new ExtendedKeyUsage(kpid);
}
 
Example #23
Source File: CertificateHelper.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: TlsResourceBuilder.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public static X509Certificate createCertificateForServerAuthorization(final KeyPair keyPair,
                                                                      final KeyCertificatePair ca,
                                                                      final String dn,
                                                                      final AlternativeName... alternativeName)
        throws CertificateException
{
    return createCertificate(keyPair,
                             ca,
                             dn,
                             createValidityPeriod(),
                             createExtendedUsageExtension(new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth})),
                             createAuthorityKeyExtension(ca.getCertificate().getPublicKey()),
                             createSubjectKeyExtension(keyPair.getPublic()),
                             createAlternateNamesExtension(alternativeName));
}
 
Example #25
Source File: CertificateUtils.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #26
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #27
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #28
Source File: OcspCertificateValidatorTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a signed certificate with a specific keypair.
 *
 * @param dn      the DN
 * @param keyPair the public key will be included in the certificate and the the private key is used to sign the certificate
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateCertificate(String dn, KeyPair keyPair) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException,
        InvalidKeyException, OperatorCreationException {
    PrivateKey privateKey = keyPair.getPrivate();
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(privateKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
            new X500Name(dn),
            BigInteger.valueOf(System.currentTimeMillis()),
            startDate, endDate,
            new X500Name(dn),
            subPubKeyInfo);

    // Set certificate extensions
    // (1) digitalSignature extension
    certBuilder.addExtension(X509Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement));

    // (2) extendedKeyUsage extension
    Vector<KeyPurposeId> ekUsages = new Vector<>();
    ekUsages.add(KeyPurposeId.id_kp_clientAuth);
    ekUsages.add(KeyPurposeId.id_kp_serverAuth);
    certBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(ekUsages));

    // Sign the certificate
    X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example #29
Source File: CertificateAutogenTask.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Path process(Path inputFile) throws IOException {
    if (signedDataGenerator != null) return inputFile;
    try {
        LogHelper.warning("You are using an auto-generated certificate (sign.enabled false). It is not good");
        LogHelper.warning("It is highly recommended that you use the correct certificate (sign.enabled true)");
        LogHelper.warning("You can use GenerateCertificateModule or your own certificate.");
        X500NameBuilder subject = new X500NameBuilder();
        subject.addRDN(BCStyle.CN, server.config.projectName.concat(" Autogenerated"));
        subject.addRDN(BCStyle.O, server.config.projectName);
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
        X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
                subject.build(),
                new BigInteger("0"),
                Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
                Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
                new X500Name("CN=ca"),
                SubjectPublicKeyInfo.getInstance(server.publicKey.getEncoded()));
        builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_codeSigning));
        //builder.addExtension(Extension.keyUsage, false, new KeyUsage(1));
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
        ContentSigner signer = csBuilder.build(server.privateKey);
        bcCertificate = builder.build(signer);
        certificate = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(bcCertificate);
        ArrayList<Certificate> chain = new ArrayList<>();
        chain.add(certificate);
        signedDataGenerator = SignHelper.createSignedDataGenerator(server.privateKey, certificate, chain, "SHA256WITHECDSA");
    } catch (OperatorCreationException | CMSException | CertificateException e) {
        LogHelper.error(e);
    }
    return inputFile;
}
 
Example #30
Source File: ExtendedKeyUsageImpl.java    From SecuritySample with Apache License 2.0 5 votes vote down vote up
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());
	}
}