Search in sources :

Example 1 with KeyUsageExtension

use of sun.security.x509.KeyUsageExtension in project OpenAttestation by OpenAttestation.

the class X509Builder method keyUsageCRLSign.

public X509Builder keyUsageCRLSign() {
    try {
        v3();
        if (keyUsageExtension == null) {
            keyUsageExtension = new KeyUsageExtension();
        }
        keyUsageExtension.set(KeyUsageExtension.CRL_SIGN, true);
        if (certificateExtensions == null) {
            certificateExtensions = new CertificateExtensions();
        }
        certificateExtensions.set(keyUsageExtension.getExtensionId().toString(), keyUsageExtension);
        info.set(X509CertInfo.EXTENSIONS, certificateExtensions);
    } catch (Exception e) {
        fault(e, "keyUsageCRLSign");
    }
    return this;
}
Also used : CertificateExtensions(sun.security.x509.CertificateExtensions) KeyUsageExtension(sun.security.x509.KeyUsageExtension) ExtendedKeyUsageExtension(sun.security.x509.ExtendedKeyUsageExtension)

Example 2 with KeyUsageExtension

use of sun.security.x509.KeyUsageExtension in project OpenAttestation by OpenAttestation.

the class X509Builder method keyUsageDataEncipherment.

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

Example 3 with KeyUsageExtension

use of sun.security.x509.KeyUsageExtension in project OpenAttestation by OpenAttestation.

the class X509Builder method keyUsageDigitalSignature.

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

Example 4 with KeyUsageExtension

use of sun.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 5 with KeyUsageExtension

use of sun.security.x509.KeyUsageExtension in project Bytecoder by mirkosertic.

the class Pair method createV3Extensions.

/**
 * Create X509v3 extensions from a string representation. Note that the
 * SubjectKeyIdentifierExtension will always be created non-critical besides
 * the extension requested in the <code>extstr</code> argument.
 *
 * @param requestedEx the requested extensions, can be null, used for -gencert
 * @param existingEx the original extensions, can be null, used for -selfcert
 * @param extstrs -ext values, Read keytool doc
 * @param pkey the public key for the certificate
 * @param akey the public key for the authority (issuer)
 * @return the created CertificateExtensions
 */
private CertificateExtensions createV3Extensions(CertificateExtensions requestedEx, CertificateExtensions existingEx, List<String> extstrs, PublicKey pkey, PublicKey akey) throws Exception {
    if (existingEx != null && requestedEx != null) {
        // This should not happen
        throw new Exception("One of request and original should be null.");
    }
    // A new extensions always using OID as key
    CertificateExtensions result = new CertificateExtensions();
    if (existingEx != null) {
        for (Extension ex : existingEx.getAllExtensions()) {
            setExt(result, ex);
        }
    }
    try {
        // Honoring requested extensions
        if (requestedEx != null) {
            // The existing requestedEx might use names as keys,
            // translate to all-OID first.
            CertificateExtensions request2 = new CertificateExtensions();
            for (sun.security.x509.Extension ex : requestedEx.getAllExtensions()) {
                request2.set(ex.getId(), ex);
            }
            for (String extstr : extstrs) {
                if (extstr.toLowerCase(Locale.ENGLISH).startsWith("honored=")) {
                    List<String> list = Arrays.asList(extstr.toLowerCase(Locale.ENGLISH).substring(8).split(","));
                    // First check existence of "all"
                    if (list.contains("all")) {
                        for (Extension ex : request2.getAllExtensions()) {
                            setExt(result, ex);
                        }
                    }
                    // one by one for others
                    for (String item : list) {
                        if (item.equals("all"))
                            continue;
                        // add or remove
                        boolean add;
                        // -1, unchanged, 0 critical, 1 non-critical
                        int action = -1;
                        String type = null;
                        if (item.startsWith("-")) {
                            add = false;
                            type = item.substring(1);
                        } else {
                            add = true;
                            int colonpos = item.indexOf(':');
                            if (colonpos >= 0) {
                                type = item.substring(0, colonpos);
                                action = oneOf(item.substring(colonpos + 1), "critical", "non-critical");
                                if (action == -1) {
                                    throw new Exception(rb.getString("Illegal.value.") + item);
                                }
                            } else {
                                type = item;
                            }
                        }
                        String n = findOidForExtName(type).toString();
                        if (add) {
                            Extension e = request2.get(n);
                            if (!e.isCritical() && action == 0 || e.isCritical() && action == 1) {
                                e = Extension.newExtension(e.getExtensionId(), !e.isCritical(), e.getExtensionValue());
                            }
                            setExt(result, e);
                        } else {
                            result.delete(n);
                        }
                    }
                    break;
                }
            }
        }
        for (String extstr : extstrs) {
            String name, value;
            boolean isCritical = false;
            int eqpos = extstr.indexOf('=');
            if (eqpos >= 0) {
                name = extstr.substring(0, eqpos);
                value = extstr.substring(eqpos + 1);
            } else {
                name = extstr;
                value = null;
            }
            int colonpos = name.indexOf(':');
            if (colonpos >= 0) {
                if (oneOf(name.substring(colonpos + 1), "critical") == 0) {
                    isCritical = true;
                }
                name = name.substring(0, colonpos);
            }
            if (name.equalsIgnoreCase("honored")) {
                continue;
            }
            int exttype = oneOf(name, extSupported);
            switch(exttype) {
                case // BC
                0:
                    int pathLen = -1;
                    boolean isCA = false;
                    if (value == null) {
                        isCA = true;
                    } else {
                        try {
                            // the abbr format
                            pathLen = Integer.parseInt(value);
                            isCA = true;
                        } catch (NumberFormatException ufe) {
                            // ca:true,pathlen:1
                            for (String part : value.split(",")) {
                                String[] nv = part.split(":");
                                if (nv.length != 2) {
                                    throw new Exception(rb.getString("Illegal.value.") + extstr);
                                } else {
                                    if (nv[0].equalsIgnoreCase("ca")) {
                                        isCA = Boolean.parseBoolean(nv[1]);
                                    } else if (nv[0].equalsIgnoreCase("pathlen")) {
                                        pathLen = Integer.parseInt(nv[1]);
                                    } else {
                                        throw new Exception(rb.getString("Illegal.value.") + extstr);
                                    }
                                }
                            }
                        }
                    }
                    setExt(result, new BasicConstraintsExtension(isCritical, isCA, pathLen));
                    break;
                case // KU
                1:
                    if (value != null) {
                        boolean[] ok = new boolean[9];
                        for (String s : value.split(",")) {
                            int p = oneOf(s, // (0),
                            "digitalSignature", // (1)
                            "nonRepudiation", // (2),
                            "keyEncipherment", // (3),
                            "dataEncipherment", // (4),
                            "keyAgreement", // (5),
                            "keyCertSign", // (6),
                            "cRLSign", // (7),
                            "encipherOnly", // (8)
                            "decipherOnly", // also (1)
                            "contentCommitment");
                            if (p < 0) {
                                throw new Exception(rb.getString("Unknown.keyUsage.type.") + s);
                            }
                            if (p == 9)
                                p = 1;
                            ok[p] = true;
                        }
                        KeyUsageExtension kue = new KeyUsageExtension(ok);
                        // The above KeyUsageExtension constructor does not
                        // allow isCritical value, so...
                        setExt(result, Extension.newExtension(kue.getExtensionId(), isCritical, kue.getExtensionValue()));
                    } else {
                        throw new Exception(rb.getString("Illegal.value.") + extstr);
                    }
                    break;
                case // EKU
                2:
                    if (value != null) {
                        Vector<ObjectIdentifier> v = new Vector<>();
                        for (String s : value.split(",")) {
                            int p = oneOf(s, "anyExtendedKeyUsage", // 1
                            "serverAuth", // 2
                            "clientAuth", // 3
                            "codeSigning", // 4
                            "emailProtection", // 5
                            "", // 6
                            "", // 7
                            "", // 8
                            "timeStamping", // 9
                            "OCSPSigning");
                            if (p < 0) {
                                try {
                                    v.add(new ObjectIdentifier(s));
                                } catch (Exception e) {
                                    throw new Exception(rb.getString("Unknown.extendedkeyUsage.type.") + s);
                                }
                            } else if (p == 0) {
                                v.add(new ObjectIdentifier("2.5.29.37.0"));
                            } else {
                                v.add(new ObjectIdentifier("1.3.6.1.5.5.7.3." + p));
                            }
                        }
                        setExt(result, new ExtendedKeyUsageExtension(isCritical, v));
                    } else {
                        throw new Exception(rb.getString("Illegal.value.") + extstr);
                    }
                    break;
                // SAN
                case 3:
                case // IAN
                4:
                    if (value != null) {
                        String[] ps = value.split(",");
                        GeneralNames gnames = new GeneralNames();
                        for (String item : ps) {
                            colonpos = item.indexOf(':');
                            if (colonpos < 0) {
                                throw new Exception("Illegal item " + item + " in " + extstr);
                            }
                            String t = item.substring(0, colonpos);
                            String v = item.substring(colonpos + 1);
                            gnames.add(createGeneralName(t, v));
                        }
                        if (exttype == 3) {
                            setExt(result, new SubjectAlternativeNameExtension(isCritical, gnames));
                        } else {
                            setExt(result, new IssuerAlternativeNameExtension(isCritical, gnames));
                        }
                    } else {
                        throw new Exception(rb.getString("Illegal.value.") + extstr);
                    }
                    break;
                // SIA, always non-critical
                case 5:
                case // AIA, always non-critical
                6:
                    if (isCritical) {
                        throw new Exception(rb.getString("This.extension.cannot.be.marked.as.critical.") + extstr);
                    }
                    if (value != null) {
                        List<AccessDescription> accessDescriptions = new ArrayList<>();
                        String[] ps = value.split(",");
                        for (String item : ps) {
                            colonpos = item.indexOf(':');
                            int colonpos2 = item.indexOf(':', colonpos + 1);
                            if (colonpos < 0 || colonpos2 < 0) {
                                throw new Exception(rb.getString("Illegal.value.") + extstr);
                            }
                            String m = item.substring(0, colonpos);
                            String t = item.substring(colonpos + 1, colonpos2);
                            String v = item.substring(colonpos2 + 1);
                            int p = oneOf(m, "", // 1
                            "ocsp", // 2
                            "caIssuers", // 3
                            "timeStamping", "", // 5
                            "caRepository");
                            ObjectIdentifier oid;
                            if (p < 0) {
                                try {
                                    oid = new ObjectIdentifier(m);
                                } catch (Exception e) {
                                    throw new Exception(rb.getString("Unknown.AccessDescription.type.") + m);
                                }
                            } else {
                                oid = new ObjectIdentifier("1.3.6.1.5.5.7.48." + p);
                            }
                            accessDescriptions.add(new AccessDescription(oid, createGeneralName(t, v)));
                        }
                        if (exttype == 5) {
                            setExt(result, new SubjectInfoAccessExtension(accessDescriptions));
                        } else {
                            setExt(result, new AuthorityInfoAccessExtension(accessDescriptions));
                        }
                    } else {
                        throw new Exception(rb.getString("Illegal.value.") + extstr);
                    }
                    break;
                case // CRL, experimental, only support 1 distributionpoint
                8:
                    if (value != null) {
                        String[] ps = value.split(",");
                        GeneralNames gnames = new GeneralNames();
                        for (String item : ps) {
                            colonpos = item.indexOf(':');
                            if (colonpos < 0) {
                                throw new Exception("Illegal item " + item + " in " + extstr);
                            }
                            String t = item.substring(0, colonpos);
                            String v = item.substring(colonpos + 1);
                            gnames.add(createGeneralName(t, v));
                        }
                        setExt(result, new CRLDistributionPointsExtension(isCritical, Collections.singletonList(new DistributionPoint(gnames, null, null))));
                    } else {
                        throw new Exception(rb.getString("Illegal.value.") + extstr);
                    }
                    break;
                case -1:
                    ObjectIdentifier oid = new ObjectIdentifier(name);
                    byte[] data = null;
                    if (value != null) {
                        data = new byte[value.length() / 2 + 1];
                        int pos = 0;
                        for (char c : value.toCharArray()) {
                            int hex;
                            if (c >= '0' && c <= '9') {
                                hex = c - '0';
                            } else if (c >= 'A' && c <= 'F') {
                                hex = c - 'A' + 10;
                            } else if (c >= 'a' && c <= 'f') {
                                hex = c - 'a' + 10;
                            } else {
                                continue;
                            }
                            if (pos % 2 == 0) {
                                data[pos / 2] = (byte) (hex << 4);
                            } else {
                                data[pos / 2] += hex;
                            }
                            pos++;
                        }
                        if (pos % 2 != 0) {
                            throw new Exception(rb.getString("Odd.number.of.hex.digits.found.") + extstr);
                        }
                        data = Arrays.copyOf(data, pos / 2);
                    } else {
                        data = new byte[0];
                    }
                    setExt(result, new Extension(oid, isCritical, new DerValue(DerValue.tag_OctetString, data).toByteArray()));
                    break;
                default:
                    throw new Exception(rb.getString("Unknown.extension.type.") + extstr);
            }
        }
        // always non-critical
        setExt(result, new SubjectKeyIdentifierExtension(new KeyIdentifier(pkey).getIdentifier()));
        if (akey != null && !pkey.equals(akey)) {
            setExt(result, new AuthorityKeyIdentifierExtension(new KeyIdentifier(akey), null, null));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return result;
}
Also used : DerValue(sun.security.util.DerValue) ObjectIdentifier(sun.security.util.ObjectIdentifier) KeyStoreException(java.security.KeyStoreException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertStoreException(java.security.cert.CertStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) sun.security.x509(sun.security.x509)

Aggregations

KeyUsageExtension (sun.security.x509.KeyUsageExtension)10 CertificateExtensions (sun.security.x509.CertificateExtensions)6 ExtendedKeyUsageExtension (sun.security.x509.ExtendedKeyUsageExtension)6 IOException (java.io.IOException)3 X509Certificate (java.security.cert.X509Certificate)3 ObjectIdentifier (sun.security.util.ObjectIdentifier)3 InvalidKeyException (java.security.InvalidKeyException)2 MessageDigest (java.security.MessageDigest)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 ConstraintsParameters (sun.security.util.ConstraintsParameters)2 DerValue (sun.security.util.DerValue)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 Timestamp (java.security.Timestamp)1