Search in sources :

Example 11 with DerInputStream

use of sun.security.util.DerInputStream in project jdk8u_jdk by JetBrains.

the class X509CertSelector method matchSubjectKeyID.

/* match on subject key identifier extension value */
private boolean matchSubjectKeyID(X509Certificate xcert) {
    if (subjectKeyID == null) {
        return true;
    }
    try {
        byte[] extVal = xcert.getExtensionValue("2.5.29.14");
        if (extVal == null) {
            if (debug != null) {
                debug.println("X509CertSelector.match: " + "no subject key ID extension");
            }
            return false;
        }
        DerInputStream in = new DerInputStream(extVal);
        byte[] certSubjectKeyID = in.getOctetString();
        if (certSubjectKeyID == null || !Arrays.equals(subjectKeyID, certSubjectKeyID)) {
            if (debug != null) {
                debug.println("X509CertSelector.match: " + "subject key IDs don't match");
            }
            return false;
        }
    } catch (IOException ex) {
        if (debug != null) {
            debug.println("X509CertSelector.match: " + "exception in subject key ID check");
        }
        return false;
    }
    return true;
}
Also used : DerInputStream(sun.security.util.DerInputStream) IOException(java.io.IOException)

Example 12 with DerInputStream

use of sun.security.util.DerInputStream in project jdk8u_jdk by JetBrains.

the class X509CertSelector method getExtensionObject.

/**
     * Returns an Extension object given any X509Certificate and extension oid.
     * Throw an {@code IOException} if the extension byte value is
     * malformed.
     *
     * @param cert a {@code X509Certificate}
     * @param extId an {@code integer} which specifies the extension index.
     * Currently, the supported extensions are as follows:
     * index 0 - PrivateKeyUsageExtension
     * index 1 - SubjectAlternativeNameExtension
     * index 2 - NameConstraintsExtension
     * index 3 - CertificatePoliciesExtension
     * index 4 - ExtendedKeyUsageExtension
     * @return an {@code Extension} object whose real type is as specified
     * by the extension oid.
     * @throws IOException if cannot construct the {@code Extension}
     * object with the extension encoding retrieved from the passed in
     * {@code X509Certificate}.
     */
private static Extension getExtensionObject(X509Certificate cert, int extId) throws IOException {
    if (cert instanceof X509CertImpl) {
        X509CertImpl impl = (X509CertImpl) cert;
        switch(extId) {
            case PRIVATE_KEY_USAGE_ID:
                return impl.getPrivateKeyUsageExtension();
            case SUBJECT_ALT_NAME_ID:
                return impl.getSubjectAlternativeNameExtension();
            case NAME_CONSTRAINTS_ID:
                return impl.getNameConstraintsExtension();
            case CERT_POLICIES_ID:
                return impl.getCertificatePoliciesExtension();
            case EXTENDED_KEY_USAGE_ID:
                return impl.getExtendedKeyUsageExtension();
            default:
                return null;
        }
    }
    byte[] rawExtVal = cert.getExtensionValue(EXTENSION_OIDS[extId]);
    if (rawExtVal == null) {
        return null;
    }
    DerInputStream in = new DerInputStream(rawExtVal);
    byte[] encoded = in.getOctetString();
    switch(extId) {
        case PRIVATE_KEY_USAGE_ID:
            try {
                return new PrivateKeyUsageExtension(FALSE, encoded);
            } catch (CertificateException ex) {
                throw new IOException(ex.getMessage());
            }
        case SUBJECT_ALT_NAME_ID:
            return new SubjectAlternativeNameExtension(FALSE, encoded);
        case NAME_CONSTRAINTS_ID:
            return new NameConstraintsExtension(FALSE, encoded);
        case CERT_POLICIES_ID:
            return new CertificatePoliciesExtension(FALSE, encoded);
        case EXTENDED_KEY_USAGE_ID:
            return new ExtendedKeyUsageExtension(FALSE, encoded);
        default:
            return null;
    }
}
Also used : DerInputStream(sun.security.util.DerInputStream) IOException(java.io.IOException)

Example 13 with DerInputStream

use of sun.security.util.DerInputStream in project jdk8u_jdk by JetBrains.

the class X509CRLSelector method match.

/**
     * Decides whether a {@code CRL} should be selected.
     *
     * @param crl the {@code CRL} to be checked
     * @return {@code true} if the {@code CRL} should be selected,
     *         {@code false} otherwise
     */
public boolean match(CRL crl) {
    if (!(crl instanceof X509CRL)) {
        return false;
    }
    X509CRL xcrl = (X509CRL) crl;
    /* match on issuer name */
    if (issuerNames != null) {
        X500Principal issuer = xcrl.getIssuerX500Principal();
        Iterator<X500Principal> i = issuerX500Principals.iterator();
        boolean found = false;
        while (!found && i.hasNext()) {
            if (i.next().equals(issuer)) {
                found = true;
            }
        }
        if (!found) {
            if (debug != null) {
                debug.println("X509CRLSelector.match: issuer DNs " + "don't match");
            }
            return false;
        }
    }
    if ((minCRL != null) || (maxCRL != null)) {
        /* Get CRL number extension from CRL */
        byte[] crlNumExtVal = xcrl.getExtensionValue("2.5.29.20");
        if (crlNumExtVal == null) {
            if (debug != null) {
                debug.println("X509CRLSelector.match: no CRLNumber");
            }
        }
        BigInteger crlNum;
        try {
            DerInputStream in = new DerInputStream(crlNumExtVal);
            byte[] encoded = in.getOctetString();
            CRLNumberExtension crlNumExt = new CRLNumberExtension(Boolean.FALSE, encoded);
            crlNum = crlNumExt.get(CRLNumberExtension.NUMBER);
        } catch (IOException ex) {
            if (debug != null) {
                debug.println("X509CRLSelector.match: exception in " + "decoding CRL number");
            }
            return false;
        }
        /* match on minCRLNumber */
        if (minCRL != null) {
            if (crlNum.compareTo(minCRL) < 0) {
                if (debug != null) {
                    debug.println("X509CRLSelector.match: CRLNumber too small");
                }
                return false;
            }
        }
        /* match on maxCRLNumber */
        if (maxCRL != null) {
            if (crlNum.compareTo(maxCRL) > 0) {
                if (debug != null) {
                    debug.println("X509CRLSelector.match: CRLNumber too large");
                }
                return false;
            }
        }
    }
    /* match on dateAndTime */
    if (dateAndTime != null) {
        Date crlThisUpdate = xcrl.getThisUpdate();
        Date nextUpdate = xcrl.getNextUpdate();
        if (nextUpdate == null) {
            if (debug != null) {
                debug.println("X509CRLSelector.match: nextUpdate null");
            }
            return false;
        }
        Date nowPlusSkew = dateAndTime;
        Date nowMinusSkew = dateAndTime;
        if (skew > 0) {
            nowPlusSkew = new Date(dateAndTime.getTime() + skew);
            nowMinusSkew = new Date(dateAndTime.getTime() - skew);
        }
        //     nextUpdate + MAX_CLOCK_SKEW ]
        if (nowMinusSkew.after(nextUpdate) || nowPlusSkew.before(crlThisUpdate)) {
            if (debug != null) {
                debug.println("X509CRLSelector.match: update out-of-range");
            }
            return false;
        }
    }
    return true;
}
Also used : X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) DerInputStream(sun.security.util.DerInputStream) IOException(java.io.IOException) CRLNumberExtension(sun.security.x509.CRLNumberExtension)

Example 14 with DerInputStream

use of sun.security.util.DerInputStream in project jdk8u_jdk by JetBrains.

the class GSSNameImpl method importName.

private void importName(GSSManagerImpl gssManager, Object appName) throws GSSException {
    int pos = 0;
    byte[] bytes = null;
    if (appName instanceof String) {
        try {
            bytes = ((String) appName).getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
        // Won't happen
        }
    } else
        bytes = (byte[]) appName;
    if ((bytes[pos++] != 0x04) || (bytes[pos++] != 0x01))
        throw new GSSExceptionImpl(GSSException.BAD_NAME, "Exported name token id is corrupted!");
    int oidLen = (((0xFF & bytes[pos++]) << 8) | (0xFF & bytes[pos++]));
    ObjectIdentifier temp = null;
    try {
        DerInputStream din = new DerInputStream(bytes, pos, oidLen);
        temp = new ObjectIdentifier(din);
    } catch (IOException e) {
        throw new GSSExceptionImpl(GSSException.BAD_NAME, "Exported name Object identifier is corrupted!");
    }
    Oid oid = new Oid(temp.toString());
    pos += oidLen;
    int mechPortionLen = (((0xFF & bytes[pos++]) << 24) | ((0xFF & bytes[pos++]) << 16) | ((0xFF & bytes[pos++]) << 8) | (0xFF & bytes[pos++]));
    if (mechPortionLen < 0 || pos > bytes.length - mechPortionLen) {
        throw new GSSExceptionImpl(GSSException.BAD_NAME, "Exported name mech name is corrupted!");
    }
    byte[] mechPortion = new byte[mechPortionLen];
    System.arraycopy(bytes, pos, mechPortion, 0, mechPortionLen);
    init(gssManager, mechPortion, NT_EXPORT_NAME, oid);
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) DerInputStream(sun.security.util.DerInputStream) IOException(java.io.IOException) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 15 with DerInputStream

use of sun.security.util.DerInputStream in project jdk8u_jdk by JetBrains.

the class PKCS12KeyStore method engineLoad.

/**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
public synchronized void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    DataInputStream dis;
    CertificateFactory cf = null;
    ByteArrayInputStream bais = null;
    byte[] encoded = null;
    if (stream == null)
        return;
    // reset the counter
    counter = 0;
    DerValue val = new DerValue(stream);
    DerInputStream s = val.toDerInputStream();
    int version = s.getInteger();
    if (version != VERSION_3) {
        throw new IOException("PKCS12 keystore not in version 3 format");
    }
    entries.clear();
    /*
         * Read the authSafe.
         */
    byte[] authSafeData;
    ContentInfo authSafe = new ContentInfo(s);
    ObjectIdentifier contentType = authSafe.getContentType();
    if (contentType.equals((Object) ContentInfo.DATA_OID)) {
        authSafeData = authSafe.getData();
    } else /* signed data */
    {
        throw new IOException("public key protected PKCS12 not supported");
    }
    DerInputStream as = new DerInputStream(authSafeData);
    DerValue[] safeContentsArray = as.getSequence(2);
    int count = safeContentsArray.length;
    // reset the counters at the start
    privateKeyCount = 0;
    secretKeyCount = 0;
    certificateCount = 0;
    /*
         * Spin over the ContentInfos.
         */
    for (int i = 0; i < count; i++) {
        byte[] safeContentsData;
        ContentInfo safeContents;
        DerInputStream sci;
        byte[] eAlgId = null;
        sci = new DerInputStream(safeContentsArray[i].toByteArray());
        safeContents = new ContentInfo(sci);
        contentType = safeContents.getContentType();
        safeContentsData = null;
        if (contentType.equals((Object) ContentInfo.DATA_OID)) {
            if (debug != null) {
                debug.println("Loading PKCS#7 data content-type");
            }
            safeContentsData = safeContents.getData();
        } else if (contentType.equals((Object) ContentInfo.ENCRYPTED_DATA_OID)) {
            if (password == null) {
                if (debug != null) {
                    debug.println("Warning: skipping PKCS#7 encryptedData" + " content-type - no password was supplied");
                }
                continue;
            }
            if (debug != null) {
                debug.println("Loading PKCS#7 encryptedData content-type");
            }
            DerInputStream edi = safeContents.getContent().toDerInputStream();
            int edVersion = edi.getInteger();
            DerValue[] seq = edi.getSequence(2);
            ObjectIdentifier edContentType = seq[0].getOID();
            eAlgId = seq[1].toByteArray();
            if (!seq[2].isContextSpecific((byte) 0)) {
                throw new IOException("encrypted content not present!");
            }
            byte newTag = DerValue.tag_OctetString;
            if (seq[2].isConstructed())
                newTag |= 0x20;
            seq[2].resetTag(newTag);
            safeContentsData = seq[2].getOctetString();
            // parse Algorithm parameters
            DerInputStream in = seq[1].toDerInputStream();
            ObjectIdentifier algOid = in.getOID();
            AlgorithmParameters algParams = parseAlgParameters(algOid, in);
            while (true) {
                try {
                    // Use JCE
                    SecretKey skey = getPBEKey(password);
                    Cipher cipher = Cipher.getInstance(algOid.toString());
                    cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
                    safeContentsData = cipher.doFinal(safeContentsData);
                    break;
                } catch (Exception e) {
                    if (password.length == 0) {
                        // Retry using an empty password
                        // without a NULL terminator.
                        password = new char[1];
                        continue;
                    }
                    throw new IOException("keystore password was incorrect", new UnrecoverableKeyException("failed to decrypt safe contents entry: " + e));
                }
            }
        } else {
            throw new IOException("public key protected PKCS12" + " not supported");
        }
        DerInputStream sc = new DerInputStream(safeContentsData);
        loadSafeContents(sc, password);
    }
    // The MacData is optional.
    if (password != null && s.available() > 0) {
        MacData macData = new MacData(s);
        try {
            String algName = macData.getDigestAlgName().toUpperCase(Locale.ENGLISH);
            // Change SHA-1 to SHA1
            algName = algName.replace("-", "");
            // generate MAC (MAC key is created within JCE)
            Mac m = Mac.getInstance("HmacPBE" + algName);
            PBEParameterSpec params = new PBEParameterSpec(macData.getSalt(), macData.getIterations());
            SecretKey key = getPBEKey(password);
            m.init(key, params);
            m.update(authSafeData);
            byte[] macResult = m.doFinal();
            if (debug != null) {
                debug.println("Checking keystore integrity " + "(MAC algorithm: " + m.getAlgorithm() + ")");
            }
            if (!MessageDigest.isEqual(macData.getDigest(), macResult)) {
                throw new UnrecoverableKeyException("Failed PKCS12" + " integrity checking");
            }
        } catch (Exception e) {
            throw new IOException("Integrity check failed: " + e, e);
        }
    }
    /*
         * Match up private keys with certificate chains.
         */
    PrivateKeyEntry[] list = keyList.toArray(new PrivateKeyEntry[keyList.size()]);
    for (int m = 0; m < list.length; m++) {
        PrivateKeyEntry entry = list[m];
        if (entry.keyId != null) {
            ArrayList<X509Certificate> chain = new ArrayList<X509Certificate>();
            X509Certificate cert = findMatchedCertificate(entry);
            mainloop: while (cert != null) {
                // Check for loops in the certificate chain
                if (!chain.isEmpty()) {
                    for (X509Certificate chainCert : chain) {
                        if (cert.equals(chainCert)) {
                            if (debug != null) {
                                debug.println("Loop detected in " + "certificate chain. Skip adding " + "repeated cert to chain. Subject: " + cert.getSubjectX500Principal().toString());
                            }
                            break mainloop;
                        }
                    }
                }
                chain.add(cert);
                X500Principal issuerDN = cert.getIssuerX500Principal();
                if (issuerDN.equals(cert.getSubjectX500Principal())) {
                    break;
                }
                cert = certsMap.get(issuerDN);
            }
            /* Update existing KeyEntry in entries table */
            if (chain.size() > 0)
                entry.chain = chain.toArray(new Certificate[chain.size()]);
        }
    }
    if (debug != null) {
        if (privateKeyCount > 0) {
            debug.println("Loaded " + privateKeyCount + " protected private key(s)");
        }
        if (secretKeyCount > 0) {
            debug.println("Loaded " + secretKeyCount + " protected secret key(s)");
        }
        if (certificateCount > 0) {
            debug.println("Loaded " + certificateCount + " certificate(s)");
        }
    }
    certEntries.clear();
    certsMap.clear();
    keyList.clear();
}
Also used : CertificateFactory(java.security.cert.CertificateFactory) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ContentInfo(sun.security.pkcs.ContentInfo) DerValue(sun.security.util.DerValue) DerInputStream(sun.security.util.DerInputStream) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) ObjectIdentifier(sun.security.util.ObjectIdentifier) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) DestroyFailedException(javax.security.auth.DestroyFailedException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Mac(javax.crypto.Mac) X509Certificate(java.security.cert.X509Certificate) SecretKey(javax.crypto.SecretKey) X500Principal(javax.security.auth.x500.X500Principal) Cipher(javax.crypto.Cipher) AlgorithmParameters(java.security.AlgorithmParameters)

Aggregations

DerInputStream (sun.security.util.DerInputStream)38 DerValue (sun.security.util.DerValue)16 IOException (java.io.IOException)12 ObjectIdentifier (sun.security.util.ObjectIdentifier)10 X509CertSelector (java.security.cert.X509CertSelector)6 BigInteger (java.math.BigInteger)5 CertificateException (java.security.cert.CertificateException)4 CertificateFactory (java.security.cert.CertificateFactory)4 X509Certificate (java.security.cert.X509Certificate)4 X500Principal (javax.security.auth.x500.X500Principal)4 SocketException (java.net.SocketException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 UnrecoverableEntryException (java.security.UnrecoverableEntryException)3 UnrecoverableKeyException (java.security.UnrecoverableKeyException)3 DestroyFailedException (javax.security.auth.DestroyFailedException)3 AlgorithmParameters (java.security.AlgorithmParameters)2 InvalidKeyException (java.security.InvalidKeyException)2 KeyFactory (java.security.KeyFactory)2 Date (java.util.Date)2