Search in sources :

Example 71 with KeyGenerator

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

Example 72 with KeyGenerator

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());
}
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)

Example 73 with KeyGenerator

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();
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecretKey(javax.crypto.SecretKey) Instant(java.time.Instant) KeyGenerator(javax.crypto.KeyGenerator)

Example 74 with KeyGenerator

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);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SecureVaultException(org.wso2.carbon.secvault.exception.SecureVaultException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyGenerator(javax.crypto.KeyGenerator)

Example 75 with KeyGenerator

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

Aggregations

KeyGenerator (javax.crypto.KeyGenerator)464 SecretKey (javax.crypto.SecretKey)343 Test (org.junit.Test)106 ArrayList (java.util.ArrayList)104 SecureRandom (java.security.SecureRandom)99 Document (org.w3c.dom.Document)98 InputStream (java.io.InputStream)95 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)93 ByteArrayOutputStream (java.io.ByteArrayOutputStream)87 NodeList (org.w3c.dom.NodeList)82 Cipher (javax.crypto.Cipher)79 ByteArrayInputStream (java.io.ByteArrayInputStream)75 XMLStreamReader (javax.xml.stream.XMLStreamReader)68 XMLSecurityProperties (org.apache.xml.security.stax.ext.XMLSecurityProperties)68 DocumentBuilder (javax.xml.parsers.DocumentBuilder)62 Key (java.security.Key)58 QName (javax.xml.namespace.QName)47 IOException (java.io.IOException)45 SecurePart (org.apache.xml.security.stax.ext.SecurePart)40 SecretKeySpec (javax.crypto.spec.SecretKeySpec)39