Search in sources :

Example 31 with KeyGenerator

use of javax.crypto.KeyGenerator in project robovm by robovm.

the class CipherTest method checkCipher.

private void checkCipher(CipherTestParam p, String provider) throws Exception {
    SecretKey key = new SecretKeySpec(p.key, "AES");
    Cipher c = Cipher.getInstance(p.mode + "/PKCS5Padding", provider);
    AlgorithmParameterSpec spec = null;
    if (p.iv != null) {
        spec = new IvParameterSpec(p.iv);
    }
    c.init(Cipher.ENCRYPT_MODE, key, spec);
    final byte[] actualCiphertext = c.doFinal(p.plaintext);
    assertEquals(Arrays.toString(p.ciphertext), Arrays.toString(actualCiphertext));
    byte[] emptyCipherText = c.doFinal();
    assertNotNull(emptyCipherText);
    c.init(Cipher.DECRYPT_MODE, key, spec);
    try {
        c.updateAAD(new byte[8]);
        fail("Cipher should not support AAD");
    } catch (UnsupportedOperationException expected) {
    }
    byte[] emptyPlainText = c.doFinal(emptyCipherText);
    assertEquals(Arrays.toString(EmptyArray.BYTE), Arrays.toString(emptyPlainText));
    // empty decrypt
    {
        if (StandardNames.IS_RI) {
            assertEquals(Arrays.toString(EmptyArray.BYTE), Arrays.toString(c.doFinal()));
            c.update(EmptyArray.BYTE);
            assertEquals(Arrays.toString(EmptyArray.BYTE), Arrays.toString(c.doFinal()));
        } else if (provider.equals("BC")) {
            try {
                c.doFinal();
                fail();
            } catch (IllegalBlockSizeException expected) {
            }
            try {
                c.update(EmptyArray.BYTE);
                c.doFinal();
                fail();
            } catch (IllegalBlockSizeException expected) {
            }
        } else if (provider.equals("AndroidOpenSSL")) {
            assertNull(c.doFinal());
            c.update(EmptyArray.BYTE);
            assertNull(c.doFinal());
        } else {
            throw new AssertionError("Define your behavior here for " + provider);
        }
    }
    // .doFinal(input)
    {
        final byte[] actualPlaintext = c.doFinal(p.ciphertext);
        assertEquals(Arrays.toString(p.plaintext), Arrays.toString(actualPlaintext));
    }
    // .doFinal(input, offset, len, output)
    {
        final byte[] largerThanCiphertext = new byte[p.ciphertext.length + 5];
        System.arraycopy(p.ciphertext, 0, largerThanCiphertext, 5, p.ciphertext.length);
        final byte[] actualPlaintext = new byte[c.getOutputSize(p.ciphertext.length)];
        assertEquals(p.plaintext.length, c.doFinal(largerThanCiphertext, 5, p.ciphertext.length, actualPlaintext));
        assertEquals(Arrays.toString(p.plaintext), Arrays.toString(Arrays.copyOfRange(actualPlaintext, 0, p.plaintext.length)));
    }
    // .doFinal(input, offset, len, output, offset)
    {
        final byte[] largerThanCiphertext = new byte[p.ciphertext.length + 10];
        System.arraycopy(p.ciphertext, 0, largerThanCiphertext, 5, p.ciphertext.length);
        final byte[] actualPlaintext = new byte[c.getOutputSize(p.ciphertext.length) + 2];
        assertEquals(p.plaintext.length, c.doFinal(largerThanCiphertext, 5, p.ciphertext.length, actualPlaintext, 1));
        assertEquals(Arrays.toString(p.plaintext), Arrays.toString(Arrays.copyOfRange(actualPlaintext, 1, p.plaintext.length + 1)));
    }
    Cipher cNoPad = Cipher.getInstance(p.mode + "/NoPadding", provider);
    cNoPad.init(Cipher.DECRYPT_MODE, key, spec);
    final byte[] actualPlaintextPadded = cNoPad.doFinal(p.ciphertext);
    assertEquals(Arrays.toString(p.plaintextPadded), Arrays.toString(actualPlaintextPadded));
    // Test wrapping a key. Every cipher should be able to wrap.
    {
        // 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, key, spec);
        byte[] cipherText = c.wrap(sk);
        // Unwrap it
        c.init(Cipher.UNWRAP_MODE, key, spec);
        Key decryptedKey = c.unwrap(cipherText, sk.getAlgorithm(), Cipher.SECRET_KEY);
        assertEquals("sk.getAlgorithm()=" + sk.getAlgorithm() + " decryptedKey.getAlgorithm()=" + decryptedKey.getAlgorithm() + " encryptKey.getEncoded()=" + Arrays.toString(sk.getEncoded()) + " decryptedKey.getEncoded()=" + Arrays.toString(decryptedKey.getEncoded()), sk, decryptedKey);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) KeyGenerator(javax.crypto.KeyGenerator) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey)

Example 32 with KeyGenerator

use of javax.crypto.KeyGenerator in project robovm by robovm.

the class KeyStoreTest method testEngineEntryInstanceOf.

/*
     * java.security.KeyStoreSpi.engineEntryInstanceOf(String, Class<? extends Entry>)
     */
public void testEngineEntryInstanceOf() throws Exception {
    //Regression for HARMONY-615
    // create a KeyStore
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, "pwd".toCharArray());
    // generate a key
    KeyGenerator keyGen = KeyGenerator.getInstance("DES");
    keyGen.init(56);
    SecretKey secretKey = keyGen.generateKey();
    // put the key into keystore
    String alias = "alias";
    keyStore.setKeyEntry(alias, secretKey, "pwd".toCharArray(), null);
    // check if it is a secret key
    assertTrue(keyStore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class));
    // check if it is NOT a private key
    assertFalse(keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class));
}
Also used : SecretKey(javax.crypto.SecretKey) KeyStore(java.security.KeyStore) KeyGenerator(javax.crypto.KeyGenerator)

Example 33 with KeyGenerator

use of javax.crypto.KeyGenerator in project KeyBox by skavanagh.

the class KeyStoreUtil method initializeKeyStore.

/**
	 * create new keystore
	 */
private static void initializeKeyStore() {
    try {
        keyStore = KeyStore.getInstance("JCEKS");
        //create keystore
        keyStore.load(null, KEYSTORE_PASS);
        //set encryption key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(KEYLENGTH);
        KeyStoreUtil.setSecret(KeyStoreUtil.ENCRYPTION_KEY_ALIAS, keyGenerator.generateKey().getEncoded());
        //write keystore
        FileOutputStream fos = new FileOutputStream(keyStoreFile);
        keyStore.store(fos, KEYSTORE_PASS);
        fos.close();
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) KeyGenerator(javax.crypto.KeyGenerator)

Example 34 with KeyGenerator

use of javax.crypto.KeyGenerator in project platform_frameworks_base by android.

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;
}
Also used : SecretKey(javax.crypto.SecretKey) FileOutputStream(java.io.FileOutputStream) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) File(java.io.File) KeyGenerator(javax.crypto.KeyGenerator)

Example 35 with KeyGenerator

use of javax.crypto.KeyGenerator in project platform_frameworks_base by android.

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());
}
Also used : SecureRandom(java.security.SecureRandom) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvalidKeyException(java.security.InvalidKeyException) KeyStore(android.security.KeyStore) SecretKey(javax.crypto.SecretKey) UnrecoverableKeyException(java.security.UnrecoverableKeyException) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator)

Aggregations

KeyGenerator (javax.crypto.KeyGenerator)166 SecretKey (javax.crypto.SecretKey)117 SecureRandom (java.security.SecureRandom)53 Cipher (javax.crypto.Cipher)43 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)32 Key (java.security.Key)31 Test (org.junit.Test)25 InvalidKeyException (java.security.InvalidKeyException)19 IvParameterSpec (javax.crypto.spec.IvParameterSpec)19 IOException (java.io.IOException)18 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)13 BadPaddingException (javax.crypto.BadPaddingException)13 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)13 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)13 File (java.io.File)12 FileOutputStream (java.io.FileOutputStream)12 RouteBuilder (org.apache.camel.builder.RouteBuilder)12 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)11 Provider (java.security.Provider)11 SecretKeySpec (javax.crypto.spec.SecretKeySpec)10