use of javax.crypto.KeyGenerator in project hadoop by apache.
the class MRAppMaster method initJobCredentialsAndUGI.
// end createJob()
/**
* Obtain the tokens needed by the job and put them in the UGI
* @param conf
*/
protected void initJobCredentialsAndUGI(Configuration conf) {
try {
this.currentUser = UserGroupInformation.getCurrentUser();
this.jobCredentials = ((JobConf) conf).getCredentials();
if (CryptoUtils.isEncryptedSpillEnabled(conf)) {
int keyLen = conf.getInt(MRJobConfig.MR_ENCRYPTED_INTERMEDIATE_DATA_KEY_SIZE_BITS, MRJobConfig.DEFAULT_MR_ENCRYPTED_INTERMEDIATE_DATA_KEY_SIZE_BITS);
KeyGenerator keyGen = KeyGenerator.getInstance(INTERMEDIATE_DATA_ENCRYPTION_ALGO);
keyGen.init(keyLen);
encryptedSpillKey = keyGen.generateKey().getEncoded();
} else {
encryptedSpillKey = new byte[] { 0 };
}
} catch (IOException e) {
throw new YarnRuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new YarnRuntimeException(e);
}
}
use of javax.crypto.KeyGenerator in project hadoop by apache.
the class TestCredentials method testReadWriteStorage.
@SuppressWarnings("unchecked")
@Test
public <T extends TokenIdentifier> void testReadWriteStorage() throws IOException, NoSuchAlgorithmException {
// create tokenStorage Object
Credentials ts = new Credentials();
Token<T> token1 = new Token();
Token<T> token2 = new Token();
Text service1 = new Text("service1");
Text service2 = new Text("service2");
Collection<Text> services = new ArrayList<Text>();
services.add(service1);
services.add(service2);
token1.setService(service1);
token2.setService(service2);
ts.addToken(new Text("sometoken1"), token1);
ts.addToken(new Text("sometoken2"), token2);
// create keys and put it in
final KeyGenerator kg = KeyGenerator.getInstance(DEFAULT_HMAC_ALGORITHM);
String alias = "alias";
Map<Text, byte[]> m = new HashMap<Text, byte[]>(10);
for (int i = 0; i < 10; i++) {
Key key = kg.generateKey();
m.put(new Text(alias + i), key.getEncoded());
ts.addSecretKey(new Text(alias + i), key.getEncoded());
}
// create file to store
File tmpFileName = new File(tmpDir, "tokenStorageTest");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(tmpFileName));
ts.write(dos);
dos.close();
// open and read it back
DataInputStream dis = new DataInputStream(new FileInputStream(tmpFileName));
ts = new Credentials();
ts.readFields(dis);
dis.close();
// get the tokens and compare the services
Collection<Token<? extends TokenIdentifier>> list = ts.getAllTokens();
assertEquals("getAllTokens should return collection of size 2", list.size(), 2);
boolean foundFirst = false;
boolean foundSecond = false;
for (Token<? extends TokenIdentifier> token : list) {
if (token.getService().equals(service1)) {
foundFirst = true;
}
if (token.getService().equals(service2)) {
foundSecond = true;
}
}
assertTrue("Tokens for services service1 and service2 must be present", foundFirst && foundSecond);
// compare secret keys
int mapLen = m.size();
assertEquals("wrong number of keys in the Storage", mapLen, ts.numberOfSecretKeys());
for (Text a : m.keySet()) {
byte[] kTS = ts.getSecretKey(a);
byte[] kLocal = m.get(a);
assertTrue("keys don't match for " + a, WritableComparator.compareBytes(kTS, 0, kTS.length, kLocal, 0, kLocal.length) == 0);
}
tmpFileName.delete();
}
use of javax.crypto.KeyGenerator in project sonarqube by SonarSource.
the class AesCipher method generateRandomSecretKey.
String generateRandomSecretKey() {
try {
KeyGenerator keyGen = KeyGenerator.getInstance(CRYPTO_KEY);
keyGen.init(KEY_SIZE_IN_BITS, new SecureRandom());
SecretKey secretKey = keyGen.generateKey();
return Base64.encodeBase64String(secretKey.getEncoded());
} catch (Exception e) {
throw new IllegalStateException("Fail to generate secret key", e);
}
}
use of javax.crypto.KeyGenerator 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.KeyGenerator 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());
}
}
Aggregations