Java Code Examples for java.security.cert.X509Certificate#getKeyUsage()

The following examples show how to use java.security.cert.X509Certificate#getKeyUsage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: X509KeySelector.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Searches the specified keystore for a certificate that matches the
 * specified X509Certificate and contains a public key that is compatible
 * with the specified SignatureMethod.
 *
 * @return a KeySelectorResult containing the cert's public key if there
 *   is a match; otherwise null
 */
private KeySelectorResult certSelect(X509Certificate xcert,
    SignatureMethod sm) throws KeyStoreException {
    // skip non-signer certs
    boolean[] keyUsage = xcert.getKeyUsage();
    if (keyUsage != null && keyUsage[0] == false) {
        return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
        PublicKey pk = ks.getCertificate(alias).getPublicKey();
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    return null;
}
 
Example 2
Source File: X509KeySelector.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Searches the specified keystore for a certificate that matches the
 * specified X509Certificate and contains a public key that is compatible
 * with the specified SignatureMethod.
 *
 * @return a KeySelectorResult containing the cert's public key if there
 *   is a match; otherwise null
 */
private KeySelectorResult certSelect(X509Certificate xcert,
    SignatureMethod sm) throws KeyStoreException {
    // skip non-signer certs
    boolean[] keyUsage = xcert.getKeyUsage();
    if (keyUsage != null && keyUsage[0] == false) {
        return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
        PublicKey pk = ks.getCertificate(alias).getPublicKey();
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    return null;
}
 
Example 3
Source File: X509KeySelector.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Searches the specified keystore for a certificate that matches the
 * specified X509Certificate and contains a public key that is compatible
 * with the specified SignatureMethod.
 *
 * @return a KeySelectorResult containing the cert's public key if there
 *   is a match; otherwise null
 */
private KeySelectorResult certSelect(X509Certificate xcert,
    SignatureMethod sm) throws KeyStoreException {
    // skip non-signer certs
    boolean[] keyUsage = xcert.getKeyUsage();
    if (keyUsage != null && keyUsage[0] == false) {
        return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
        PublicKey pk = ks.getCertificate(alias).getPublicKey();
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    return null;
}
 
Example 4
Source File: X509KeySelector.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Searches the specified keystore for a certificate that matches the
 * specified X509Certificate and contains a public key that is compatible
 * with the specified SignatureMethod.
 *
 * @return a KeySelectorResult containing the cert's public key if there
 *   is a match; otherwise null
 */
private KeySelectorResult certSelect(X509Certificate xcert,
    SignatureMethod sm) throws KeyStoreException {
    // skip non-signer certs
    boolean[] keyUsage = xcert.getKeyUsage();
    if (keyUsage != null && keyUsage[0] == false) {
        return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
        PublicKey pk = ks.getCertificate(alias).getPublicKey();
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    return null;
}
 
Example 5
Source File: X509KeySelector.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Searches the specified keystore for a certificate that matches the
 * specified X509Certificate and contains a public key that is compatible
 * with the specified SignatureMethod.
 *
 * @return a KeySelectorResult containing the cert's public key if there
 *   is a match; otherwise null
 */
private KeySelectorResult certSelect(X509Certificate xcert,
    SignatureMethod sm) throws KeyStoreException {
    // skip non-signer certs
    boolean[] keyUsage = xcert.getKeyUsage();
    if (keyUsage != null && keyUsage[0] == false) {
        return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
        PublicKey pk = ks.getCertificate(alias).getPublicKey();
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    return null;
}
 
Example 6
Source File: X509KeySelector.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Searches the specified keystore for a certificate that matches the
 * specified X509Certificate and contains a public key that is compatible
 * with the specified SignatureMethod.
 *
 * @return a KeySelectorResult containing the cert's public key if there
 *   is a match; otherwise null
 */
private KeySelectorResult certSelect(X509Certificate xcert,
    SignatureMethod sm) throws KeyStoreException {
    // skip non-signer certs
    boolean[] keyUsage = xcert.getKeyUsage();
    if (keyUsage != null && keyUsage[0] == false) {
        return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
        PublicKey pk = ks.getCertificate(alias).getPublicKey();
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    return null;
}
 
Example 7
Source File: X509KeySelector.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Searches the specified keystore for a certificate that matches the
 * specified X509Certificate and contains a public key that is compatible
 * with the specified SignatureMethod.
 *
 * @return a KeySelectorResult containing the cert's public key if there
 *         is a match; otherwise null
 */
private KeySelectorResult certSelect(X509Certificate xcert,
                                     SignatureMethod sm) throws KeyStoreException {
    // skip non-signer certs
    boolean[] keyUsage = xcert.getKeyUsage();
    if (!keyUsage[0]) {
        return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
        PublicKey pk = ks.getCertificate(alias).getPublicKey();
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    return null;
}
 
Example 8
Source File: X509CredentialsAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
private boolean isValidKeyUsage(final X509Certificate certificate) {
    logger.debug("Checking certificate keyUsage extension");

    /*
     * KeyUsage ::= BIT STRING { digitalSignature (0), nonRepudiation (1),
     * keyEncipherment (2), dataEncipherment (3), keyAgreement (4),
     * keyCertSign (5), cRLSign (6), encipherOnly (7), decipherOnly (8) }
     */
    final boolean[] keyUsage = certificate.getKeyUsage();
    if (keyUsage == null) {
        logger.warn("Configuration specifies checkKeyUsage but keyUsage extension not found in certificate.");
        return !this.requireKeyUsage;
    }

    final boolean valid;
    if (isCritical(certificate, KEY_USAGE_OID) || this.requireKeyUsage) {
        logger.debug("KeyUsage extension is marked critical or required by configuration.");
        valid = keyUsage[0];
    } else {
        logger.debug(
           "KeyUsage digitalSignature=%s, Returning true since keyUsage validation not required by configuration.");
        valid = true;
    }
    return valid;
}
 
Example 9
Source File: X509CredentialsAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Checks if is valid key usage. <p>
 * KeyUsage ::= BIT STRING { digitalSignature (0), nonRepudiation (1),
 * keyEncipherment (2), dataEncipherment (3), keyAgreement (4),
 * keyCertSign (5), cRLSign (6), encipherOnly (7), decipherOnly (8) }
 *          
 * @param certificate the certificate
 * @return true, if  valid key usage
 */
private boolean isValidKeyUsage(final X509Certificate certificate) {
    logger.debug("Checking certificate keyUsage extension");
    final boolean[] keyUsage = certificate.getKeyUsage();
    if (keyUsage == null) {
        logger.warn("Configuration specifies checkKeyUsage but keyUsage extension not found in certificate.");
        return !this.requireKeyUsage;
    }

    final boolean valid;
    if (isCritical(certificate, KEY_USAGE_OID) || this.requireKeyUsage) {
        logger.debug("KeyUsage extension is marked critical or required by configuration.");
        valid = keyUsage[0];
    } else {
        logger.debug(
           "KeyUsage digitalSignature=%s, Returning true since keyUsage validation not required by configuration.");
        valid = true;
    }
    return valid;
}
 
Example 10
Source File: Signature.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static PublicKey getPublicKeyFromCert(Certificate cert)
        throws InvalidKeyException {
    // If the certificate is of type X509Certificate,
    // we should check whether it has a Key Usage
    // extension marked as critical.
    //if (cert instanceof java.security.cert.X509Certificate) {
    if (cert instanceof X509Certificate) {
        // Check whether the cert has a key usage extension
        // marked as a critical extension.
        // The OID for KeyUsage extension is 2.5.29.15.
        X509Certificate c = (X509Certificate)cert;
        Set<String> critSet = c.getCriticalExtensionOIDs();

        if (critSet != null && !critSet.isEmpty()
            && critSet.contains("2.5.29.15")) {
            boolean[] keyUsageInfo = c.getKeyUsage();
            // keyUsageInfo[0] is for digitalSignature.
            if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
                throw new InvalidKeyException("Wrong key usage");
        }
    }
    return cert.getPublicKey();
}
 
Example 11
Source File: RFC3280CertPathUtilities.java    From ripple-lib-java with ISC License 6 votes vote down vote up
protected static void prepareNextCertN(
    CertPath certPath,
    int index)
    throws CertPathValidatorException
{
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate)certs.get(index);

    //
    // (n)
    //
    boolean[] _usage = cert.getKeyUsage();

    if ((_usage != null) && !_usage[RFC3280CertPathUtilities.KEY_CERT_SIGN])
    {
        throw new ExtCertPathValidatorException(
            "Issuer certificate keyusage extension is critical and does not permit key signing.", null,
            certPath, index);
    }
}
 
Example 12
Source File: X509KeySelector.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Searches the specified keystore for a certificate that matches the
 * specified X509Certificate and contains a public key that is compatible
 * with the specified SignatureMethod.
 *
 * @return a KeySelectorResult containing the cert's public key if there
 *   is a match; otherwise null
 */
private KeySelectorResult certSelect(X509Certificate xcert,
    SignatureMethod sm) throws KeyStoreException {
    // skip non-signer certs
    boolean[] keyUsage = xcert.getKeyUsage();
    if (keyUsage != null && keyUsage[0] == false) {
        return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
        PublicKey pk = ks.getCertificate(alias).getPublicKey();
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    return null;
}
 
Example 13
Source File: CertificateModel.java    From Spark with Apache License 2.0 6 votes vote down vote up
private String keyUsageExtractor(X509Certificate cert){
	String value;
	value = Res.getString("cert.extension.extended.usage.digital.signature") + ": " + cert.getKeyUsage()[0]
			+ "\n";
	value += Res.getString("cert.extension.extended.usage.non.repudiation") + ": " + cert.getKeyUsage()[1]
			+ "\n";
	value += Res.getString("cert.extension.extended.usage.key.encipherment") + ": " + cert.getKeyUsage()[2]
			+ "\n";
	value += Res.getString("cert.extension.extended.usage.data.encipherment") + ": " + cert.getKeyUsage()[3]
			+ "\n";
	value += Res.getString("cert.extension.extended.usage.key.agreement") + ": " + cert.getKeyUsage()[4]
			+ "\n";
	value += Res.getString("cert.extension.extended.usage.key.cert.sign") + ": " + cert.getKeyUsage()[5]
			+ "\n";
	value += Res.getString("cert.extension.extended.usage.crl.sign") + ": " + cert.getKeyUsage()[6] 
			+ "\n";
	value += Res.getString("cert.extension.extended.usage.encipher.only") + ": " + cert.getKeyUsage()[7]
			+ "\n";
	value += Res.getString("cert.extension.extended.usage.decipher.only") + ": " + cert.getKeyUsage()[8];

	return value;
}
 
Example 14
Source File: CertificateValidationUtil.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
public static void validateApplicationCertificateUsage(X509Certificate certificate) throws UaException {
    Set<String> criticalExtensions = certificate.getCriticalExtensionOIDs();
    if (criticalExtensions == null) criticalExtensions = new HashSet<>();

    if (criticalExtensions.contains(KEY_USAGE_OID)) {
        boolean[] keyUsage = certificate.getKeyUsage();
        boolean digitalSignature = keyUsage[0];
        boolean nonRepudiation = keyUsage[1];
        boolean keyEncipherment = keyUsage[2];
        boolean dataEncipherment = keyUsage[3];

        if (!digitalSignature) {
            throw new UaException(StatusCodes.Bad_CertificateUseNotAllowed,
                    "required KeyUsage 'digitalSignature' not found");
        }

        if (!nonRepudiation) {
            throw new UaException(StatusCodes.Bad_CertificateUseNotAllowed,
                    "required KeyUsage 'nonRepudiation' not found");
        }

        if (!keyEncipherment) {
            throw new UaException(StatusCodes.Bad_CertificateUseNotAllowed,
                    "required KeyUsage 'keyEncipherment' not found");
        }

        if (!dataEncipherment) {
            throw new UaException(StatusCodes.Bad_CertificateUseNotAllowed,
                    "required KeyUsage 'dataEncipherment' not found");
        }
    }
}
 
Example 15
Source File: SmartCardAccessJnaImpl.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 5 votes vote down vote up
public ArrayList<CertificateData> getCertificateList(long slotID) throws Exception{
    ArrayList<CertificateData> ret = new ArrayList<CertificateData>();

    long sessionID = CE.OpenSession(slotID, (CK_SESSION_INFO.CKF_RW_SESSION | CK_SESSION_INFO.CKF_SERIAL_SESSION), null, null);
    try {
        long[] objectIdList = CE.FindObjects(sessionID, new CKA[]{ new CKA(CKA.CLASS, CKO.CERTIFICATE)});
        
        for(long objectId:objectIdList){
            CKA[] ckaId = new CKA[]{ new CKA(CKA.ID, new byte[255])};
            CE.GetAttributeValue(sessionID, objectId, ckaId);
            byte[] id = StringUtils.trim(ckaId[0].getValue());
            
            CKA[] ckaLabel = new CKA[]{ new CKA(CKA.LABEL, new byte[255])};
            CE.GetAttributeValue(sessionID, objectId, ckaLabel);
            byte[] label = StringUtils.trim(ckaLabel[0].getValue());
            
            CKA[] ckaValue = new CKA[]{ new CKA(CKA.VALUE, new byte[2048])};
            CE.GetAttributeValue(sessionID, objectId, ckaValue);
            X509Certificate cert = X509Utils.getX509Certificate(ckaValue[0].getValue());
            
            if(!(cert.getKeyUsage()[0] || cert.getKeyUsage()[1]))
                continue;
            CertificateData cd = new CertificateData();
            cd.certID = id;
            cd.certLABEL = label;
            cd.cert = cert;
            ret.add(cd);
        }
        
        return ret;
    } finally {
        CE.CloseSession(sessionID);
    }
}
 
Example 16
Source File: PkiServiceProvider.java    From NCANode with MIT License 5 votes vote down vote up
public static String keyUsage(X509Certificate cert) {
    boolean[] ku = cert.getKeyUsage();

    if (ku[0] && ku[1]) {
        return "SIGN";
    } else if (ku[0] && ku[2]) {
        return "AUTH";
    } else {
        return "UNKNOWN";
    }
}
 
Example 17
Source File: RFC3281CertPathUtilities.java    From ripple-lib-java with ISC License 5 votes vote down vote up
protected static void processAttrCert3(X509Certificate acIssuerCert,
    PKIXExtendedParameters pkixParams) throws CertPathValidatorException
{
    if (acIssuerCert.getKeyUsage() != null
        && (!acIssuerCert.getKeyUsage()[0] && !acIssuerCert.getKeyUsage()[1]))
    {
        throw new CertPathValidatorException(
            "Attribute certificate issuer public key cannot be used to validate digital signatures.");
    }
    if (acIssuerCert.getBasicConstraints() != -1)
    {
        throw new CertPathValidatorException(
            "Attribute certificate issuer is also a public key certificate issuer.");
    }
}
 
Example 18
Source File: X509Utils.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 4 votes vote down vote up
public static boolean checkIsForSigning(X509Certificate cert){
    if(cert.getKeyUsage()[0])
        return true;
    return false;
}
 
Example 19
Source File: KeyStoresTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testGenerateKeyPair() throws Exception {
    addKeyStore();

    try {
        int numAliasesBefore = readAliases().size();

        ModelNode operation = new ModelNode();
        operation.get(ClientConstants.OP_ADDR).add("subsystem", "elytron").add("key-store", KEYSTORE_NAME);
        operation.get(ClientConstants.OP).set(ElytronDescriptionConstants.GENERATE_KEY_PAIR);
        operation.get(ElytronDescriptionConstants.ALIAS).set("bsmith");
        operation.get(ElytronDescriptionConstants.ALGORITHM).set("RSA");
        operation.get(ElytronDescriptionConstants.KEY_SIZE).set(1024);
        operation.get(ElytronDescriptionConstants.VALIDITY).set(365);
        operation.get(ElytronDescriptionConstants.SIGNATURE_ALGORITHM).set("SHA256withRSA");
        operation.get(ElytronDescriptionConstants.DISTINGUISHED_NAME).set("CN=bob smith, OU=jboss, O=red hat, L=raleigh, ST=north carolina, C=us");
        ModelNode extensions = new ModelNode();
        extensions.add(getExtension(false, "ExtendedKeyUsage", "clientAuth"));
        extensions.add(getExtension(true, "KeyUsage", "digitalSignature"));
        extensions.add(getExtension(false, "SubjectAlternativeName", "email:[email protected],DNS:bobsmith.example.com"));
        operation.get(ElytronDescriptionConstants.EXTENSIONS).set(extensions);
        operation.get(CredentialReference.CREDENTIAL_REFERENCE).get(CredentialReference.CLEAR_TEXT).set(KEY_PASSWORD);
        assertSuccess(services.executeOperation(operation));
        assertEquals(numAliasesBefore + 1, readAliases().size());

        ModelNode newAlias = readAlias("bsmith");
        assertEquals(KeyStore.PrivateKeyEntry.class.getSimpleName(), newAlias.get(ElytronDescriptionConstants.ENTRY_TYPE).asString());
        assertEquals(1, newAlias.get(ElytronDescriptionConstants.CERTIFICATE_CHAIN).asList().size());

        ServiceName serviceName = Capabilities.KEY_STORE_RUNTIME_CAPABILITY.getCapabilityServiceName(KEYSTORE_NAME);
        KeyStore keyStore = (KeyStore) services.getContainer().getService(serviceName).getValue();
        assertNotNull(keyStore);
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate("bsmith");
        assertEquals("RSA", certificate.getPublicKey().getAlgorithm());
        assertEquals(1024, ((RSAKey) certificate.getPublicKey()).getModulus().bitLength());
        Date notBefore = certificate.getNotBefore();
        Date notAfter = certificate.getNotAfter();
        assertEquals(365, (notAfter.getTime() - notBefore.getTime()) / (1000 * 60 * 60 * 24));
        assertEquals("SHA256withRSA", certificate.getSigAlgName());
        assertEquals(new X500Principal("CN=bob smith, OU=jboss, O=red hat, L=raleigh, ST=north carolina, C=us"), certificate.getSubjectX500Principal());
        assertEquals(new X500Principal("CN=bob smith, OU=jboss, O=red hat, L=raleigh, ST=north carolina, C=us"), certificate.getIssuerX500Principal());
        try {
            certificate.verify(certificate.getPublicKey());
        } catch (Exception e) {
            fail("Exception not expected");
        }
        assertEquals(1, certificate.getCriticalExtensionOIDs().size());
        assertEquals(3, certificate.getNonCriticalExtensionOIDs().size());
        assertEquals(Arrays.asList(X500.OID_KP_CLIENT_AUTH), certificate.getExtendedKeyUsage());
        boolean[] keyUsage = certificate.getKeyUsage();
        assertTrue(KeyUsage.digitalSignature.in(keyUsage));
        final Collection<List<?>> names = certificate.getSubjectAlternativeNames();
        assertEquals(2, names.size());
        final Iterator<List<?>> iterator = names.iterator();
        List<?> item = iterator.next();
        assertEquals(2, item.size());
        assertEquals(Integer.valueOf(GeneralName.RFC_822_NAME), item.get(0));
        assertEquals("[email protected]", item.get(1));
        item = iterator.next();
        assertEquals(2, item.size());
        assertEquals(Integer.valueOf(GeneralName.DNS_NAME), item.get(0));
        assertEquals("bobsmith.example.com", item.get(1));
        assertNotNull(certificate.getExtensionValue(X500.OID_CE_SUBJECT_KEY_IDENTIFIER));

        assertNotNull(keyStore.getKey("bsmith", KEY_PASSWORD.toCharArray()));
    } finally {
        removeKeyStore();
    }
}
 
Example 20
Source File: ICPBRKeyUsage.java    From signer with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * 
 * @param cert
 *            X509Certificate
 */
public ICPBRKeyUsage(X509Certificate cert) {
	this.keyUsage = cert.getKeyUsage();
}