Search in sources :

Example 6 with KeyUsageExtension

use of org.mozilla.jss.netscape.security.x509.KeyUsageExtension in project jdk8u_jdk by JetBrains.

the class SignerInfo method verify.

/* Returns null if verify fails, this signerInfo if
       verify succeeds. */
SignerInfo verify(PKCS7 block, byte[] data) throws NoSuchAlgorithmException, SignatureException {
    try {
        ContentInfo content = block.getContentInfo();
        if (data == null) {
            data = content.getContentBytes();
        }
        ConstraintsParameters cparams = new ConstraintsParameters(timestamp);
        String digestAlgname = getDigestAlgorithmId().getName();
        byte[] dataSigned;
        // digest and compare it with the digest of data
        if (authenticatedAttributes == null) {
            dataSigned = data;
        } else {
            // first, check content type
            ObjectIdentifier contentType = (ObjectIdentifier) authenticatedAttributes.getAttributeValue(PKCS9Attribute.CONTENT_TYPE_OID);
            if (contentType == null || !contentType.equals((Object) content.contentType))
                // contentType does not match, bad SignerInfo
                return null;
            // now, check message digest
            byte[] messageDigest = (byte[]) authenticatedAttributes.getAttributeValue(PKCS9Attribute.MESSAGE_DIGEST_OID);
            if (// fail if there is no message digest
            messageDigest == null)
                return null;
            // check that digest algorithm is not restricted
            try {
                JAR_DISABLED_CHECK.permits(digestAlgname, cparams);
            } catch (CertPathValidatorException e) {
                throw new SignatureException(e.getMessage(), e);
            }
            MessageDigest md = MessageDigest.getInstance(digestAlgname);
            byte[] computedMessageDigest = md.digest(data);
            if (messageDigest.length != computedMessageDigest.length)
                return null;
            for (int i = 0; i < messageDigest.length; i++) {
                if (messageDigest[i] != computedMessageDigest[i])
                    return null;
            }
            // message digest attribute matched
            // digest of original data
            // the data actually signed is the DER encoding of
            // the authenticated attributes (tagged with
            // the "SET OF" tag, not 0xA0).
            dataSigned = authenticatedAttributes.getDerEncoding();
        }
        // put together digest algorithm and encryption algorithm
        // to form signing algorithm
        String encryptionAlgname = getDigestEncryptionAlgorithmId().getName();
        // Workaround: sometimes the encryptionAlgname is actually
        // a signature name
        String tmp = AlgorithmId.getEncAlgFromSigAlg(encryptionAlgname);
        if (tmp != null)
            encryptionAlgname = tmp;
        String algname = AlgorithmId.makeSigAlg(digestAlgname, encryptionAlgname);
        // check that jar signature algorithm is not restricted
        try {
            JAR_DISABLED_CHECK.permits(algname, cparams);
        } catch (CertPathValidatorException e) {
            throw new SignatureException(e.getMessage(), e);
        }
        X509Certificate cert = getCertificate(block);
        if (cert == null) {
            return null;
        }
        PublicKey key = cert.getPublicKey();
        // check if the public key is restricted
        if (!JAR_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
            throw new SignatureException("Public key check failed. " + "Disabled key used: " + KeyUtil.getKeySize(key) + " bit " + key.getAlgorithm());
        }
        if (cert.hasUnsupportedCriticalExtension()) {
            throw new SignatureException("Certificate has unsupported " + "critical extension(s)");
        }
        // Make sure that if the usage of the key in the certificate is
        // restricted, it can be used for digital signatures.
        // XXX We may want to check for additional extensions in the
        // future.
        boolean[] keyUsageBits = cert.getKeyUsage();
        if (keyUsageBits != null) {
            KeyUsageExtension keyUsage;
            try {
                // We don't care whether or not this extension was marked
                // critical in the certificate.
                // We're interested only in its value (i.e., the bits set)
                // and treat the extension as critical.
                keyUsage = new KeyUsageExtension(keyUsageBits);
            } catch (IOException ioe) {
                throw new SignatureException("Failed to parse keyUsage " + "extension");
            }
            boolean digSigAllowed = keyUsage.get(KeyUsageExtension.DIGITAL_SIGNATURE).booleanValue();
            boolean nonRepuAllowed = keyUsage.get(KeyUsageExtension.NON_REPUDIATION).booleanValue();
            if (!digSigAllowed && !nonRepuAllowed) {
                throw new SignatureException("Key usage restricted: " + "cannot be used for " + "digital signatures");
            }
        }
        Signature sig = Signature.getInstance(algname);
        sig.initVerify(key);
        sig.update(dataSigned);
        if (sig.verify(encryptedDigest)) {
            return this;
        }
    } catch (IOException e) {
        throw new SignatureException("IO error verifying signature:\n" + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new SignatureException("InvalidKey: " + e.getMessage());
    }
    return null;
}
Also used : PublicKey(java.security.PublicKey) SignatureException(java.security.SignatureException) IOException(java.io.IOException) ConstraintsParameters(sun.security.util.ConstraintsParameters) InvalidKeyException(java.security.InvalidKeyException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException) Signature(java.security.Signature) MessageDigest(java.security.MessageDigest) ObjectIdentifier(sun.security.util.ObjectIdentifier) KeyUsageExtension(sun.security.x509.KeyUsageExtension)

Example 7 with KeyUsageExtension

use of org.mozilla.jss.netscape.security.x509.KeyUsageExtension in project Bytecoder by mirkosertic.

the class SignerInfo method verify.

/* Returns null if verify fails, this signerInfo if
       verify succeeds. */
SignerInfo verify(PKCS7 block, byte[] data) throws NoSuchAlgorithmException, SignatureException {
    try {
        ContentInfo content = block.getContentInfo();
        if (data == null) {
            data = content.getContentBytes();
        }
        Timestamp timestamp = null;
        try {
            timestamp = getTimestamp();
        } catch (Exception ignore) {
        }
        ConstraintsParameters cparams = new ConstraintsParameters(timestamp);
        String digestAlgname = getDigestAlgorithmId().getName();
        byte[] dataSigned;
        // digest and compare it with the digest of data
        if (authenticatedAttributes == null) {
            dataSigned = data;
        } else {
            // first, check content type
            ObjectIdentifier contentType = (ObjectIdentifier) authenticatedAttributes.getAttributeValue(PKCS9Attribute.CONTENT_TYPE_OID);
            if (contentType == null || !contentType.equals(content.contentType))
                // contentType does not match, bad SignerInfo
                return null;
            // now, check message digest
            byte[] messageDigest = (byte[]) authenticatedAttributes.getAttributeValue(PKCS9Attribute.MESSAGE_DIGEST_OID);
            if (// fail if there is no message digest
            messageDigest == null)
                return null;
            // check that digest algorithm is not restricted
            try {
                JAR_DISABLED_CHECK.permits(digestAlgname, cparams);
            } catch (CertPathValidatorException e) {
                throw new SignatureException(e.getMessage(), e);
            }
            MessageDigest md = MessageDigest.getInstance(digestAlgname);
            byte[] computedMessageDigest = md.digest(data);
            if (messageDigest.length != computedMessageDigest.length)
                return null;
            for (int i = 0; i < messageDigest.length; i++) {
                if (messageDigest[i] != computedMessageDigest[i])
                    return null;
            }
            // message digest attribute matched
            // digest of original data
            // the data actually signed is the DER encoding of
            // the authenticated attributes (tagged with
            // the "SET OF" tag, not 0xA0).
            dataSigned = authenticatedAttributes.getDerEncoding();
        }
        // put together digest algorithm and encryption algorithm
        // to form signing algorithm
        String encryptionAlgname = getDigestEncryptionAlgorithmId().getName();
        // Workaround: sometimes the encryptionAlgname is actually
        // a signature name
        String tmp = AlgorithmId.getEncAlgFromSigAlg(encryptionAlgname);
        if (tmp != null)
            encryptionAlgname = tmp;
        String algname = AlgorithmId.makeSigAlg(digestAlgname, encryptionAlgname);
        // check that jar signature algorithm is not restricted
        try {
            JAR_DISABLED_CHECK.permits(algname, cparams);
        } catch (CertPathValidatorException e) {
            throw new SignatureException(e.getMessage(), e);
        }
        X509Certificate cert = getCertificate(block);
        if (cert == null) {
            return null;
        }
        PublicKey key = cert.getPublicKey();
        // check if the public key is restricted
        if (!JAR_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
            throw new SignatureException("Public key check failed. " + "Disabled key used: " + KeyUtil.getKeySize(key) + " bit " + key.getAlgorithm());
        }
        if (cert.hasUnsupportedCriticalExtension()) {
            throw new SignatureException("Certificate has unsupported " + "critical extension(s)");
        }
        // Make sure that if the usage of the key in the certificate is
        // restricted, it can be used for digital signatures.
        // XXX We may want to check for additional extensions in the
        // future.
        boolean[] keyUsageBits = cert.getKeyUsage();
        if (keyUsageBits != null) {
            KeyUsageExtension keyUsage;
            try {
                // We don't care whether or not this extension was marked
                // critical in the certificate.
                // We're interested only in its value (i.e., the bits set)
                // and treat the extension as critical.
                keyUsage = new KeyUsageExtension(keyUsageBits);
            } catch (IOException ioe) {
                throw new SignatureException("Failed to parse keyUsage " + "extension");
            }
            boolean digSigAllowed = keyUsage.get(KeyUsageExtension.DIGITAL_SIGNATURE).booleanValue();
            boolean nonRepuAllowed = keyUsage.get(KeyUsageExtension.NON_REPUDIATION).booleanValue();
            if (!digSigAllowed && !nonRepuAllowed) {
                throw new SignatureException("Key usage restricted: " + "cannot be used for " + "digital signatures");
            }
        }
        Signature sig = Signature.getInstance(algname);
        sig.initVerify(key);
        sig.update(dataSigned);
        if (sig.verify(encryptedDigest)) {
            return this;
        }
    } catch (IOException e) {
        throw new SignatureException("IO error verifying signature:\n" + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new SignatureException("InvalidKey: " + e.getMessage());
    }
    return null;
}
Also used : PublicKey(java.security.PublicKey) SignatureException(java.security.SignatureException) IOException(java.io.IOException) ConstraintsParameters(sun.security.util.ConstraintsParameters) InvalidKeyException(java.security.InvalidKeyException) Timestamp(java.security.Timestamp) CertPathValidatorException(java.security.cert.CertPathValidatorException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException) Signature(java.security.Signature) MessageDigest(java.security.MessageDigest) ObjectIdentifier(sun.security.util.ObjectIdentifier) KeyUsageExtension(sun.security.x509.KeyUsageExtension)

Example 8 with KeyUsageExtension

use of org.mozilla.jss.netscape.security.x509.KeyUsageExtension in project candlepin by candlepin.

the class JSSPKIUtility method buildStandardExtensions.

/**
 * Add boilerplate extensions required by RFC 5280.
 * @param certExtensions a CertificateExtensions object to modify
 * @param keyPair the KeyPair used to create the SubjectKeyIdentifier extension
 * @param providedExtensions A Set of provided extensions that will be added to the certificate.  In some
 * cases (hosted mode) access to the information in those extensions is required for creating the
 * subjectKeyIdentifier.
 *
 * @return a modified version of the certExtensions parameter
 * @throws IOException in case of encoding failures
 */
private CertificateExtensions buildStandardExtensions(CertificateExtensions certExtensions, String dn, KeyPair keyPair, Set<X509ExtensionWrapper> providedExtensions, X509Certificate caCert, String alternateName) throws IOException {
    /* The RFC states that KeyUsage SHOULD be marked as critical.  In previous Candlepin code we were
         * not marking it critical but this constructor will.  I do not believe there should be any
         * compatibility issues, but I am noting it just in case. */
    KeyUsageExtension keyUsage = new KeyUsageExtension();
    keyUsage.set(KeyUsageExtension.DIGITAL_SIGNATURE, true);
    keyUsage.set(KeyUsageExtension.KEY_ENCIPHERMENT, true);
    keyUsage.set(KeyUsageExtension.DATA_ENCIPHERMENT, true);
    certExtensions.add(keyUsage);
    // Not critical by default
    ExtendedKeyUsageExtension extendedKeyUsage = new ExtendedKeyUsageExtension();
    /* JSS doesn't have a constant defined for the "clientAuth" OID so we have to put it in by hand.
         * See https://tools.ietf.org/html/rfc5280#appendix-A specifically id-kp-clientAuth.  This OID
         * denotes that a certificate is meant for client authentication over TLS */
    extendedKeyUsage.addOID(new ObjectIdentifier("1.3.6.1.5.5.7.3.2"));
    certExtensions.add(extendedKeyUsage);
    // Not critical for non-CA certs.  -1 pathLen means it won't be encoded.
    BasicConstraintsExtension basicConstraints = new BasicConstraintsExtension(false, -1);
    certExtensions.add(basicConstraints);
    try {
        /* Not critical by default.  I am extremely dubious that we actually need this extension
             * but I'm keeping it because our old cert creation code added it. */
        NSCertTypeExtension netscapeCertType = new NSCertTypeExtension();
        netscapeCertType.set(NSCertTypeExtension.SSL_CLIENT, true);
        netscapeCertType.set(NSCertTypeExtension.EMAIL, true);
        certExtensions.add(netscapeCertType);
    } catch (CertificateException e) {
        throw new IOException("Could not construct certificate extensions", e);
    }
    try {
        /* The JSS SubjectKeyIdentifierExtension class expects you to give it the unencoded KeyIdentifier.
             * The SubjectKeyIdentifierExtension class, however, returns the encoded KeyIdentifier (an DER
             * octet string).  Therefore, we need to unpack the KeyIdentifier. */
        byte[] encodedSki = subjectKeyWriter.getSubjectKeyIdentifier(keyPair, providedExtensions);
        OCTET_STRING extOctets = (OCTET_STRING) ASN1Util.decode(new OCTET_STRING.Template(), encodedSki);
        // Required to be non-critical
        SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension(extOctets.toByteArray());
        certExtensions.add(ski);
        // Not critical by default
        AuthorityKeyIdentifierExtension aki = buildAuthorityKeyIdentifier(caCert);
        certExtensions.add(aki);
        // Not critical by default and should *not* be critical since the subject field isn't empty
        if (alternateName != null) {
            SubjectAlternativeNameExtension altNames = new SubjectAlternativeNameExtension();
            GeneralName[] akiName = new GeneralName[2];
            akiName[0] = new GeneralName(new X500Name(dn));
            akiName[1] = new GeneralName(new X500Name("CN=" + alternateName));
            GeneralNames generalNames = new GeneralNames(akiName);
            altNames.setGeneralNames(generalNames);
            certExtensions.add(altNames);
        }
    } catch (InvalidBERException | GeneralNamesException | NoSuchAlgorithmException e) {
        throw new IOException("Could not construct certificate extensions", e);
    }
    return certExtensions;
}
Also used : ExtendedKeyUsageExtension(org.mozilla.jss.netscape.security.extensions.ExtendedKeyUsageExtension) NSCertTypeExtension(org.mozilla.jss.netscape.security.extensions.NSCertTypeExtension) SubjectAlternativeNameExtension(org.mozilla.jss.netscape.security.x509.SubjectAlternativeNameExtension) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) X500Name(org.mozilla.jss.netscape.security.x509.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectKeyIdentifierExtension(org.mozilla.jss.netscape.security.x509.SubjectKeyIdentifierExtension) InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) BasicConstraintsExtension(org.mozilla.jss.netscape.security.x509.BasicConstraintsExtension) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) GeneralNames(org.mozilla.jss.netscape.security.x509.GeneralNames) GeneralNamesException(org.mozilla.jss.netscape.security.x509.GeneralNamesException) AuthorityKeyIdentifierExtension(org.mozilla.jss.netscape.security.x509.AuthorityKeyIdentifierExtension) GeneralName(org.mozilla.jss.netscape.security.x509.GeneralName) KeyUsageExtension(org.mozilla.jss.netscape.security.x509.KeyUsageExtension) ExtendedKeyUsageExtension(org.mozilla.jss.netscape.security.extensions.ExtendedKeyUsageExtension) ObjectIdentifier(org.mozilla.jss.netscape.security.util.ObjectIdentifier)

Example 9 with KeyUsageExtension

use of org.mozilla.jss.netscape.security.x509.KeyUsageExtension in project OpenAttestation by OpenAttestation.

the class X509Builder method keyUsageKeyEncipherment.

public X509Builder keyUsageKeyEncipherment() {
    // for encrypting and transporting other keys
    try {
        v3();
        if (keyUsageExtension == null) {
            keyUsageExtension = new KeyUsageExtension();
        }
        keyUsageExtension.set(KeyUsageExtension.KEY_ENCIPHERMENT, true);
        if (certificateExtensions == null) {
            certificateExtensions = new CertificateExtensions();
        }
        certificateExtensions.set(keyUsageExtension.getExtensionId().toString(), keyUsageExtension);
        info.set(X509CertInfo.EXTENSIONS, certificateExtensions);
    } catch (Exception e) {
        fault(e, "keyUsageKeyEncipherment");
    }
    return this;
}
Also used : CertificateExtensions(sun.security.x509.CertificateExtensions) KeyUsageExtension(sun.security.x509.KeyUsageExtension) ExtendedKeyUsageExtension(sun.security.x509.ExtendedKeyUsageExtension)

Example 10 with KeyUsageExtension

use of org.mozilla.jss.netscape.security.x509.KeyUsageExtension in project OpenAttestation by OpenAttestation.

the class X509Builder method keyUsageNonRepudiation.

public X509Builder keyUsageNonRepudiation() {
    // other than CA or CRL; this applies to API clients
    try {
        v3();
        if (keyUsageExtension == null) {
            keyUsageExtension = new KeyUsageExtension();
        }
        keyUsageExtension.set(KeyUsageExtension.NON_REPUDIATION, true);
        if (certificateExtensions == null) {
            certificateExtensions = new CertificateExtensions();
        }
        certificateExtensions.set(keyUsageExtension.getExtensionId().toString(), keyUsageExtension);
        info.set(X509CertInfo.EXTENSIONS, certificateExtensions);
    } catch (Exception e) {
        fault(e, "keyUsageNonRepudiation");
    }
    return this;
}
Also used : CertificateExtensions(sun.security.x509.CertificateExtensions) KeyUsageExtension(sun.security.x509.KeyUsageExtension) ExtendedKeyUsageExtension(sun.security.x509.ExtendedKeyUsageExtension)

Aggregations

KeyUsageExtension (sun.security.x509.KeyUsageExtension)12 CertificateExtensions (sun.security.x509.CertificateExtensions)8 ExtendedKeyUsageExtension (sun.security.x509.ExtendedKeyUsageExtension)6 IOException (java.io.IOException)5 X509Certificate (java.security.cert.X509Certificate)3 InvalidKeyException (java.security.InvalidKeyException)2 MessageDigest (java.security.MessageDigest)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 PublicKey (java.security.PublicKey)2 Signature (java.security.Signature)2 SignatureException (java.security.SignatureException)2 CertPathValidatorException (java.security.cert.CertPathValidatorException)2 CertificateException (java.security.cert.CertificateException)2 ExtendedKeyUsageExtension (org.mozilla.jss.netscape.security.extensions.ExtendedKeyUsageExtension)2 KeyUsageExtension (org.mozilla.jss.netscape.security.x509.KeyUsageExtension)2 ConstraintsParameters (sun.security.util.ConstraintsParameters)2 ObjectIdentifier (sun.security.util.ObjectIdentifier)2 BasicConstraintsExtension (sun.security.x509.BasicConstraintsExtension)2 NAEException (com.ingrian.security.nae.NAEException)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1