· 7 years ago · Apr 21, 2018, 05:46 PM
1protected void generateKey() {
2 try {
3 keyStore = KeyStore.getInstance("AndroidKeyStore");
4 } catch (Exception e) {
5 e.printStackTrace();
6 }
7
8
9 KeyGenerator keyGenerator;
10 try {
11 keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
12 } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
13 throw new RuntimeException("Failed to get KeyGenerator instance", e);
14 }
15
16
17 try {
18 keyStore.load(null);
19 keyGenerator.init(new
20 KeyGenParameterSpec.Builder(KEY_NAME,
21 KeyProperties.PURPOSE_ENCRYPT |
22 KeyProperties.PURPOSE_DECRYPT)
23 .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
24 .setUserAuthenticationRequired(true)
25 .setEncryptionPaddings(
26 KeyProperties.ENCRYPTION_PADDING_PKCS7)
27 .build());
28 keyGenerator.generateKey();
29 } catch (NoSuchAlgorithmException |
30 InvalidAlgorithmParameterException
31 | CertificateException | IOException e) {
32 throw new RuntimeException(e);
33 }
34 }
35
36 public boolean cipherInit() {
37 try {
38 cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
39 } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
40 throw new RuntimeException("Failed to get Cipher", e);
41 }
42
43
44 try {
45 keyStore.load(null);
46 SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
47 null);
48 cipher.init(Cipher.ENCRYPT_MODE, key);
49 return true;
50 } catch (KeyPermanentlyInvalidatedException e) {
51 return false;
52 } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
53 throw new RuntimeException("Failed to init Cipher", e);
54 }
55 }
56}