Java Code Examples for org.bouncycastle.asn1.x509.ExtendedKeyUsage

The following examples show how to use org.bouncycastle.asn1.x509.ExtendedKeyUsage. These examples are extracted from open source projects. 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 Project: hadoop-ozone   Source File: DefaultProfile.java    License: 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 2
Source Project: portecle   Source File: X509Ext.java    License: 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 3
Source Project: DeviceConnect-Android   Source File: AbstractKeyStoreManager.java    License: MIT License 6 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 4
Source Project: xipki   Source File: X509Util.java    License: 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 5
Source Project: xipki   Source File: IdentifiedCertprofile.java    License: 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 Project: Spark   Source File: IdentityController.java    License: 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 7
Source Project: hadoop-ozone   Source File: TestDefaultProfile.java    License: 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 8
Source Project: localization_nifi   Source File: CertificateUtils.java    License: 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 9
Source Project: localization_nifi   Source File: CertificateUtils.java    License: 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 10
/**
 * 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 11
@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 12
Source Project: nifi-registry   Source File: CertificateUtils.java    License: 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 13
Source Project: nifi-registry   Source File: CertificateUtils.java    License: 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 14
Source Project: qpid-broker-j   Source File: TlsResourceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public static X509Certificate createCertificateForClientAuthorization(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_clientAuth})),
                             createAuthorityKeyExtension(ca.getCertificate().getPublicKey()),
                             createSubjectKeyExtension(keyPair.getPublic()),
                             createAlternateNamesExtension(alternativeName));
}
 
Example 15
Source Project: qpid-broker-j   Source File: TlsResourceBuilder.java    License: 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 16
Source Project: qpid-broker-j   Source File: TlsResourceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static Extension createExtendedUsageExtension(final ExtendedKeyUsage extendedKeyUsage)
        throws CertificateException
{
    try
    {
        return new Extension(Extension.extendedKeyUsage, false, extendedKeyUsage.getEncoded());
    }
    catch (IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example 17
Source Project: fabric-sdk-java   Source File: TLSCertificateBuilder.java    License: 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 18
Source Project: dcos-commons   Source File: TLSArtifactsGenerator.java    License: 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 19
Source Project: keystore-explorer   Source File: X509Ext.java    License: 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 20
Source Project: nifi   Source File: CertificateUtils.java    License: 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 21
Source Project: nifi   Source File: CertificateUtils.java    License: 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 22
Source Project: nifi   Source File: OcspCertificateValidatorTest.java    License: 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 23
Source Project: ofdrw   Source File: PKCGenerate.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 签发证书
 *
 * @param p10Obj     证书请求ASN1对象
 * @param root       CA根证书
 * @param privateKey CA私钥
 * @return X509证书对象
 */
public static X509Certificate GenCert(PKCS10CertificationRequest p10Obj,
                                      Certificate root,
                                      PrivateKey privateKey)
        throws GeneralSecurityException,
        IOException,
        OperatorCreationException {
    JcaPKCS10CertificationRequest req = new JcaPKCS10CertificationRequest(p10Obj);
    // 从证书请求中获取到使用DN
    X500Name subject = req.getSubject();

    // 取得根证书的Subject,签发证书的使用者就是根证书的使用者
    X500Name issuer = new X509CertificateHolder(root.getEncoded())
            .getSubject();

    // 根据需求构造实体证书
    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(
            // 颁发者信息
            issuer
            // 证书序列号
            , BigInteger.valueOf(Instant.now().toEpochMilli())
            // 证书生效日期
            , Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant())
            // 证书失效日期
            , Date.from(LocalDateTime.now().plusYears(2).atZone(ZoneId.systemDefault()).toInstant())
            // 使用者信息
            , subject
            // 证书公钥
            , req.getPublicKey())
            // 设置密钥用法
            .addExtension(Extension.keyUsage,
                    false
                    , new X509KeyUsage(X509KeyUsage.digitalSignature
                            | X509KeyUsage.nonRepudiation
                            | X509KeyUsage.keyCertSign))
            // 设置扩展密钥用法:客户端身份认证
            .addExtension(Extension.extendedKeyUsage,
                    false,
                    new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth))
            // 基础约束,标识是否是CA证书,这里false标识为实体证书
            .addExtension(Extension.basicConstraints,
                    false,
                    new BasicConstraints(false))
            // Netscape Cert Type SSL客户端身份认证
            .addExtension(MiscObjectIdentifiers.netscapeCertType,
                    false,
                    new NetscapeCertType(NetscapeCertType.sslClient));

    // 5. 证书签名实现类
    ContentSigner sigGen = new JcaContentSignerBuilder("SM3withSM2")
            .setProvider("BC")
            .build(privateKey);

    // 6. 签发证书
    return new JcaX509CertificateConverter()
            .setProvider("BC")
            .getCertificate(certGen.build(sigGen));
}
 
Example 24
Source Project: credhub   Source File: CertificateReader.java    License: Apache License 2.0 4 votes vote down vote up
public ExtendedKeyUsage getExtendedKeyUsage() {
  return ExtendedKeyUsage.fromExtensions(certificateHolder.getExtensions());
}
 
Example 25
private void addExtKeyUsage(X509ExtensionSet extensionSet, String ekuOid) throws IOException {
	ExtendedKeyUsage eku = new ExtendedKeyUsage(
			new KeyPurposeId[] { KeyPurposeId.getInstance(new ASN1ObjectIdentifier(ekuOid)) });
	byte[] ekuEncoded = wrapInOctetString(eku.getEncoded());
	extensionSet.addExtension(X509ExtensionType.EXTENDED_KEY_USAGE.oid(), false, ekuEncoded);
}
 
Example 26
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 == TSL_SIGNING) {
			jcbTslSigning.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);
		} else {
			customExtKeyUsagesOids.add(oid);
		}
	}
	jcbCustomExtKeyUsage.setSelected(customExtKeyUsagesOids.size() > 0);
}
 
Example 27
private void okPressed() {
	if (!jcbTlsWebServerAuthentication.isSelected() && !jcbTlsWebClientAuthentication.isSelected()
			&& !jcbCodeSigning.isSelected() && !jcbEmailProtection.isSelected()
			&& !jcbIpSecurityEndSystem.isSelected() && !jcbIpSecurityTunnelTermination.isSelected()
			&& !jcbIpSecurityUser.isSelected() && !jcbTimeStamping.isSelected() && !jcbOcspStamping.isSelected()
			&& !jcbDocumentSigning.isSelected() && !jcbAdobePDFSigning.isSelected() && !jcbTslSigning.isSelected()
			&& !jcbEncryptedFileSystem.isSelected() && !jcbAnyExtendedKeyUsage.isSelected()
			&& !jcbSmartcardLogon.isSelected() && !jcbCustomExtKeyUsage.isSelected()) {
		JOptionPane.showMessageDialog(this, res.getString("DExtendedKeyUsage.ValueReq.message"), getTitle(),
				JOptionPane.WARNING_MESSAGE);
		return;
	}

	ArrayList<KeyPurposeId> keyPurposeIds = new ArrayList<>();

	if (jcbTlsWebServerAuthentication.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(SERVER_AUTH.oid())));
	}

	if (jcbTlsWebClientAuthentication.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(CLIENT_AUTH.oid())));
	}

	if (jcbCodeSigning.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(CODE_SIGNING.oid())));
	}

	if (jcbDocumentSigning.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(DOCUMENT_SIGNING.oid())));
	}

	if (jcbAdobePDFSigning.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(ADOBE_PDF_SIGNING.oid())));
	}

	if (jcbTslSigning.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(TSL_SIGNING.oid())));
	}

	if (jcbEmailProtection.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(EMAIL_PROTECTION.oid())));
	}

	if (jcbEncryptedFileSystem.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(ENCRYPTED_FILE_SYSTEM.oid())));
	}

	if (jcbIpSecurityEndSystem.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(IPSEC_END_SYSTEM.oid())));
	}

	if (jcbIpSecurityTunnelTermination.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(IPSEC_TUNNEL.oid())));
	}

	if (jcbIpSecurityUser.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(IPSEC_USER.oid())));
	}

	if (jcbTimeStamping.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(TIME_STAMPING.oid())));
	}

	if (jcbOcspStamping.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(OCSP_SIGNING.oid())));
	}

	if (jcbSmartcardLogon.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(SMARTCARD_LOGON.oid())));
	}

	if (jcbAnyExtendedKeyUsage.isSelected()) {
		keyPurposeIds.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(ANY_EXTENDED_KEY_USAGE.oid())));
	}
	if (jcbCustomExtKeyUsage.isSelected()) {
		for (ASN1ObjectIdentifier customExcKeyUsageOid : customExtKeyUsagesOids) {
			keyPurposeIds.add(KeyPurposeId.getInstance(customExcKeyUsageOid));
		}
	}
	ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(
			keyPurposeIds.toArray(new KeyPurposeId[keyPurposeIds.size()]));

	try {
		value = extendedKeyUsage.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example 28
Source Project: DeviceConnect-Android   Source File: SslUtil.java    License: MIT License 4 votes vote down vote up
/**
 * Generates a new, self-signed X509 V3 certificate for a KeyPair.
 *
 * @param  pair                      the {@link KeyPair} to be used
 * @param  name                      X.500 distinguished name
 * @param  notBefore                 not valid before this date
 * @param  notAfter                  not valid after this date
 * @param  serialNumber              serial number
 * @return                           the new certificate
 * @throws GeneralSecurityException  on error generating the certificate
 */
@SuppressWarnings("deprecation")
public static X509Certificate generateX509V3Certificate(KeyPair pair,
                                                        String name, Date notBefore, Date notAfter, BigInteger serialNumber)
        throws GeneralSecurityException {
    java.security.Security.addProvider(
            new org.bouncycastle.jce.provider.BouncyCastleProvider());
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X509Name dnName = new X509Name(name);

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setSubjectDN(dnName);   // note: same as issuer
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    // For self-signed certificates, OpenSSL 0.9.6 has specific requirements
    // about certificate and extension content.  Quoting the `man verify`:
    //
    //   In OpenSSL 0.9.6 and later all certificates whose subject name matches
    //   the issuer name of the current certificate are subject to further
    //   tests. The relevant authority key identifier components of the current
    //   certificate (if present) must match the subject key identifier (if
    //   present) and issuer and serial number of the candidate issuer, in
    //   addition the keyUsage extension of the candidate issuer (if present)
    //   must permit certificate signing.
    //
    // In the code that follows,
    //   - the KeyUsage extension permits cert signing (KeyUsage.keyCertSign);
    //   - the Authority Key Identifier extension is added, matching the
    //     subject key identifier, and using the issuer, and serial number.
    certGen.addExtension(X509Extensions.BasicConstraints, true,
            new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature
            | KeyUsage.keyEncipherment | KeyUsage.keyCertSign));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(
            KeyPurposeId.id_kp_serverAuth));
    AuthorityKeyIdentifier authIdentifier = createAuthorityKeyIdentifier(
            pair.getPublic(), dnName, serialNumber);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, true,
            authIdentifier);
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
            new SubjectKeyIdentifierStructure(pair.getPublic()));
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(
            new GeneralName(GeneralName.rfc822Name, "[email protected]")));
    // This method is deprecated, but Android Eclair does not provide the
    // generate() methods.
    X509Certificate cert = certGen.generateX509Certificate(pair.getPrivate(), SecurityUtil.getSecurityProvider());
    return cert;
}
 
Example 29
ExtKeyUsageExtension(final ExtendedKeyUsage extendedKeyUsage) {
  super(Extension.extendedKeyUsage, false, extendedKeyUsage);
}
 
Example 30
ExtKeyUsageExtension(final KeyPurposeId usage) {
  this(new ExtendedKeyUsage(usage));
}