Search in sources :

Example 61 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory in project jdk8u_jdk by JetBrains.

the class DigestMD5Base method makeDesKeys.

/**
     * Create parity-adjusted keys suitable for DES / DESede encryption.
     *
     * @param input A non-null byte array containing key material for
     * DES / DESede.
     * @param desStrength A string specifying eithe a DES or a DESede key.
     * @return SecretKey An instance of either DESKeySpec or DESedeKeySpec.
     *
     * @throws NoSuchAlgorithmException if the either the DES or DESede
     * algorithms cannote be lodaed by JCE.
     * @throws InvalidKeyException if an invalid array of bytes is used
     * as a key for DES or DESede.
     * @throws InvalidKeySpecException in an invalid parameter is passed
     * to either te DESKeySpec of the DESedeKeySpec constructors.
     */
private static SecretKey makeDesKeys(byte[] input, String desStrength) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    // Generate first subkey using first 7 bytes
    byte[] subkey1 = addDesParity(input, 0, 7);
    KeySpec spec = null;
    SecretKeyFactory desFactory = SecretKeyFactory.getInstance(desStrength);
    switch(desStrength) {
        case "des":
            spec = new DESKeySpec(subkey1, 0);
            if (logger.isLoggable(Level.FINEST)) {
                traceOutput(DP_CLASS_NAME, "makeDesKeys", "DIGEST42:DES key input: ", input);
                traceOutput(DP_CLASS_NAME, "makeDesKeys", "DIGEST43:DES key parity-adjusted: ", subkey1);
                traceOutput(DP_CLASS_NAME, "makeDesKeys", "DIGEST44:DES key material: ", ((DESKeySpec) spec).getKey());
                logger.log(Level.FINEST, "DIGEST45: is parity-adjusted? {0}", Boolean.valueOf(DESKeySpec.isParityAdjusted(subkey1, 0)));
            }
            break;
        case "desede":
            // Generate second subkey using second 7 bytes
            byte[] subkey2 = addDesParity(input, 7, 7);
            // Construct 24-byte encryption-decryption-encryption sequence
            byte[] ede = new byte[subkey1.length * 2 + subkey2.length];
            System.arraycopy(subkey1, 0, ede, 0, subkey1.length);
            System.arraycopy(subkey2, 0, ede, subkey1.length, subkey2.length);
            System.arraycopy(subkey1, 0, ede, subkey1.length + subkey2.length, subkey1.length);
            spec = new DESedeKeySpec(ede, 0);
            if (logger.isLoggable(Level.FINEST)) {
                traceOutput(DP_CLASS_NAME, "makeDesKeys", "DIGEST46:3DES key input: ", input);
                traceOutput(DP_CLASS_NAME, "makeDesKeys", "DIGEST47:3DES key ede: ", ede);
                traceOutput(DP_CLASS_NAME, "makeDesKeys", "DIGEST48:3DES key material: ", ((DESedeKeySpec) spec).getKey());
                logger.log(Level.FINEST, "DIGEST49: is parity-adjusted? ", Boolean.valueOf(DESedeKeySpec.isParityAdjusted(ede, 0)));
            }
            break;
        default:
            throw new IllegalArgumentException("Invalid DES strength:" + desStrength);
    }
    return desFactory.generateSecret(spec);
}
Also used : DESKeySpec(javax.crypto.spec.DESKeySpec) SecretKeySpec(javax.crypto.spec.SecretKeySpec) DESedeKeySpec(javax.crypto.spec.DESedeKeySpec) KeySpec(java.security.spec.KeySpec) DESedeKeySpec(javax.crypto.spec.DESedeKeySpec) DESKeySpec(javax.crypto.spec.DESKeySpec) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 62 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory in project jdk8u_jdk by JetBrains.

the class Des method des_cksum.

/**
     * Encrypts the message blocks using DES CBC and output the
     * final block of 8-byte ciphertext.
     * @param ivec Initialization vector.
     * @param msg Input message as an byte array.
     * @param key DES key to encrypt the message.
     * @return the last block of ciphertext.
     *
     * @created by Yanni Zhang, Dec 6, 99.
     */
public static byte[] des_cksum(byte[] ivec, byte[] msg, byte[] key) throws KrbCryptoException {
    Cipher cipher = null;
    byte[] result = new byte[8];
    try {
        cipher = Cipher.getInstance("DES/CBC/NoPadding");
    } catch (Exception e) {
        KrbCryptoException ke = new KrbCryptoException("JCE provider may not be installed. " + e.getMessage());
        ke.initCause(e);
        throw ke;
    }
    IvParameterSpec params = new IvParameterSpec(ivec);
    SecretKeySpec skSpec = new SecretKeySpec(key, "DES");
    try {
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        // SecretKey sk = skf.generateSecret(skSpec);
        SecretKey sk = (SecretKey) skSpec;
        cipher.init(Cipher.ENCRYPT_MODE, sk, params);
        for (int i = 0; i < msg.length / 8; i++) {
            result = cipher.doFinal(msg, i * 8, 8);
            cipher.init(Cipher.ENCRYPT_MODE, sk, (new IvParameterSpec(result)));
        }
    } catch (GeneralSecurityException e) {
        KrbCryptoException ke = new KrbCryptoException(e.getMessage());
        ke.initCause(e);
        throw ke;
    }
    return result;
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) KrbCryptoException(sun.security.krb5.KrbCryptoException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) GeneralSecurityException(java.security.GeneralSecurityException) KrbCryptoException(sun.security.krb5.KrbCryptoException)

Example 63 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory in project jdk8u_jdk by JetBrains.

the class Des3DkCrypto method getCipher.

protected Cipher getCipher(byte[] key, byte[] ivec, int mode) throws GeneralSecurityException {
    // NoSuchAlgorithException
    SecretKeyFactory factory = SecretKeyFactory.getInstance("desede");
    // InvalidKeyException
    KeySpec spec = new DESedeKeySpec(key, 0);
    // InvalidKeySpecException
    SecretKey secretKey = factory.generateSecret(spec);
    // IV
    if (ivec == null) {
        ivec = ZERO_IV;
    }
    // NoSuchAlgorithmException, NoSuchPaddingException
    // NoSuchProviderException
    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
    IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);
    // InvalidKeyException, InvalidAlgorithParameterException
    cipher.init(mode, secretKey, encIv);
    return cipher;
}
Also used : SecretKey(javax.crypto.SecretKey) KeySpec(java.security.spec.KeySpec) DESKeySpec(javax.crypto.spec.DESKeySpec) SecretKeySpec(javax.crypto.spec.SecretKeySpec) DESedeKeySpec(javax.crypto.spec.DESedeKeySpec) DESedeKeySpec(javax.crypto.spec.DESedeKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 64 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory in project jdk8u_jdk by JetBrains.

the class Pair method doGenSecretKey.

/**
     * Creates a new secret key.
     */
private void doGenSecretKey(String alias, String keyAlgName, int keysize) throws Exception {
    if (alias == null) {
        alias = keyAlias;
    }
    if (keyStore.containsAlias(alias)) {
        MessageFormat form = new MessageFormat(rb.getString("Secret.key.not.generated.alias.alias.already.exists"));
        Object[] source = { alias };
        throw new Exception(form.format(source));
    }
    // Use the keystore's default PBE algorithm for entry protection
    boolean useDefaultPBEAlgorithm = true;
    SecretKey secKey = null;
    if (keyAlgName.toUpperCase(Locale.ENGLISH).startsWith("PBE")) {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");
        // User is prompted for PBE credential
        secKey = factory.generateSecret(new PBEKeySpec(promptForCredential()));
        // Check whether a specific PBE algorithm was specified
        if (!"PBE".equalsIgnoreCase(keyAlgName)) {
            useDefaultPBEAlgorithm = false;
        }
        if (verbose) {
            MessageFormat form = new MessageFormat(rb.getString("Generated.keyAlgName.secret.key"));
            Object[] source = { useDefaultPBEAlgorithm ? "PBE" : secKey.getAlgorithm() };
            System.err.println(form.format(source));
        }
    } else {
        KeyGenerator keygen = KeyGenerator.getInstance(keyAlgName);
        if (keysize == -1) {
            if ("DES".equalsIgnoreCase(keyAlgName)) {
                keysize = 56;
            } else if ("DESede".equalsIgnoreCase(keyAlgName)) {
                keysize = 168;
            } else {
                throw new Exception(rb.getString("Please.provide.keysize.for.secret.key.generation"));
            }
        }
        keygen.init(keysize);
        secKey = keygen.generateKey();
        if (verbose) {
            MessageFormat form = new MessageFormat(rb.getString("Generated.keysize.bit.keyAlgName.secret.key"));
            Object[] source = { new Integer(keysize), secKey.getAlgorithm() };
            System.err.println(form.format(source));
        }
    }
    if (keyPass == null) {
        keyPass = promptForKeyPass(alias, null, storePass);
    }
    if (useDefaultPBEAlgorithm) {
        keyStore.setKeyEntry(alias, secKey, keyPass, null);
    } else {
        keyStore.setEntry(alias, new KeyStore.SecretKeyEntry(secKey), new KeyStore.PasswordProtection(keyPass, keyAlgName, null));
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) MessageFormat(java.text.MessageFormat) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertStoreException(java.security.cert.CertStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) BigInteger(java.math.BigInteger) SecretKey(javax.crypto.SecretKey) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyGenerator(javax.crypto.KeyGenerator)

Example 65 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory in project jdk8u_jdk by JetBrains.

the class PBKDF2Wrapper method initCipher.

/**
     * Initiate the Cipher object for PBKDF2 algorithm using given "mode".
     *
     * @param mode Cipher mode: encrypt or decrypt
     * @return Cipher object for PBKDF2 algorithm
     * @throws GeneralSecurityException all security exceptions are thrown.
     */
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo);
    SecretKey key = keyFactory.generateSecret(pbeKeySpec);
    // get Cipher instance
    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider);
    cipher.init(mode, new SecretKeySpec(key.getEncoded(), KEY_ALGORITHM), new IvParameterSpec(iv));
    return cipher;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) Provider(java.security.Provider)

Aggregations

SecretKeyFactory (javax.crypto.SecretKeyFactory)129 SecretKey (javax.crypto.SecretKey)84 PBEKeySpec (javax.crypto.spec.PBEKeySpec)75 Cipher (javax.crypto.Cipher)58 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)39 DESKeySpec (javax.crypto.spec.DESKeySpec)28 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)26 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)26 KeySpec (java.security.spec.KeySpec)25 SecretKeySpec (javax.crypto.spec.SecretKeySpec)23 SecureRandom (java.security.SecureRandom)18 KeyStoreException (java.security.KeyStoreException)16 IOException (java.io.IOException)15 InvalidKeyException (java.security.InvalidKeyException)14 PrivateKey (java.security.PrivateKey)12 CertificateException (java.security.cert.CertificateException)12 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)12 UnrecoverableKeyException (java.security.UnrecoverableKeyException)11 Key (java.security.Key)10 KeyFactory (java.security.KeyFactory)10