· 4 years ago · Jun 21, 2021, 04:08 PM
1 void encryptToken(String token) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
2
3 final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
4 final KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder("MyKeyAlias",
5 KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
6 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
7 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
8 .build();
9 keyGenerator.init(keyGenParameterSpec);
10 SecretKey secretKey = keyGenerator.generateKey();
11
12 final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
13 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
14 iv = cipher.getIV();
15 encryption = cipher.doFinal(token.getBytes(StandardCharsets.UTF_8));
16 }
17
18 void decryptToken(String secretMessage) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
19 KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
20 keyStore.load(null);
21 final KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry) keyStore.getEntry("MyKeyAlias", null);
22 final SecretKey secretKey = secretKeyEntry.getSecretKey();
23
24 final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
25 final GCMParameterSpec spec = new GCMParameterSpec(128, iv);
26 cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
27 final byte[] decodedData = cipher.doFinal(encryption);
28 final String unencryptedString = new String(decodedData, StandardCharsets.UTF_8);
29 }