Search in sources :

Example 66 with SecretKey

use of javax.crypto.SecretKey in project android_frameworks_base by ResurrectionRemix.

the class SystemKeyStore method generateNewKey.

public byte[] generateNewKey(int numBits, String algName, String keyName) throws NoSuchAlgorithmException {
    // Check if key with similar name exists. If so, return null.
    File keyFile = getKeyFile(keyName);
    if (keyFile.exists()) {
        throw new IllegalArgumentException();
    }
    KeyGenerator skg = KeyGenerator.getInstance(algName);
    SecureRandom srng = SecureRandom.getInstance("SHA1PRNG");
    skg.init(numBits, srng);
    SecretKey sk = skg.generateKey();
    byte[] retKey = sk.getEncoded();
    try {
        // Store the key
        if (!keyFile.createNewFile()) {
            throw new IllegalArgumentException();
        }
        FileOutputStream fos = new FileOutputStream(keyFile);
        fos.write(retKey);
        fos.flush();
        FileUtils.sync(fos);
        fos.close();
        FileUtils.setPermissions(keyFile.getName(), (FileUtils.S_IRUSR | FileUtils.S_IWUSR), -1, -1);
    } catch (IOException ioe) {
        return null;
    }
    return retKey;
}
Also used : SecretKey(javax.crypto.SecretKey) FileOutputStream(java.io.FileOutputStream) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) File(java.io.File) KeyGenerator(javax.crypto.KeyGenerator)

Example 67 with SecretKey

use of javax.crypto.SecretKey in project android_frameworks_base by ResurrectionRemix.

the class AndroidKeyStoreCipherSpiBase method engineWrap.

@Override
protected final byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {
    if (mKey == null) {
        throw new IllegalStateException("Not initilized");
    }
    if (!isEncrypting()) {
        throw new IllegalStateException("Cipher must be initialized in Cipher.WRAP_MODE to wrap keys");
    }
    if (key == null) {
        throw new NullPointerException("key == null");
    }
    byte[] encoded = null;
    if (key instanceof SecretKey) {
        if ("RAW".equalsIgnoreCase(key.getFormat())) {
            encoded = key.getEncoded();
        }
        if (encoded == null) {
            try {
                SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(key.getAlgorithm());
                SecretKeySpec spec = (SecretKeySpec) keyFactory.getKeySpec((SecretKey) key, SecretKeySpec.class);
                encoded = spec.getEncoded();
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
            }
        }
    } else if (key instanceof PrivateKey) {
        if ("PKCS8".equalsIgnoreCase(key.getFormat())) {
            encoded = key.getEncoded();
        }
        if (encoded == null) {
            try {
                KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class);
                encoded = spec.getEncoded();
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
            }
        }
    } else if (key instanceof PublicKey) {
        if ("X.509".equalsIgnoreCase(key.getFormat())) {
            encoded = key.getEncoded();
        }
        if (encoded == null) {
            try {
                KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class);
                encoded = spec.getEncoded();
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
            }
        }
    } else {
        throw new InvalidKeyException("Unsupported key type: " + key.getClass().getName());
    }
    if (encoded == null) {
        throw new InvalidKeyException("Failed to wrap key because it does not export its key material");
    }
    try {
        return engineDoFinal(encoded, 0, encoded.length);
    } catch (BadPaddingException e) {
        throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SecretKeyFactory(javax.crypto.SecretKeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory)

Example 68 with SecretKey

use of javax.crypto.SecretKey in project OpenAM by OpenRock.

the class DataEncryptor method encryptWithAsymmetricKey.

/**
     * Encrypts the given data with an asymmetric key. The asymmetric 
     * encryption uses symmetric secret key for data encryption and sends
     * the secret key to the recipient by encrypting the same with given
     * transport key (publick key). 
     * @param data the data to be encrypted.
     * @param encryptionAlgorithm the encryption algorithm to be used.
     *        The encryption algorithm must be one of the supported
     *        algorithm by the underlying JCE encryption provider.
     *        Examples of encryption algorithms are "DES", "AES" etc. 
     * @param encryptionStrength the encryption strength for a given
     *                           encryption algorithm.
     * @param encKey the encryption key to be used. For PKI, this
     *               key should be public key of the intended recipient.  
     * @return the encrypted data in Base64 encoded format.
     */
public static String encryptWithAsymmetricKey(String data, String encryptionAlgorithm, int encryptionStrength, Key encKey) throws Exception {
    try {
        KeyGenerator keygen = KeyGenerator.getInstance(encryptionAlgorithm);
        if (encryptionStrength != 0) {
            keygen.init(encryptionStrength);
        }
        SecretKey sKey = keygen.generateKey();
        Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
        cipher.init(Cipher.ENCRYPT_MODE, sKey);
        byte[] encData = cipher.doFinal(data.getBytes("UTF-8"));
        cipher = Cipher.getInstance(encKey.getAlgorithm());
        cipher.init(Cipher.WRAP_MODE, encKey);
        byte[] keyWrap = cipher.wrap(sKey);
        byte[] encDataPad = wrapKeyWithEncryptedData(encData, keyWrap);
        return Base64.encode(encDataPad);
    } catch (NoSuchAlgorithmException nse) {
        throw new Exception(nse.getMessage());
    } catch (NoSuchPaddingException npe) {
        throw new Exception(npe.getMessage());
    } catch (InvalidKeyException ike) {
        throw new Exception(ike.getMessage());
    } catch (UnsupportedEncodingException uae) {
        throw new Exception(uae.getMessage());
    }
}
Also used : SecretKey(javax.crypto.SecretKey) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) KeyGenerator(javax.crypto.KeyGenerator) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 69 with SecretKey

use of javax.crypto.SecretKey in project OpenAM by OpenRock.

the class DataEncryptor method decryptWithSymmetricKey.

/**
     * Decrypts the given data with a symmetric key generated using shared
     * secret.
     * @param data the data to be decrypted with symmetric key.
     * @param encAlgorithm the encryption algorithm was used for
     *        encrypting the data.
     * @param secret the shared secret to be used for decrypting the data.
     * @return the decrypted data. 
     */
public static String decryptWithSymmetricKey(String data, String encAlgorithm, String secret) throws Exception {
    try {
        String algorithm = encAlgorithm;
        if (!algorithm.startsWith("PBEWith")) {
            algorithm = "PBEWithMD5And" + encAlgorithm;
        }
        SecretKeyFactory skFactory = SecretKeyFactory.getInstance(algorithm);
        PBEKeySpec pbeKeySpec = new PBEKeySpec(secret.toCharArray());
        SecretKey sKey = skFactory.generateSecret(pbeKeySpec);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, sKey, pbeParameterSpec);
        byte[] tmp = Base64.decode(data);
        byte[] encData = removePrefix(tmp);
        byte[] decData = cipher.doFinal(encData);
        return Base64.encode(decData);
    } catch (NoSuchAlgorithmException nse) {
        throw new Exception(nse.getMessage());
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKeyFactory(javax.crypto.SecretKeyFactory) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 70 with SecretKey

use of javax.crypto.SecretKey in project android_frameworks_base by ResurrectionRemix.

the class AndroidKeyStoreKeyGeneratorSpi method engineGenerateKey.

@Override
protected SecretKey engineGenerateKey() {
    KeyGenParameterSpec spec = mSpec;
    if (spec == null) {
        throw new IllegalStateException("Not initialized");
    }
    KeymasterArguments args = new KeymasterArguments();
    args.addUnsignedInt(KeymasterDefs.KM_TAG_KEY_SIZE, mKeySizeBits);
    args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, mKeymasterAlgorithm);
    args.addEnums(KeymasterDefs.KM_TAG_PURPOSE, mKeymasterPurposes);
    args.addEnums(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockModes);
    args.addEnums(KeymasterDefs.KM_TAG_PADDING, mKeymasterPaddings);
    args.addEnums(KeymasterDefs.KM_TAG_DIGEST, mKeymasterDigests);
    KeymasterUtils.addUserAuthArgs(args, spec.isUserAuthenticationRequired(), spec.getUserAuthenticationValidityDurationSeconds(), spec.isUserAuthenticationValidWhileOnBody(), spec.isInvalidatedByBiometricEnrollment());
    KeymasterUtils.addMinMacLengthAuthorizationIfNecessary(args, mKeymasterAlgorithm, mKeymasterBlockModes, mKeymasterDigests);
    args.addDateIfNotNull(KeymasterDefs.KM_TAG_ACTIVE_DATETIME, spec.getKeyValidityStart());
    args.addDateIfNotNull(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME, spec.getKeyValidityForOriginationEnd());
    args.addDateIfNotNull(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME, spec.getKeyValidityForConsumptionEnd());
    if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) && (!spec.isRandomizedEncryptionRequired())) {
        // Permit caller-provided IV when encrypting with this key
        args.addBoolean(KeymasterDefs.KM_TAG_CALLER_NONCE);
    }
    byte[] additionalEntropy = KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng(mRng, (mKeySizeBits + 7) / 8);
    int flags = 0;
    String keyAliasInKeystore = Credentials.USER_SECRET_KEY + spec.getKeystoreAlias();
    KeyCharacteristics resultingKeyCharacteristics = new KeyCharacteristics();
    boolean success = false;
    try {
        Credentials.deleteAllTypesForAlias(mKeyStore, spec.getKeystoreAlias(), spec.getUid());
        int errorCode = mKeyStore.generateKey(keyAliasInKeystore, args, additionalEntropy, spec.getUid(), flags, resultingKeyCharacteristics);
        if (errorCode != KeyStore.NO_ERROR) {
            throw new ProviderException("Keystore operation failed", KeyStore.getKeyStoreException(errorCode));
        }
        @KeyProperties.KeyAlgorithmEnum String keyAlgorithmJCA;
        try {
            keyAlgorithmJCA = KeyProperties.KeyAlgorithm.fromKeymasterSecretKeyAlgorithm(mKeymasterAlgorithm, mKeymasterDigest);
        } catch (IllegalArgumentException e) {
            throw new ProviderException("Failed to obtain JCA secret key algorithm name", e);
        }
        SecretKey result = new AndroidKeyStoreSecretKey(keyAliasInKeystore, spec.getUid(), keyAlgorithmJCA);
        success = true;
        return result;
    } finally {
        if (!success) {
            Credentials.deleteAllTypesForAlias(mKeyStore, spec.getKeystoreAlias(), spec.getUid());
        }
    }
}
Also used : KeymasterArguments(android.security.keymaster.KeymasterArguments) KeyGenParameterSpec(android.security.keystore.KeyGenParameterSpec) ProviderException(java.security.ProviderException) SecretKey(javax.crypto.SecretKey) KeyCharacteristics(android.security.keymaster.KeyCharacteristics)

Aggregations

SecretKey (javax.crypto.SecretKey)491 Cipher (javax.crypto.Cipher)176 SecretKeySpec (javax.crypto.spec.SecretKeySpec)141 KeyGenerator (javax.crypto.KeyGenerator)121 SecretKeyFactory (javax.crypto.SecretKeyFactory)89 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)87 SecureRandom (java.security.SecureRandom)61 InvalidKeyException (java.security.InvalidKeyException)58 PBEKeySpec (javax.crypto.spec.PBEKeySpec)58 IvParameterSpec (javax.crypto.spec.IvParameterSpec)46 IOException (java.io.IOException)44 Test (org.junit.Test)40 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)35 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)34 KeyStore (java.security.KeyStore)32 PrivateKey (java.security.PrivateKey)30 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)30 KeyStoreException (java.security.KeyStoreException)29 BadPaddingException (javax.crypto.BadPaddingException)29 Mac (javax.crypto.Mac)29