Search in sources :

Example 6 with KeyUsage

use of com.android.org.bouncycastle.asn1.x509.KeyUsage in project nhin-d by DirectProject.

the class KeyUsageExtensionField method injectReferenceValue.

/**
	 * {@inheritDoc}
	 */
@Override
public void injectReferenceValue(X509Certificate value) throws PolicyProcessException {
    this.certificate = value;
    final DERObject exValue = getExtensionValue(value);
    if (exValue == null) {
        if (isRequired())
            throw new PolicyRequiredException("Extention " + getExtentionIdentifier().getDisplay() + " is marked as required by is not present.");
        else {
            this.policyValue = PolicyValueFactory.getInstance(0);
            return;
        }
    }
    final KeyUsage keyUsage = new KeyUsage((DERBitString) exValue);
    final byte[] data = keyUsage.getBytes();
    final int intValue = (data.length == 1) ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff);
    this.policyValue = PolicyValueFactory.getInstance(intValue);
}
Also used : PolicyRequiredException(org.nhindirect.policy.PolicyRequiredException) DERObject(org.bouncycastle.asn1.DERObject) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage)

Example 7 with KeyUsage

use of com.android.org.bouncycastle.asn1.x509.KeyUsage in project poi by apache.

the class TestSignatureInfo method initKeyPair.

private void initKeyPair(String alias, String subjectDN) throws Exception {
    final char[] password = "test".toCharArray();
    File file = new File("build/test.pfx");
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    if (file.exists()) {
        FileInputStream fis = new FileInputStream(file);
        keystore.load(fis, password);
        fis.close();
    } else {
        keystore.load(null, password);
    }
    if (keystore.isKeyEntry(alias)) {
        Key key = keystore.getKey(alias, password);
        x509 = (X509Certificate) keystore.getCertificate(alias);
        keyPair = new KeyPair(x509.getPublicKey(), (PrivateKey) key);
    } else {
        keyPair = PkiTestUtils.generateKeyPair();
        Date notBefore = cal.getTime();
        Calendar cal2 = (Calendar) cal.clone();
        cal2.add(Calendar.YEAR, 1);
        Date notAfter = cal2.getTime();
        KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature);
        x509 = PkiTestUtils.generateCertificate(keyPair.getPublic(), subjectDN, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, keyUsage);
        keystore.setKeyEntry(alias, keyPair.getPrivate(), password, new Certificate[] { x509 });
        FileOutputStream fos = new FileOutputStream(file);
        keystore.store(fos, password);
        fos.close();
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) Calendar(java.util.Calendar) FileOutputStream(java.io.FileOutputStream) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) File(java.io.File) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) Key(java.security.Key) PrivateKey(java.security.PrivateKey) Date(java.util.Date)

Example 8 with KeyUsage

use of com.android.org.bouncycastle.asn1.x509.KeyUsage in project robovm by robovm.

the class RFC3280CertPathUtilities method processCRLF.

/**
     * Obtain and validate the certification path for the complete CRL issuer.
     * If a key usage extension is present in the CRL issuer's certificate,
     * verify that the cRLSign bit is set.
     *
     * @param crl                CRL which contains revocation information for the certificate
     *                           <code>cert</code>.
     * @param cert               The attribute certificate or certificate to check if it is
     *                           revoked.
     * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
     * @param defaultCRLSignKey  The public key of the issuer certificate
     *                           <code>defaultCRLSignCert</code>.
     * @param paramsPKIX         paramsPKIX PKIX parameters.
     * @param certPathCerts      The certificates on the certification path.
     * @return A <code>Set</code> with all keys of possible CRL issuer
     *         certificates.
     * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
     *                            some error occurs.
     */
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
    // (f)
    // get issuer from CRL
    X509CertStoreSelector selector = new X509CertStoreSelector();
    try {
        byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
        selector.setSubject(issuerPrincipal);
    } catch (IOException e) {
        throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
    }
    // get CRL signing certs
    Collection coll;
    try {
        coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
    } catch (AnnotatedException e) {
        throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
    }
    coll.add(defaultCRLSignCert);
    Iterator cert_it = coll.iterator();
    List validCerts = new ArrayList();
    List validKeys = new ArrayList();
    while (cert_it.hasNext()) {
        X509Certificate signingCert = (X509Certificate) cert_it.next();
        /*
             * CA of the certificate, for which this CRL is checked, has also
             * signed CRL, so skip the path validation, because is already done
             */
        if (signingCert.equals(defaultCRLSignCert)) {
            validCerts.add(signingCert);
            validKeys.add(defaultCRLSignKey);
            continue;
        }
        try {
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
            selector = new X509CertStoreSelector();
            selector.setCertificate(signingCert);
            ExtendedPKIXParameters temp = (ExtendedPKIXParameters) paramsPKIX.clone();
            temp.setTargetCertConstraints(selector);
            ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters.getInstance(temp);
            /*
                 * if signingCert is placed not higher on the cert path a
                 * dependency loop results. CRL for cert is checked, but
                 * signingCert is needed for checking the CRL which is dependent
                 * on checking cert because it is higher in the cert path and so
                 * signing signingCert transitively. so, revocation is disabled,
                 * forgery attacks of the CRL are detected in this outer loop
                 * for all other it must be enabled to prevent forgery attacks
                 */
            if (certPathCerts.contains(signingCert)) {
                params.setRevocationEnabled(false);
            } else {
                params.setRevocationEnabled(true);
            }
            List certs = builder.build(params).getCertPath().getCertificates();
            validCerts.add(signingCert);
            validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
        } catch (CertPathBuilderException e) {
            throw new AnnotatedException("Internal error.", e);
        } catch (CertPathValidatorException e) {
            throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    Set checkKeys = new HashSet();
    AnnotatedException lastException = null;
    for (int i = 0; i < validCerts.size(); i++) {
        X509Certificate signCert = (X509Certificate) validCerts.get(i);
        boolean[] keyusage = signCert.getKeyUsage();
        if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
            lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
        } else {
            checkKeys.add(validKeys.get(i));
        }
    }
    if (checkKeys.isEmpty() && lastException == null) {
        throw new AnnotatedException("Cannot find a valid issuer certificate.");
    }
    if (checkKeys.isEmpty() && lastException != null) {
        throw lastException;
    }
    return checkKeys;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ExtendedPKIXBuilderParameters(org.bouncycastle.x509.ExtendedPKIXBuilderParameters) X509CertStoreSelector(org.bouncycastle.x509.X509CertStoreSelector) ArrayList(java.util.ArrayList) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) CertPathBuilder(java.security.cert.CertPathBuilder) HashSet(java.util.HashSet)

Example 9 with KeyUsage

use of com.android.org.bouncycastle.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 10 with KeyUsage

use of com.android.org.bouncycastle.asn1.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)

Aggregations

X509Certificate (java.security.cert.X509Certificate)10 KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)10 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)8 Date (java.util.Date)6 IOException (java.io.IOException)5 KeyPair (java.security.KeyPair)5 KeyStore (java.security.KeyStore)5 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)5 File (java.io.File)4 X500Name (org.bouncycastle.asn1.x500.X500Name)4 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)4 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)4 BigInteger (java.math.BigInteger)3 GeneralSecurityException (java.security.GeneralSecurityException)3 SecureRandom (java.security.SecureRandom)3 CertificateExpiredException (java.security.cert.CertificateExpiredException)3 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)3 GeneralName (org.bouncycastle.asn1.x509.GeneralName)3 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)3 SubjectKeyIdentifier (org.bouncycastle.asn1.x509.SubjectKeyIdentifier)3