· 6 years ago · Jul 17, 2019, 02:50 AM
1/**
2 _____ _____ _
3 | __ \ / ____| | |
4 | | | | ___| | _ __ _ _ _ __ | |_ ___ _ __
5 | | | |/ _ \ | | '__| | | | '_ \| __/ _ \| '__|
6 | |__| | __/ |____| | | |_| | |_) | || (_) | |
7 |_____/ \___|\_____|_| \__, | .__/ \__\___/|_|
8 __/ | |
9 |___/|_|
10 */
11class DeCryptor {
12
13 private static final String TRANSFORMATION = "AES/GCM/NoPadding";
14 private static final String ANDROID_KEY_STORE = "AndroidKeyStore";
15
16 private KeyStore keyStore;
17
18 DeCryptor() throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
19 IOException {
20 initKeyStore();
21 }
22
23 private void initKeyStore() throws KeyStoreException, CertificateException,
24 NoSuchAlgorithmException, IOException {
25 keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
26 keyStore.load(null);
27 }
28
29 String decryptData(final String alias, final byte[] encryptedData, final byte[] encryptionIv)
30 throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException,
31 NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException,
32 BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
33
34 final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
35 final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv);
36 cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), spec);
37
38 return new String(cipher.doFinal(encryptedData), "UTF-8");
39 }
40
41 private SecretKey getSecretKey(final String alias) throws NoSuchAlgorithmException,
42 UnrecoverableEntryException, KeyStoreException {
43 return ((KeyStore.SecretKeyEntry) keyStore.getEntry(alias, null)).getSecretKey();
44 }
45}