Creates a symmetric key in the Android Key Store. - Android java.security

Android examples for java.security:KeyStore

Description

Creates a symmetric key in the Android Key Store.

Demo Code


//package com.java2s;

import android.security.keystore.KeyGenParameterSpec;

import android.security.keystore.KeyProperties;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import java.security.cert.CertificateException;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

public class Main {
    public static final String KEY_STORE_TYPE = "AndroidKeyStore";

    /**/*from w w  w.j ava 2 s .co m*/
     * Creates a symmetric key in the Android Key Store.
     * This key can only be used once the user has authenticated with fingerprint.
     */
    public static SecretKey createKey(String alias) {
        try {
            KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
            keyStore.load(null);

            KeyGenerator keyGenerator = KeyGenerator.getInstance(
                    KeyProperties.KEY_ALGORITHM_AES, KEY_STORE_TYPE);
            keyGenerator
                    .init(new KeyGenParameterSpec.Builder(alias,
                            KeyProperties.PURPOSE_ENCRYPT
                                    | KeyProperties.PURPOSE_DECRYPT)
                            .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                            .setUserAuthenticationRequired(true)
                            .setEncryptionPaddings(
                                    KeyProperties.ENCRYPTION_PADDING_PKCS7)
                            .build());
            return keyGenerator.generateKey();
        } catch (NoSuchAlgorithmException | NoSuchProviderException
                | InvalidAlgorithmParameterException | KeyStoreException
                | CertificateException | IOException e) {
            throw new RuntimeException("Failed to create a symmetric key",
                    e);
        }
    }
}

Related Tutorials