Search in sources :

Example 11 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project certmgr by hdecarne.

the class KeyUsageController method init.

/**
 * Initialize the dialog with existing extension data.
 *
 * @param data The extension data to use.
 * @param expertMode Whether to run in expert mode ({@code true}) or not ({@code false}).
 * @return This controller.
 */
public KeyUsageController init(KeyUsageExtensionData data, boolean expertMode) {
    init(expertMode);
    this.ctlCritical.setSelected(data.getCritical());
    if (data.hasUsage(KeyUsage.ANY)) {
        this.ctlAnyUsage.setSelected(true);
    } else {
        for (KeyUsage usage : data) {
            this.ctlUsages.getSelectionModel().select(usage);
        }
    }
    return this;
}
Also used : KeyUsage(de.carne.certmgr.certs.x509.KeyUsage)

Example 12 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project candlepin by candlepin.

the class BouncyCastlePKIUtility method createX509Certificate.

@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {
    X509Certificate caCert = reader.getCACert();
    byte[] publicKeyEncoded = clientKeyPair.getPublic().getEncoded();
    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()), serialNumber, startDate, endDate, new X500Name(dn), SubjectPublicKeyInfo.getInstance(publicKeyEncoded));
    // set key usage - required for proper x509 function
    KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);
    // add SSL extensions - required for proper x509 function
    NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);
    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, certType);
    certGen.addExtension(Extension.keyUsage, false, keyUsage);
    JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
    AuthorityKeyIdentifier aki = extensionUtil.createAuthorityKeyIdentifier(caCert);
    certGen.addExtension(Extension.authorityKeyIdentifier, false, aki.getEncoded());
    certGen.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
    certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    // Add an additional alternative name if provided.
    if (alternateName != null) {
        /*
             Why add the certificate subject again as an alternative name?  RFC 6125 Section 6.4.4
             stipulates that if SANs are provided, a validator MUST use them instead of the certificate
             subject.  If no SANs are present, the RFC allows the validator to use the subject field.  So,
             if we do have an SAN to add, we need to add the subject field again as an SAN.

             See http://stackoverflow.com/questions/5935369 and
             https://tools.ietf.org/html/rfc6125#section-6.4.4 and

             NB: These extensions should *not* be marked critical since the subject field is not empty.
            */
        GeneralName subject = new GeneralName(GeneralName.directoryName, dn);
        GeneralName name = new GeneralName(GeneralName.directoryName, "CN=" + alternateName);
        ASN1Encodable[] altNameArray = { subject, name };
        GeneralNames altNames = GeneralNames.getInstance(new DERSequence(altNameArray));
        certGen.addExtension(Extension.subjectAlternativeName, false, altNames);
    }
    if (extensions != null) {
        for (X509ExtensionWrapper wrapper : extensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            String value = wrapper.getValue() == null ? "" : wrapper.getValue();
            certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DERUTF8String(value));
        }
    }
    if (byteExtensions != null) {
        for (X509ByteExtensionWrapper wrapper : byteExtensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
            certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DEROctetString(value));
        }
    }
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNATURE_ALGO).setProvider(BC_PROVIDER);
    ContentSigner signer;
    try {
        signer = builder.build(reader.getCaKey());
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
    // Generate the certificate
    return new JcaX509CertificateConverter().getCertificate(certGen.build(signer));
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERSequence(org.bouncycastle.asn1.DERSequence) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) NetscapeCertType(org.bouncycastle.asn1.misc.NetscapeCertType) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509ByteExtensionWrapper(org.candlepin.pki.X509ByteExtensionWrapper) X509ExtensionWrapper(org.candlepin.pki.X509ExtensionWrapper) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 13 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project helios by spotify.

the class X509CertificateFactory method generate.

private CertificateAndPrivateKey generate(final AgentProxy agentProxy, final Identity identity, final String username) {
    final UUID uuid = new UUID();
    final Calendar calendar = Calendar.getInstance();
    final X500Name issuerdn = new X500Name("C=US,O=Spotify,CN=helios-client");
    final X500Name subjectdn = new X500NameBuilder().addRDN(BCStyle.UID, username).build();
    calendar.add(Calendar.MILLISECOND, -validBeforeMilliseconds);
    final Date notBefore = calendar.getTime();
    calendar.add(Calendar.MILLISECOND, validBeforeMilliseconds + validAfterMilliseconds);
    final Date notAfter = calendar.getTime();
    // Reuse the UUID time as a SN
    final BigInteger serialNumber = BigInteger.valueOf(uuid.getTime()).abs();
    try {
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
        final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerdn, serialNumber, notBefore, notAfter, subjectdn, subjectPublicKeyInfo);
        final DigestCalculator digestCalculator = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);
        final SubjectKeyIdentifier keyId = utils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
        final String keyIdHex = KEY_ID_ENCODING.encode(keyId.getKeyIdentifier());
        log.info("generating an X509 certificate for {} with key ID={} and identity={}", username, keyIdHex, identity.getComment());
        builder.addExtension(Extension.subjectKeyIdentifier, false, keyId);
        builder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
        builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
        final X509CertificateHolder holder = builder.build(new SshAgentContentSigner(agentProxy, identity));
        final X509Certificate certificate = CERTIFICATE_CONVERTER.getCertificate(holder);
        log.debug("generated certificate:\n{}", asPemString(certificate));
        return new CertificateAndPrivateKey(certificate, keyPair.getPrivate());
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) KeyPair(java.security.KeyPair) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) Calendar(java.util.Calendar) DigestCalculator(org.bouncycastle.operator.DigestCalculator) SecureRandom(java.security.SecureRandom) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyPairGenerator(java.security.KeyPairGenerator) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) UUID(com.eaio.uuid.UUID) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 14 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project zaproxy by zaproxy.

the class SslCertificateUtils method createRootCA.

/**
	 * Creates a new Root CA certificate and returns private and public key as
	 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
	 *
	 * @return
	 * @throws NoSuchAlgorithmException If no providers are found
	 * for 'RSA' key pair generator
	 * or 'SHA1PRNG' Secure random number generator
	 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
	 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));
    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Security.addProvider(new BouncyCastleProvider());
    Random rnd = new Random();
    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");
    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);
    KeyStore ks = null;
    try {
        certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
        KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage };
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));
        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}
Also used : KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) KeyPairGenerator(java.security.KeyPairGenerator) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Random(java.util.Random) SecureRandom(java.security.SecureRandom) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 15 with KeyUsage

use of de.carne.certmgr.certs.x509.KeyUsage in project nhin-d by DirectProject.

the class PKCS11Commands method createCSR.

@Command(name = "CreateCSR", usage = CREATE_CSR)
public void createCSR(String[] args) {
    final String alias = StringArrayUtil.getRequiredValue(args, 0);
    final String commonName = StringArrayUtil.getRequiredValue(args, 1);
    final String subjectAltName = StringArrayUtil.getRequiredValue(args, 2);
    final String keyUsage = StringArrayUtil.getRequiredValue(args, 3);
    // make sure we have a valid keyUsage
    if (!(keyUsage.compareToIgnoreCase("DigitalSignature") == 0 || keyUsage.compareToIgnoreCase("KeyEncipherment") == 0 || keyUsage.compareToIgnoreCase("DualUse") == 0)) {
        System.out.println("Invalid key usage.");
        return;
    }
    final Vector<String> additionalRDNFields = new Vector<String>();
    int cnt = 4;
    String rdnField;
    do {
        rdnField = StringArrayUtil.getOptionalValue(args, cnt++, "");
        if (!StringUtils.isEmpty(rdnField))
            additionalRDNFields.add(rdnField);
    } while (!StringUtils.isEmpty(rdnField));
    try {
        final KeyStore ks = mgr.getKS();
        if (!ks.containsAlias(alias)) {
            System.out.println("Entry with key name " + alias + " does not exist.");
            return;
        }
        final X509Certificate storedCert = (X509Certificate) ks.getCertificate(alias);
        if (storedCert == null) {
            System.out.println("Key name " + alias + " does not contain a certificate that can be exported.  This key may not be an RSA key pair.");
            return;
        }
        final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
        if (privKey == null) {
            System.out.println("Failed to object private key.  This key may not be an RSA key pair.");
            return;
        }
        // create the CSR
        //  create the extensions that we want
        final X509ExtensionsGenerator extsGen = new X509ExtensionsGenerator();
        // Key Usage
        int usage;
        if (keyUsage.compareToIgnoreCase("KeyEncipherment") == 0)
            usage = KeyUsage.keyEncipherment;
        else if (keyUsage.compareToIgnoreCase("DigitalSignature") == 0)
            usage = KeyUsage.digitalSignature;
        else
            usage = KeyUsage.keyEncipherment | KeyUsage.digitalSignature;
        extsGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(usage));
        // Subject Alt Name
        int nameType = subjectAltName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
        final GeneralNames altName = new GeneralNames(new GeneralName(nameType, subjectAltName));
        extsGen.addExtension(X509Extensions.SubjectAlternativeName, false, altName);
        // Extended Key Usage
        final Vector<KeyPurposeId> purposes = new Vector<KeyPurposeId>();
        purposes.add(KeyPurposeId.id_kp_emailProtection);
        extsGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(purposes));
        // Basic constraint
        final BasicConstraints bc = new BasicConstraints(false);
        extsGen.addExtension(X509Extensions.BasicConstraints, true, bc);
        // create the extension requests
        final X509Extensions exts = extsGen.generate();
        final ASN1EncodableVector attributes = new ASN1EncodableVector();
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(exts.toASN1Object()));
        attributes.add(attribute);
        final DERSet requestedAttributes = new DERSet(attributes);
        // create the DN
        final StringBuilder dnBuilder = new StringBuilder("CN=").append(commonName);
        for (String field : additionalRDNFields) dnBuilder.append(",").append(field);
        final X500Principal subjectPrin = new X500Principal(dnBuilder.toString());
        final X509Principal xName = new X509Principal(true, subjectPrin.getName());
        // create the CSR
        final PKCS10CertificationRequest request = new PKCS10CertificationRequest("SHA256WITHRSA", xName, storedCert.getPublicKey(), requestedAttributes, privKey, ks.getProvider().getName());
        final byte[] encodedCSR = request.getEncoded();
        final String csrString = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + Base64.encodeBase64String(encodedCSR) + "-----END CERTIFICATE REQUEST-----";
        final File csrFile = new File(alias + "-CSR.pem");
        FileUtils.writeStringToFile(csrFile, csrString);
        System.out.println("CSR written to " + csrFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to create CSR : " + e.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) Attribute(org.bouncycastle.asn1.x509.Attribute) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERSet(org.bouncycastle.asn1.DERSet) X509Principal(org.bouncycastle.jce.X509Principal) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) X509ExtensionsGenerator(org.bouncycastle.asn1.x509.X509ExtensionsGenerator) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) File(java.io.File) Command(org.nhindirect.common.tooling.Command)

Aggregations

KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)22 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)14 Date (java.util.Date)12 X500Name (org.bouncycastle.asn1.x500.X500Name)12 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)12 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)12 X509Certificate (java.security.cert.X509Certificate)11 ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)11 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)11 ContentSigner (org.bouncycastle.operator.ContentSigner)10 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)9 KeyPurposeId (org.bouncycastle.asn1.x509.KeyPurposeId)8 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)8 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)7 KeyPair (java.security.KeyPair)6 KeyStore (java.security.KeyStore)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 CertificateException (java.security.cert.CertificateException)6 IOException (java.io.IOException)5 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)5