use of javax.crypto.KeyGenerator in project robovm by robovm.
the class CipherWrapThread method crypt.
@Override
public void crypt() throws Exception {
KeyGenerator kg = KeyGenerator.getInstance(getAlgName().replace("Wrap", ""));
kg.init(getKeyLength(), new SecureRandom());
Key key = kg.generateKey();
// ignore mode and padding
Cipher cip = Cipher.getInstance(getAlgName());
cip.init(Cipher.WRAP_MODE, key);
byte[] output = cip.wrap(key);
cip.init(Cipher.UNWRAP_MODE, key);
Key decrypted = cip.unwrap(output, getAlgName(), Cipher.SECRET_KEY);
checkEncodedData(key.getFormat().getBytes(), decrypted.getFormat().getBytes());
checkEncodedData(key.getEncoded(), decrypted.getEncoded());
}
use of javax.crypto.KeyGenerator in project robovm by robovm.
the class KeyGeneratorThread method test.
public void test() throws Exception {
KeyGenerator kg = KeyGenerator.getInstance(algName);
Key k = kg.generateKey();
if (kg.getAlgorithm().toLowerCase().equals(k.getAlgorithm().toLowerCase()) != true) {
throw new Exception("Algorithm names not matched for KeyGenerator" + " and for Key objects");
}
if (kg.getAlgorithm().toLowerCase().equals(algName.toLowerCase()) != true) {
throw new Exception("Algorithm names not matched for KeyGenerator" + " and for Key objects");
}
byte[] array1 = k.getEncoded();
k = kg.generateKey();
byte[] array2 = k.getEncoded();
int matches = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == array2[i]) {
matches++;
}
}
if (matches > array1.length / 2) {
throw new Exception("Generated keys are simular");
}
SecureRandom random = new SecureRandom();
kg.init(random);
matches = 0;
k = kg.generateKey();
array1 = k.getEncoded();
random = new SecureRandom();
kg.init(random);
k = kg.generateKey();
array2 = k.getEncoded();
for (int i = 0; i < array1.length; i++) {
if (array1[i] == array2[i]) {
matches++;
}
}
}
use of javax.crypto.KeyGenerator in project robovm by robovm.
the class CipherTest method test_Cipher.
private void test_Cipher(Cipher c) throws Exception {
String algorithm = c.getAlgorithm().toUpperCase(Locale.US);
String providerName = c.getProvider().getName();
if (!isSupported(algorithm, providerName)) {
return;
}
String cipherID = algorithm + ":" + providerName;
try {
c.getOutputSize(0);
} catch (IllegalStateException expected) {
}
// TODO: test keys from different factories (e.g. OpenSSLRSAPrivateKey vs JCERSAPrivateKey)
Key encryptKey = getEncryptKey(algorithm);
final AlgorithmParameterSpec encryptSpec = getEncryptAlgorithmParameterSpec(algorithm);
int encryptMode = getEncryptMode(algorithm);
// Bouncycastle doesn't return a default PBEParameterSpec
if (isPBE(algorithm) && !"BC".equals(providerName)) {
assertNotNull(cipherID + " getParameters()", c.getParameters());
assertNotNull(c.getParameters().getParameterSpec(PBEParameterSpec.class));
} else {
assertNull(cipherID + " getParameters()", c.getParameters());
}
try {
assertNull(cipherID + " getIV()", c.getIV());
} catch (NullPointerException e) {
// Bouncycastle apparently has a bug here with AESWRAP, et al.
if (!("BC".equals(providerName) && isOnlyWrappingAlgorithm(algorithm))) {
throw e;
}
}
c.init(encryptMode, encryptKey, encryptSpec);
assertEquals(cipherID + " getBlockSize() encryptMode", getExpectedBlockSize(algorithm, encryptMode, providerName), c.getBlockSize());
assertEquals(cipherID + " getOutputSize(0) encryptMode", getExpectedOutputSize(algorithm, encryptMode, providerName), c.getOutputSize(0));
final AlgorithmParameterSpec decryptSpec = getDecryptAlgorithmParameterSpec(encryptSpec, c);
int decryptMode = getDecryptMode(algorithm);
c.init(decryptMode, encryptKey, decryptSpec);
assertEquals(cipherID + " getBlockSize() decryptMode", getExpectedBlockSize(algorithm, decryptMode, providerName), c.getBlockSize());
assertEquals(cipherID + " getOutputSize(0) decryptMode", getExpectedOutputSize(algorithm, decryptMode, providerName), c.getOutputSize(0));
if (isPBE(algorithm)) {
if (algorithm.endsWith("RC4")) {
assertNull(cipherID + " getIV()", c.getIV());
} else {
assertNotNull(cipherID + " getIV()", c.getIV());
}
} else if (decryptSpec instanceof IvParameterSpec) {
assertEquals(cipherID + " getIV()", Arrays.toString(((IvParameterSpec) decryptSpec).getIV()), Arrays.toString(c.getIV()));
} else {
try {
assertNull(cipherID + " getIV()", c.getIV());
} catch (NullPointerException e) {
// Bouncycastle apparently has a bug here with AESWRAP, et al.
if (!("BC".equals(providerName) && isOnlyWrappingAlgorithm(algorithm))) {
throw e;
}
}
}
AlgorithmParameters params = c.getParameters();
if (decryptSpec == null) {
assertNull(cipherID + " getParameters()", params);
} else if (decryptSpec instanceof IvParameterSpec) {
IvParameterSpec ivDecryptSpec = (IvParameterSpec) params.getParameterSpec(IvParameterSpec.class);
assertEquals(cipherID + " getIV()", Arrays.toString(((IvParameterSpec) decryptSpec).getIV()), Arrays.toString(ivDecryptSpec.getIV()));
} else if (decryptSpec instanceof PBEParameterSpec) {
// Bouncycastle seems to be schizophrenic about whther it returns this or not
if (!"BC".equals(providerName)) {
assertNotNull(cipherID + " getParameters()", params);
}
}
assertNull(cipherID, c.getExemptionMechanism());
// Test wrapping a key. Every cipher should be able to wrap. Except those that can't.
if (isSupportedForWrapping(algorithm)) {
// Generate a small SecretKey for AES.
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
SecretKey sk = kg.generateKey();
// Wrap it
c.init(Cipher.WRAP_MODE, encryptKey, encryptSpec);
byte[] cipherText = c.wrap(sk);
// Unwrap it
c.init(Cipher.UNWRAP_MODE, getDecryptKey(algorithm), decryptSpec);
Key decryptedKey = c.unwrap(cipherText, sk.getAlgorithm(), Cipher.SECRET_KEY);
assertEquals(cipherID + " sk.getAlgorithm()=" + sk.getAlgorithm() + " decryptedKey.getAlgorithm()=" + decryptedKey.getAlgorithm() + " encryptKey.getEncoded()=" + Arrays.toString(sk.getEncoded()) + " decryptedKey.getEncoded()=" + Arrays.toString(decryptedKey.getEncoded()), sk, decryptedKey);
}
if (!isOnlyWrappingAlgorithm(algorithm)) {
c.init(Cipher.ENCRYPT_MODE, encryptKey, encryptSpec);
byte[] cipherText = c.doFinal(getActualPlainText(algorithm));
c.init(Cipher.DECRYPT_MODE, getDecryptKey(algorithm), decryptSpec);
byte[] decryptedPlainText = c.doFinal(cipherText);
assertEquals(cipherID, Arrays.toString(getExpectedPlainText(algorithm, providerName)), Arrays.toString(decryptedPlainText));
}
}
use of javax.crypto.KeyGenerator in project robovm by robovm.
the class CipherTest method getEncryptKey.
private static synchronized Key getEncryptKey(String algorithm) throws Exception {
Key key = ENCRYPT_KEYS.get(algorithm);
if (key != null) {
return key;
}
if (algorithm.startsWith("RSA")) {
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(RSA_2048_modulus, RSA_2048_privateExponent);
key = kf.generatePrivate(keySpec);
} else if (isPBE(algorithm)) {
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
key = skf.generateSecret(new PBEKeySpec("secret".toCharArray()));
} else {
KeyGenerator kg = KeyGenerator.getInstance(getBaseAlgorithm(algorithm));
key = kg.generateKey();
}
ENCRYPT_KEYS.put(algorithm, key);
return key;
}
use of javax.crypto.KeyGenerator in project robovm by robovm.
the class CipherTest method testRC4_MultipleKeySizes.
public void testRC4_MultipleKeySizes() throws Exception {
final int SMALLEST_KEY_SIZE = 40;
final int LARGEST_KEY_SIZE = 1024;
/* Make an array of keys for our tests */
SecretKey[] keys = new SecretKey[LARGEST_KEY_SIZE - SMALLEST_KEY_SIZE];
{
KeyGenerator kg = KeyGenerator.getInstance("ARC4");
for (int keysize = SMALLEST_KEY_SIZE; keysize < LARGEST_KEY_SIZE; keysize++) {
final int index = keysize - SMALLEST_KEY_SIZE;
kg.init(keysize);
keys[index] = kg.generateKey();
}
}
/*
* Use this to compare the output of the first provider against
* subsequent providers.
*/
String[] expected = new String[LARGEST_KEY_SIZE - SMALLEST_KEY_SIZE];
/* Find all providers that provide ARC4. We must have at least one! */
Map<String, String> filter = new HashMap<String, String>();
filter.put("Cipher.ARC4", "");
Provider[] providers = Security.getProviders(filter);
assertTrue("There must be security providers of Cipher.ARC4", providers.length > 0);
/* Keep track of this for later error messages */
String firstProvider = providers[0].getName();
for (Provider p : providers) {
Cipher c = Cipher.getInstance("ARC4", p);
for (int keysize = SMALLEST_KEY_SIZE; keysize < LARGEST_KEY_SIZE; keysize++) {
final int index = keysize - SMALLEST_KEY_SIZE;
final SecretKey sk = keys[index];
/*
* Test that encryption works. Donig this in a loop also has the
* benefit of testing that re-initialization works for this
* cipher.
*/
c.init(Cipher.ENCRYPT_MODE, sk);
byte[] cipherText = c.doFinal(ORIGINAL_PLAIN_TEXT);
assertNotNull(cipherText);
/*
* Compare providers against eachother to make sure they're all
* in agreement. This helps when you add a brand new provider.
*/
if (expected[index] == null) {
expected[index] = Arrays.toString(cipherText);
} else {
assertEquals(firstProvider + " should output the same as " + p.getName() + " for key size " + keysize, expected[index], Arrays.toString(cipherText));
}
c.init(Cipher.DECRYPT_MODE, sk);
byte[] actualPlaintext = c.doFinal(cipherText);
assertEquals("Key size: " + keysize, Arrays.toString(ORIGINAL_PLAIN_TEXT), Arrays.toString(actualPlaintext));
}
}
}
Aggregations