Search in sources :

Example 16 with AlgorithmId

use of sun.security.x509.AlgorithmId in project atlas by alibaba.

the class SignedJarBuilder method writeSignatureBlock.

/**
     * Write the certificate file with a digital signature.
     */
private void writeSignatureBlock(Signature signature, X509Certificate publicKey, PrivateKey privateKey) throws IOException, GeneralSecurityException {
    SignerInfo signerInfo = new SignerInfo(new X500Name(publicKey.getIssuerX500Principal().getName()), publicKey.getSerialNumber(), AlgorithmId.get(DIGEST_ALGORITHM), AlgorithmId.get(privateKey.getAlgorithm()), signature.sign());
    PKCS7 pkcs7 = new PKCS7(new AlgorithmId[] { AlgorithmId.get(DIGEST_ALGORITHM) }, new ContentInfo(ContentInfo.DATA_OID, null), new X509Certificate[] { publicKey }, new SignerInfo[] { signerInfo });
    pkcs7.encodeSignedData(mOutputJar);
}
Also used : SignerInfo(sun.security.pkcs.SignerInfo) ContentInfo(sun.security.pkcs.ContentInfo) PKCS7(sun.security.pkcs.PKCS7) X500Name(sun.security.x509.X500Name)

Example 17 with AlgorithmId

use of sun.security.x509.AlgorithmId in project jdk8u_jdk by JetBrains.

the class CipherForKeyProtector method recover.

/*
     * Recovers the cleartext version of the given key (in protected format),
     * using the password provided at construction time.
     */
Key recover(EncryptedPrivateKeyInfo encrInfo) throws UnrecoverableKeyException, NoSuchAlgorithmException {
    byte[] plain;
    try {
        String encrAlg = encrInfo.getAlgorithm().getOID().toString();
        if (!encrAlg.equals(PBE_WITH_MD5_AND_DES3_CBC_OID) && !encrAlg.equals(KEY_PROTECTOR_OID)) {
            throw new UnrecoverableKeyException("Unsupported encryption " + "algorithm");
        }
        if (encrAlg.equals(KEY_PROTECTOR_OID)) {
            // JDK 1.2 style recovery
            plain = recover(encrInfo.getEncryptedData());
        } else {
            byte[] encodedParams = encrInfo.getAlgorithm().getEncodedParams();
            // parse the PBE parameters into the corresponding spec
            AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE");
            pbeParams.init(encodedParams);
            PBEParameterSpec pbeSpec = pbeParams.getParameterSpec(PBEParameterSpec.class);
            // create PBE key from password
            PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
            SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
            pbeKeySpec.clearPassword();
            // decrypt private key
            PBEWithMD5AndTripleDESCipher cipher;
            cipher = new PBEWithMD5AndTripleDESCipher();
            cipher.engineInit(Cipher.DECRYPT_MODE, sKey, pbeSpec, null);
            plain = cipher.engineDoFinal(encrInfo.getEncryptedData(), 0, encrInfo.getEncryptedData().length);
        }
        // determine the private-key algorithm, and parse private key
        // using the appropriate key factory
        String oidName = new AlgorithmId(new PrivateKeyInfo(plain).getAlgorithm().getOID()).getName();
        KeyFactory kFac = KeyFactory.getInstance(oidName);
        return kFac.generatePrivate(new PKCS8EncodedKeySpec(plain));
    } catch (NoSuchAlgorithmException ex) {
        // later catch of GeneralSecurityException
        throw ex;
    } catch (IOException ioe) {
        throw new UnrecoverableKeyException(ioe.getMessage());
    } catch (GeneralSecurityException gse) {
        throw new UnrecoverableKeyException(gse.getMessage());
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) SecretKey(javax.crypto.SecretKey) UnrecoverableKeyException(java.security.UnrecoverableKeyException) AlgorithmId(sun.security.x509.AlgorithmId) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyFactory(java.security.KeyFactory) AlgorithmParameters(java.security.AlgorithmParameters)

Example 18 with AlgorithmId

use of sun.security.x509.AlgorithmId in project jdk8u_jdk by JetBrains.

the class CipherForKeyProtector method protect.

/**
     * Protects the given cleartext private key, using the password provided at
     * construction time.
     */
byte[] protect(PrivateKey key) throws Exception {
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);
    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);
    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();
    // encrypt private key
    PBEWithMD5AndTripleDESCipher cipher;
    cipher = new PBEWithMD5AndTripleDESCipher();
    cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null);
    byte[] plain = key.getEncoded();
    byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length);
    // wrap encrypted private key in EncryptedPrivateKeyInfo
    // (as defined in PKCS#8)
    AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance());
    pbeParams.init(pbeSpec);
    AlgorithmId encrAlg = new AlgorithmId(new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams);
    return new EncryptedPrivateKeyInfo(encrAlg, encrKey).getEncoded();
}
Also used : SecretKey(javax.crypto.SecretKey) AlgorithmId(sun.security.x509.AlgorithmId) AlgorithmParameters(java.security.AlgorithmParameters) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 19 with AlgorithmId

use of sun.security.x509.AlgorithmId in project jdk8u_jdk by JetBrains.

the class PKCS12KeyStore method setKeyEntry.

/*
     * Sets a key entry (with attributes, when present)
     */
private void setKeyEntry(String alias, Key key, KeyStore.PasswordProtection passwordProtection, Certificate[] chain, Set<KeyStore.Entry.Attribute> attributes) throws KeyStoreException {
    try {
        Entry entry;
        if (key instanceof PrivateKey) {
            PrivateKeyEntry keyEntry = new PrivateKeyEntry();
            keyEntry.date = new Date();
            if ((key.getFormat().equals("PKCS#8")) || (key.getFormat().equals("PKCS8"))) {
                if (debug != null) {
                    debug.println("Setting a protected private key (" + key.getClass().getName() + ") at alias '" + alias + "'");
                }
                // Encrypt the private key
                keyEntry.protectedPrivKey = encryptPrivateKey(key.getEncoded(), passwordProtection);
            } else {
                throw new KeyStoreException("Private key is not encoded" + "as PKCS#8");
            }
            // clone the chain
            if (chain != null) {
                // validate cert-chain
                if ((chain.length > 1) && (!validateChain(chain)))
                    throw new KeyStoreException("Certificate chain is " + "not valid");
                keyEntry.chain = chain.clone();
                certificateCount += chain.length;
                if (debug != null) {
                    debug.println("Setting a " + chain.length + "-certificate chain at alias '" + alias + "'");
                }
            }
            privateKeyCount++;
            entry = keyEntry;
        } else if (key instanceof SecretKey) {
            SecretKeyEntry keyEntry = new SecretKeyEntry();
            keyEntry.date = new Date();
            // Encode secret key in a PKCS#8
            DerOutputStream pkcs8 = new DerOutputStream();
            DerOutputStream secretKeyInfo = new DerOutputStream();
            secretKeyInfo.putInteger(0);
            AlgorithmId algId = AlgorithmId.get(key.getAlgorithm());
            algId.encode(secretKeyInfo);
            secretKeyInfo.putOctetString(key.getEncoded());
            pkcs8.write(DerValue.tag_Sequence, secretKeyInfo);
            // Encrypt the secret key (using same PBE as for private keys)
            keyEntry.protectedSecretKey = encryptPrivateKey(pkcs8.toByteArray(), passwordProtection);
            if (debug != null) {
                debug.println("Setting a protected secret key (" + key.getClass().getName() + ") at alias '" + alias + "'");
            }
            secretKeyCount++;
            entry = keyEntry;
        } else {
            throw new KeyStoreException("Unsupported Key type");
        }
        entry.attributes = new HashSet<>();
        if (attributes != null) {
            entry.attributes.addAll(attributes);
        }
        // set the keyId to current date
        entry.keyId = ("Time " + (entry.date).getTime()).getBytes("UTF8");
        // set the alias
        entry.alias = alias.toLowerCase(Locale.ENGLISH);
        // add the entry
        entries.put(alias.toLowerCase(Locale.ENGLISH), entry);
    } catch (Exception nsae) {
        throw new KeyStoreException("Key protection " + " algorithm not found: " + nsae, nsae);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) PrivateKey(java.security.PrivateKey) DerOutputStream(sun.security.util.DerOutputStream) AlgorithmId(sun.security.x509.AlgorithmId) KeyStoreException(java.security.KeyStoreException) 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)

Example 20 with AlgorithmId

use of sun.security.x509.AlgorithmId in project jdk8u_jdk by JetBrains.

the class PKCS12KeyStore method engineGetKey.

/**
     * Returns the key associated with the given alias, using the given
     * password to recover it.
     *
     * @param alias the alias name
     * @param password the password for recovering the key
     *
     * @return the requested key, or null if the given alias does not exist
     * or does not identify a <i>key entry</i>.
     *
     * @exception NoSuchAlgorithmException if the algorithm for recovering the
     * key cannot be found
     * @exception UnrecoverableKeyException if the key cannot be recovered
     * (e.g., the given password is wrong).
     */
public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException {
    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    Key key = null;
    if (entry == null || (!(entry instanceof KeyEntry))) {
        return null;
    }
    // get the encoded private key or secret key
    byte[] encrBytes = null;
    if (entry instanceof PrivateKeyEntry) {
        encrBytes = ((PrivateKeyEntry) entry).protectedPrivKey;
    } else if (entry instanceof SecretKeyEntry) {
        encrBytes = ((SecretKeyEntry) entry).protectedSecretKey;
    } else {
        throw new UnrecoverableKeyException("Error locating key");
    }
    byte[] encryptedKey;
    AlgorithmParameters algParams;
    ObjectIdentifier algOid;
    try {
        // get the encrypted private key
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(encrBytes);
        encryptedKey = encrInfo.getEncryptedData();
        // parse Algorithm parameters
        DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
        DerInputStream in = val.toDerInputStream();
        algOid = in.getOID();
        algParams = parseAlgParameters(algOid, in);
    } catch (IOException ioe) {
        UnrecoverableKeyException uke = new UnrecoverableKeyException("Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
        uke.initCause(ioe);
        throw uke;
    }
    try {
        byte[] keyInfo;
        while (true) {
            try {
                // Use JCE
                SecretKey skey = getPBEKey(password);
                Cipher cipher = Cipher.getInstance(mapPBEParamsToAlgorithm(algOid, algParams));
                cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
                keyInfo = cipher.doFinal(encryptedKey);
                break;
            } catch (Exception e) {
                if (password.length == 0) {
                    // Retry using an empty password
                    // without a NULL terminator.
                    password = new char[1];
                    continue;
                }
                throw e;
            }
        }
        /*
             * Parse the key algorithm and then use a JCA key factory
             * to re-create the key.
             */
        DerValue val = new DerValue(keyInfo);
        DerInputStream in = val.toDerInputStream();
        int i = in.getInteger();
        DerValue[] value = in.getSequence(2);
        AlgorithmId algId = new AlgorithmId(value[0].getOID());
        String keyAlgo = algId.getName();
        // decode private key
        if (entry instanceof PrivateKeyEntry) {
            KeyFactory kfac = KeyFactory.getInstance(keyAlgo);
            PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(keyInfo);
            key = kfac.generatePrivate(kspec);
            if (debug != null) {
                debug.println("Retrieved a protected private key (" + key.getClass().getName() + ") at alias '" + alias + "'");
            }
        // decode secret key
        } else {
            byte[] keyBytes = in.getOctetString();
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, keyAlgo);
            // Special handling required for PBE: needs a PBEKeySpec
            if (keyAlgo.startsWith("PBE")) {
                SecretKeyFactory sKeyFactory = SecretKeyFactory.getInstance(keyAlgo);
                KeySpec pbeKeySpec = sKeyFactory.getKeySpec(secretKeySpec, PBEKeySpec.class);
                key = sKeyFactory.generateSecret(pbeKeySpec);
            } else {
                key = secretKeySpec;
            }
            if (debug != null) {
                debug.println("Retrieved a protected secret key (" + key.getClass().getName() + ") at alias '" + alias + "'");
            }
        }
    } catch (Exception e) {
        UnrecoverableKeyException uke = new UnrecoverableKeyException("Get Key failed: " + e.getMessage());
        uke.initCause(e);
        throw uke;
    }
    return key;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeySpec(java.security.spec.KeySpec) PBEKeySpec(javax.crypto.spec.PBEKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) DerValue(sun.security.util.DerValue) DerInputStream(sun.security.util.DerInputStream) SecretKeyFactory(javax.crypto.SecretKeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory) 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) SecretKey(javax.crypto.SecretKey) AlgorithmId(sun.security.x509.AlgorithmId) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(sun.security.pkcs.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) AlgorithmParameters(java.security.AlgorithmParameters)

Aggregations

AlgorithmId (sun.security.x509.AlgorithmId)24 CertificateException (java.security.cert.CertificateException)10 X500Name (sun.security.x509.X500Name)10 X509CertImpl (sun.security.x509.X509CertImpl)9 AlgorithmParameters (java.security.AlgorithmParameters)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 X509Certificate (java.security.cert.X509Certificate)7 SecretKey (javax.crypto.SecretKey)7 IOException (java.io.IOException)6 BigInteger (java.math.BigInteger)6 UnrecoverableKeyException (java.security.UnrecoverableKeyException)6 ObjectIdentifier (sun.security.util.ObjectIdentifier)6 CertificateAlgorithmId (sun.security.x509.CertificateAlgorithmId)6 KeyStoreException (java.security.KeyStoreException)5 CertificateFactory (java.security.cert.CertificateFactory)5 ContentInfo (sun.security.pkcs.ContentInfo)5 PKCS7 (sun.security.pkcs.PKCS7)5 SignerInfo (sun.security.pkcs.SignerInfo)5 PrivateKey (java.security.PrivateKey)4 UnrecoverableEntryException (java.security.UnrecoverableEntryException)4