use of javax.crypto.KeyGenerator in project jdk8u_jdk by JetBrains.
the class P12SecretKey method run.
private void run(String keystoreType) throws Exception {
char[] pw = "password".toCharArray();
KeyStore ks = KeyStore.getInstance(keystoreType);
ks.load(null, pw);
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
SecretKey key = kg.generateKey();
KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);
KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);
ks.setEntry(ALIAS, ske, kspp);
File ksFile = File.createTempFile("test", ".test");
try (FileOutputStream fos = new FileOutputStream(ksFile)) {
ks.store(fos, pw);
fos.flush();
}
// now see if we can get it back
try (FileInputStream fis = new FileInputStream(ksFile)) {
KeyStore ks2 = KeyStore.getInstance(keystoreType);
ks2.load(fis, pw);
KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);
SecretKey keyIn = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {
System.err.println("OK: worked just fine with " + keystoreType + " keystore");
} else {
System.err.println("ERROR: keys are NOT equal after storing in " + keystoreType + " keystore");
}
}
}
use of javax.crypto.KeyGenerator in project android_frameworks_base by AOSPA.
the class LockSettingsService method tieProfileLockToParent.
private void tieProfileLockToParent(int userId, String password) {
if (DEBUG)
Slog.v(TAG, "tieProfileLockToParent for user: " + userId);
byte[] randomLockSeed = password.getBytes(StandardCharsets.UTF_8);
byte[] encryptionResult;
byte[] iv;
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES);
keyGenerator.init(new SecureRandom());
SecretKey secretKey = keyGenerator.generateKey();
java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
try {
keyStore.setEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId, new java.security.KeyStore.SecretKeyEntry(secretKey), new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build());
keyStore.setEntry(LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + userId, new java.security.KeyStore.SecretKeyEntry(secretKey), new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).setUserAuthenticationRequired(true).setUserAuthenticationValidityDurationSeconds(30).build());
// Key imported, obtain a reference to it.
SecretKey keyStoreEncryptionKey = (SecretKey) keyStore.getKey(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId, null);
Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/" + KeyProperties.ENCRYPTION_PADDING_NONE);
cipher.init(Cipher.ENCRYPT_MODE, keyStoreEncryptionKey);
encryptionResult = cipher.doFinal(randomLockSeed);
iv = cipher.getIV();
} finally {
// The original key can now be discarded.
keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId);
}
} catch (CertificateException | UnrecoverableKeyException | IOException | BadPaddingException | IllegalBlockSizeException | KeyStoreException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Failed to encrypt key", e);
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
if (iv.length != PROFILE_KEY_IV_SIZE) {
throw new RuntimeException("Invalid iv length: " + iv.length);
}
outputStream.write(iv);
outputStream.write(encryptionResult);
} catch (IOException e) {
throw new RuntimeException("Failed to concatenate byte arrays", e);
}
mStorage.writeChildProfileLock(userId, outputStream.toByteArray());
}
use of javax.crypto.KeyGenerator in project cxf by apache.
the class StaxSymmetricBindingHandler method setupEncryptedKey.
private String setupEncryptedKey(AbstractTokenWrapper wrapper, AbstractToken sigToken) throws WSSecurityException {
Instant created = Instant.now();
Instant expires = created.plusSeconds(WSS4JUtils.getSecurityTokenLifetime(message) / 1000L);
SecurityToken tempTok = new SecurityToken(IDGenerator.generateID(null), created, expires);
KeyGenerator keyGenerator = KeyUtils.getKeyGenerator(sbinding.getAlgorithmSuite().getAlgorithmSuiteType().getEncryption());
SecretKey symmetricKey = keyGenerator.generateKey();
tempTok.setKey(symmetricKey);
tempTok.setSecret(symmetricKey.getEncoded());
TokenStoreUtils.getTokenStore(message).add(tempTok);
return tempTok.getId();
}
use of javax.crypto.KeyGenerator in project carbon-apimgt by wso2.
the class FileEncryptionUtility method createAndStoreAESKey.
/**
* Creates and stores an AES key
*
* @throws APIManagementException if an error occurs while creating or storing AES key
*/
void createAndStoreAESKey() throws APIManagementException {
try {
// create a new AES key
KeyGenerator keyGenerator = KeyGenerator.getInstance(EncryptionConstants.AES);
keyGenerator.init(AES_Key_Size);
byte[] aesKey = keyGenerator.generateKey().getEncoded();
// store key => encrypt -> encode -> chars -> string
byte[] encryptedKeyBytes = SecureVaultUtils.base64Encode(getSecureVault().encrypt(aesKey));
String encryptedKeyString = new String(SecureVaultUtils.toChars(encryptedKeyBytes));
Files.deleteIfExists(Paths.get(getAesKeyFileLocation()));
APIFileUtils.createFile(getAesKeyFileLocation());
APIFileUtils.writeToFile(getAesKeyFileLocation(), encryptedKeyString);
log.debug("AES key successfully created and stored");
} catch (NoSuchAlgorithmException | SecureVaultException | APIMgtDAOException | IOException e) {
String msg = "Error while creating or storing created AES key";
throw new APIManagementException(msg, e);
}
}
use of javax.crypto.KeyGenerator in project jaffa-framework by jaffa-projects.
the class EncryptionHelper method main.
/**
* This method can be used from the command line for creating a Secret Key.
* @param args the command line arguments
* Requires one mandatory parameter, which is the file name to use to write out the SecretKey
*/
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Missing Parameter. Please supply the filename for writing out the SecretKey");
return;
}
File f = new File(args[0]);
if (f.exists())
System.out.println("Warning: Existing File Will Be Replaced.");
try {
// Create Key
KeyGenerator kg = KeyGenerator.getInstance("DES");
SecretKey secretKey = kg.generateKey();
// Convert to Raw bytearray for storage
byte[] rawsecretKey = secretKey.getEncoded();
// Write the newly generated key to a file.
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(secretKey);
oos.flush();
oos.close();
fos.close();
} catch (NoSuchAlgorithmException e) {
System.err.println("Invalid Algorithm : " + e.getMessage());
} catch (IOException e) {
System.err.println("Error Writing Out Key : " + e.getMessage());
}
}
Aggregations