use of javax.crypto.SecretKey in project robovm by robovm.
the class PKCS12KeyStoreSpi method unwrapKey.
protected PrivateKey unwrapKey(AlgorithmIdentifier algId, byte[] data, char[] password, boolean wrongPKCS12Zero) throws IOException {
ASN1ObjectIdentifier algorithm = algId.getAlgorithm();
try {
if (algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds)) {
PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters());
PBEKeySpec pbeSpec = new PBEKeySpec(password);
PrivateKey out;
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm.getId(), bcProvider);
PBEParameterSpec defParams = new PBEParameterSpec(pbeParams.getIV(), pbeParams.getIterations().intValue());
SecretKey k = keyFact.generateSecret(pbeSpec);
((BCPBEKey) k).setTryWrongPKCS12Zero(wrongPKCS12Zero);
Cipher cipher = Cipher.getInstance(algorithm.getId(), bcProvider);
cipher.init(Cipher.UNWRAP_MODE, k, defParams);
// we pass "" as the key algorithm type as it is unknown at this point
return (PrivateKey) cipher.unwrap(data, "", Cipher.PRIVATE_KEY);
} else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) {
PBES2Parameters alg = PBES2Parameters.getInstance(algId.getParameters());
PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId(), bcProvider);
SecretKey k = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), func.getIterationCount().intValue(), SecretKeyUtil.getKeySize(alg.getEncryptionScheme().getAlgorithm())));
Cipher cipher = Cipher.getInstance(alg.getEncryptionScheme().getAlgorithm().getId(), bcProvider);
cipher.init(Cipher.UNWRAP_MODE, k, new IvParameterSpec(ASN1OctetString.getInstance(alg.getEncryptionScheme().getParameters()).getOctets()));
// we pass "" as the key algorithm type as it is unknown at this point
return (PrivateKey) cipher.unwrap(data, "", Cipher.PRIVATE_KEY);
}
} catch (Exception e) {
throw new IOException("exception unwrapping private key - " + e.toString());
}
throw new IOException("exception unwrapping private key - cannot recognise: " + algorithm);
}
use of javax.crypto.SecretKey in project robovm by robovm.
the class OpenSSLCipher method engineInitInternal.
private void engineInitInternal(int opmode, Key key, byte[] iv, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) {
encrypting = true;
} else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) {
encrypting = false;
} else {
throw new InvalidParameterException("Unsupported opmode " + opmode);
}
if (!(key instanceof SecretKey)) {
throw new InvalidKeyException("Only SecretKey is supported");
}
final byte[] encodedKey = key.getEncoded();
if (encodedKey == null) {
throw new InvalidKeyException("key.getEncoded() == null");
}
checkSupportedKeySize(encodedKey.length);
final long cipherType = NativeCrypto.EVP_get_cipherbyname(getCipherName(encodedKey.length, mode));
if (cipherType == 0) {
throw new InvalidAlgorithmParameterException("Cannot find name for key length = " + (encodedKey.length * 8) + " and mode = " + mode);
}
final int ivLength = NativeCrypto.EVP_CIPHER_iv_length(cipherType);
if (iv == null && ivLength != 0) {
iv = new byte[ivLength];
if (encrypting) {
if (random == null) {
random = new SecureRandom();
}
random.nextBytes(iv);
}
} else if (iv != null && iv.length != ivLength) {
throw new InvalidAlgorithmParameterException("expected IV length of " + ivLength);
}
this.iv = iv;
if (supportsVariableSizeKey()) {
NativeCrypto.EVP_CipherInit_ex(cipherCtx.getContext(), cipherType, null, null, encrypting);
NativeCrypto.EVP_CIPHER_CTX_set_key_length(cipherCtx.getContext(), encodedKey.length);
NativeCrypto.EVP_CipherInit_ex(cipherCtx.getContext(), 0, encodedKey, iv, encrypting);
} else {
NativeCrypto.EVP_CipherInit_ex(cipherCtx.getContext(), cipherType, encodedKey, iv, encrypting);
}
// OpenSSL only supports PKCS5 Padding.
NativeCrypto.EVP_CIPHER_CTX_set_padding(cipherCtx.getContext(), padding == Padding.PKCS5PADDING);
modeBlockSize = NativeCrypto.EVP_CIPHER_CTX_block_size(cipherCtx.getContext());
calledUpdate = false;
}
use of javax.crypto.SecretKey in project robovm by robovm.
the class MacTest method test_getInstance_OpenSSL_ENGINE.
public void test_getInstance_OpenSSL_ENGINE() throws Exception {
final String secret = "-HMAC-test1";
final byte[] testString = "testing123".getBytes();
Provider p = Security.getProvider(OpenSSLProvider.PROVIDER_NAME);
NativeCryptoTest.loadTestEngine();
OpenSSLEngine engine = OpenSSLEngine.getInstance(NativeCryptoTest.TEST_ENGINE_ID);
/*
* The "-HMAC-" prefix is a special prefix recognized by
* test_openssl_engine.cpp
*/
SecretKey key1 = engine.getSecretKeyById(secret, "HmacSHA256");
SecretKey key1dupe = engine.getSecretKeyById(secret, "HmacSHA256");
/* Non-ENGINE-based SecretKey */
SecretKey key2 = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
/* The one that is ENGINE-based can't be equal to a non-ENGINE one. */
assertFalse(key1.equals(key2));
assertEquals(key1, key1dupe);
assertNull(key1.getFormat());
assertNull(key1.getEncoded());
assertEquals("RAW", key2.getFormat());
assertEquals(Arrays.toString(secret.getBytes()), Arrays.toString(key2.getEncoded()));
Mac mac1 = Mac.getInstance("HmacSHA256", p);
mac1.init(key1);
mac1.update(testString);
byte[] output1 = mac1.doFinal();
assertEquals(mac1.getMacLength(), output1.length);
Mac mac2 = Mac.getInstance("HmacSHA256", p);
mac2.init(key2);
mac2.update(testString);
byte[] output2 = mac2.doFinal();
assertEquals(Arrays.toString(output2), Arrays.toString(output1));
}
use of javax.crypto.SecretKey in project storm by apache.
the class BlowfishTupleSerializer method main.
/**
* Produce a blowfish key to be used in "Storm jar" command
*/
public static void main(String[] args) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
String keyString = new String(Hex.encodeHex(raw));
System.out.println("storm -c " + SECRET_KEY + "=" + keyString + " -c " + Config.TOPOLOGY_TUPLE_SERIALIZER + "=" + BlowfishTupleSerializer.class.getName() + " ...");
} catch (Exception ex) {
LOG.error(ex.getMessage());
ex.printStackTrace();
}
}
use of javax.crypto.SecretKey in project hadoop by apache.
the class TestZKRMStateStore method testFencedState.
@Test
public void testFencedState() throws Exception {
TestZKRMStateStoreTester zkTester = new TestZKRMStateStoreTester();
RMStateStore store = zkTester.getRMStateStore();
// Move state to FENCED from ACTIVE
store.updateFencedState();
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
long submitTime = System.currentTimeMillis();
long startTime = submitTime + 1000;
// Add a new app
RMApp mockApp = mock(RMApp.class);
ApplicationSubmissionContext context = new ApplicationSubmissionContextPBImpl();
when(mockApp.getSubmitTime()).thenReturn(submitTime);
when(mockApp.getStartTime()).thenReturn(startTime);
when(mockApp.getApplicationSubmissionContext()).thenReturn(context);
when(mockApp.getUser()).thenReturn("test");
store.storeNewApplication(mockApp);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
// Add a new attempt
ClientToAMTokenSecretManagerInRM clientToAMTokenMgr = new ClientToAMTokenSecretManagerInRM();
ApplicationAttemptId attemptId = ApplicationAttemptId.fromString("appattempt_1234567894321_0001_000001");
SecretKey clientTokenMasterKey = clientToAMTokenMgr.createMasterKey(attemptId);
RMAppAttemptMetrics mockRmAppAttemptMetrics = mock(RMAppAttemptMetrics.class);
Container container = new ContainerPBImpl();
container.setId(ContainerId.fromString("container_1234567891234_0001_01_000001"));
RMAppAttempt mockAttempt = mock(RMAppAttempt.class);
when(mockAttempt.getAppAttemptId()).thenReturn(attemptId);
when(mockAttempt.getMasterContainer()).thenReturn(container);
when(mockAttempt.getClientTokenMasterKey()).thenReturn(clientTokenMasterKey);
when(mockAttempt.getRMAppAttemptMetrics()).thenReturn(mockRmAppAttemptMetrics);
when(mockRmAppAttemptMetrics.getAggregateAppResourceUsage()).thenReturn(new AggregateAppResourceUsage(0, 0));
store.storeNewApplicationAttempt(mockAttempt);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
long finishTime = submitTime + 1000;
// Update attempt
ApplicationAttemptStateData newAttemptState = ApplicationAttemptStateData.newInstance(attemptId, container, store.getCredentialsFromAppAttempt(mockAttempt), startTime, RMAppAttemptState.FINISHED, "testUrl", "test", FinalApplicationStatus.SUCCEEDED, 100, finishTime, 0, 0, 0, 0);
store.updateApplicationAttemptState(newAttemptState);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
// Update app
ApplicationStateData appState = ApplicationStateData.newInstance(submitTime, startTime, context, "test");
store.updateApplicationState(appState);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
// Remove app
store.removeApplication(mockApp);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
// store RM delegation token;
RMDelegationTokenIdentifier dtId1 = new RMDelegationTokenIdentifier(new Text("owner1"), new Text("renewer1"), new Text("realuser1"));
Long renewDate1 = new Long(System.currentTimeMillis());
dtId1.setSequenceNumber(1111);
store.storeRMDelegationToken(dtId1, renewDate1);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
store.updateRMDelegationToken(dtId1, renewDate1);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
// remove delegation key;
store.removeRMDelegationToken(dtId1);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
// store delegation master key;
DelegationKey key = new DelegationKey(1234, 4321, "keyBytes".getBytes());
store.storeRMDTMasterKey(key);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
// remove delegation master key;
store.removeRMDTMasterKey(key);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
// store or update AMRMToken;
store.storeOrUpdateAMRMTokenSecretManager(null, false);
assertEquals("RMStateStore should have been in fenced state", true, store.isFencedState());
store.close();
}
Aggregations