Search in sources :

Example 16 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project robovm by robovm.

the class TestKeyStore method createCertificate.

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.
    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);
    BigInteger serial = BigInteger.valueOf(1);
    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha1WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha1WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }
    X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
    x509cg.setSubjectDN(subject);
    x509cg.setIssuerDN(issuer);
    x509cg.setNotBefore(start);
    x509cg.setNotAfter(end);
    x509cg.setPublicKey(publicKey);
    x509cg.setSignatureAlgorithm(signatureAlgorithm);
    x509cg.setSerialNumber(serial);
    if (keyUsage != 0) {
        x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    }
    for (int i = 0; i < extendedKeyUsages.size(); i++) {
        KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
        boolean critical = criticalExtendedKeyUsages.get(i);
        x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
    }
    for (GeneralName subjectAltName : subjectAltNames) {
        x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
    }
    if (privateKey instanceof ECPrivateKey) {
        /*
             * bouncycastle needs its own ECPrivateKey implementation
             */
        KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        privateKey = kf.generatePrivate(ks);
    }
    X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
    if (StandardNames.IS_RI) {
        /*
             * The RI can't handle the BC EC signature algorithm
             * string of "ECDSA", since it expects "...WITHEC...",
             * so convert from BC to RI X509Certificate
             * implementation via bytes.
             */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) NameConstraints(com.android.org.bouncycastle.asn1.x509.NameConstraints) KeyPurposeId(com.android.org.bouncycastle.asn1.x509.KeyPurposeId) ExtendedKeyUsage(com.android.org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(com.android.org.bouncycastle.asn1.x509.KeyUsage) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString) CertificateFactory(java.security.cert.CertificateFactory) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) GeneralNames(com.android.org.bouncycastle.asn1.x509.GeneralNames) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BigInteger(java.math.BigInteger) GeneralName(com.android.org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(com.android.org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(com.android.org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 17 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project XobotOS by xamarin.

the class X509CertificateObject method toString.

public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = System.getProperty("line.separator");
    buf.append("  [0]         Version: ").append(this.getVersion()).append(nl);
    buf.append("         SerialNumber: ").append(this.getSerialNumber()).append(nl);
    buf.append("             IssuerDN: ").append(this.getIssuerDN()).append(nl);
    buf.append("           Start Date: ").append(this.getNotBefore()).append(nl);
    buf.append("           Final Date: ").append(this.getNotAfter()).append(nl);
    buf.append("            SubjectDN: ").append(this.getSubjectDN()).append(nl);
    buf.append("           Public Key: ").append(this.getPublicKey()).append(nl);
    buf.append("  Signature Algorithm: ").append(this.getSigAlgName()).append(nl);
    byte[] sig = this.getSignature();
    buf.append("            Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl);
    for (int i = 20; i < sig.length; i += 20) {
        if (i < sig.length - 20) {
            buf.append("                       ").append(new String(Hex.encode(sig, i, 20))).append(nl);
        } else {
            buf.append("                       ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl);
        }
    }
    X509Extensions extensions = c.getTBSCertificate().getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        if (e.hasMoreElements()) {
            buf.append("       Extensions: \n");
        }
        while (e.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (ext.getValue() != null) {
                byte[] octs = ext.getValue().getOctets();
                ASN1InputStream dIn = new ASN1InputStream(octs);
                buf.append("                       critical(").append(ext.isCritical()).append(") ");
                try {
                    if (oid.equals(X509Extensions.BasicConstraints)) {
                        buf.append(new BasicConstraints((ASN1Sequence) dIn.readObject())).append(nl);
                    } else if (oid.equals(X509Extensions.KeyUsage)) {
                        buf.append(new KeyUsage((DERBitString) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) {
                        buf.append(new NetscapeCertType((DERBitString) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) {
                        buf.append(new NetscapeRevocationURL((DERIA5String) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) {
                        buf.append(new VerisignCzagExtension((DERIA5String) dIn.readObject())).append(nl);
                    } else {
                        buf.append(oid.getId());
                        buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
                    //buf.append(" value = ").append("*****").append(nl);
                    }
                } catch (Exception ex) {
                    buf.append(oid.getId());
                    //     buf.append(" value = ").append(new String(Hex.encode(ext.getValue().getOctets()))).append(nl);
                    buf.append(" value = ").append("*****").append(nl);
                }
            } else {
                buf.append(nl);
            }
        }
    }
    return buf.toString();
}
Also used : VerisignCzagExtension(org.bouncycastle.asn1.misc.VerisignCzagExtension) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) X509Extension(org.bouncycastle.asn1.x509.X509Extension) NetscapeRevocationURL(org.bouncycastle.asn1.misc.NetscapeRevocationURL) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERBitString(org.bouncycastle.asn1.DERBitString) DERBitString(org.bouncycastle.asn1.DERBitString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) CertificateExpiredException(java.security.cert.CertificateExpiredException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) DERIA5String(org.bouncycastle.asn1.DERIA5String) NetscapeCertType(org.bouncycastle.asn1.misc.NetscapeCertType) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 18 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project nifi by apache.

the class CertificateUtils method generateSelfSignedX509Certificate.

/**
 * 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);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertIOException(org.bouncycastle.cert.CertIOException) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 19 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project nifi by apache.

the class OcspCertificateValidatorTest method generateCertificate.

/**
 * 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);
}
Also used : PrivateKey(java.security.PrivateKey) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) Vector(java.util.Vector) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 20 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project xipki by xipki.

the class ExtensionsChecker method checkExtensionExtendedKeyUsage.

// method checkExtensionKeyUsage
private void checkExtensionExtendedKeyUsage(StringBuilder failureMsg, byte[] extensionValue, Extensions requestedExtensions, ExtensionControl extControl) {
    Set<String> isUsages = new HashSet<>();
    org.bouncycastle.asn1.x509.ExtendedKeyUsage keyusage = org.bouncycastle.asn1.x509.ExtendedKeyUsage.getInstance(extensionValue);
    KeyPurposeId[] usages = keyusage.getUsages();
    if (usages != null) {
        for (KeyPurposeId usage : usages) {
            isUsages.add(usage.getId());
        }
    }
    Set<String> expectedUsages = new HashSet<>();
    Set<ExtKeyUsageControl> requiredExtKeyusage = getExtKeyusage(true);
    if (requiredExtKeyusage != null) {
        for (ExtKeyUsageControl usage : requiredExtKeyusage) {
            expectedUsages.add(usage.getExtKeyUsage().getId());
        }
    }
    Set<ExtKeyUsageControl> optionalExtKeyusage = getExtKeyusage(false);
    if (requestedExtensions != null && extControl.isRequest() && CollectionUtil.isNonEmpty(optionalExtKeyusage)) {
        Extension extension = requestedExtensions.getExtension(Extension.extendedKeyUsage);
        if (extension != null) {
            org.bouncycastle.asn1.x509.ExtendedKeyUsage reqKeyUsage = org.bouncycastle.asn1.x509.ExtendedKeyUsage.getInstance(extension.getParsedValue());
            for (ExtKeyUsageControl k : optionalExtKeyusage) {
                if (reqKeyUsage.hasKeyPurposeId(KeyPurposeId.getInstance(k.getExtKeyUsage()))) {
                    expectedUsages.add(k.getExtKeyUsage().getId());
                }
            }
        }
    }
    if (CollectionUtil.isEmpty(expectedUsages)) {
        byte[] constantExtValue = getConstantExtensionValue(Extension.keyUsage);
        if (constantExtValue != null) {
            expectedUsages = getExtKeyUsage(constantExtValue);
        }
    }
    Set<String> diffs = strInBnotInA(expectedUsages, isUsages);
    if (CollectionUtil.isNonEmpty(diffs)) {
        failureMsg.append("usages ").append(diffs.toString()).append(" are present but not expected; ");
    }
    diffs = strInBnotInA(isUsages, expectedUsages);
    if (CollectionUtil.isNonEmpty(diffs)) {
        failureMsg.append("usages ").append(diffs.toString()).append(" are absent but are required; ");
    }
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) ExtKeyUsageControl(org.xipki.ca.api.profile.x509.ExtKeyUsageControl) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) ASN1String(org.bouncycastle.asn1.ASN1String) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) QaDirectoryString(org.xipki.ca.qa.internal.QaDirectoryString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERT61String(org.bouncycastle.asn1.DERT61String) HashSet(java.util.HashSet)

Aggregations

KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)49 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)40 X500Name (org.bouncycastle.asn1.x500.X500Name)33 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)30 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)30 X509Certificate (java.security.cert.X509Certificate)29 Date (java.util.Date)29 ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)29 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)27 ContentSigner (org.bouncycastle.operator.ContentSigner)24 BigInteger (java.math.BigInteger)23 GeneralName (org.bouncycastle.asn1.x509.GeneralName)21 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)21 IOException (java.io.IOException)20 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)19 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)16 HashSet (java.util.HashSet)15 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)15 KeyPurposeId (org.bouncycastle.asn1.x509.KeyPurposeId)15 Extension (org.bouncycastle.asn1.x509.Extension)14