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;
}
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);
}
}
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());
}
}
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());
}
}
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());
}
}
}
Aggregations