· 6 years ago · Mar 04, 2019, 12:08 AM
1package com.example.android.secure;
2
3import javax.crypto.Cipher;
4import javax.crypto.SecretKey;
5import javax.crypto.SecretKeyFactory;
6import javax.crypto.spec.IvParameterSpec;
7import javax.crypto.spec.PBEKeySpec;
8import javax.crypto.spec.SecretKeySpec;
9
10public class EncryptionManager {
11
12 // we should get a password from the user
13 String password = "...";
14 String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC";
15 // Important not to rely on default here !!!! use CBC instead of ECB
16 String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
17 int NUM_OF_ITERATIONS = 1000;
18 int KEY_SIZE = 256;
19 // generated on first run
20 byte[] salt = "abababababababababa bab".getBytes();
21 byte[] iv = "1234567890abcdef".getBytes();
22 // This is the value to be encrypted.
23 String clearText = "...";
24 byte[] encryptedText;
25 byte[] decryptedText;
26
27 public void exampleCodeNoRealMethod() {
28 try {
29 PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, NUM_OF_ITERATIONS, KEY_SIZE);
30 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALGORITHM);
31 SecretKey tempKey = keyFactory.generateSecret(pbeKeySpec);
32 SecretKey secretKey = new SecretKeySpec(tempKey.getEncoded(), "AES");
33 IvParameterSpec ivSpec = new IvParameterSpec(iv);
34 Cipher encCipher = Cipher.getInstance(CIPHER_ALGORITHM);
35 encCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
36 Cipher decCipher = Cipher.getInstance(CIPHER_ALGORITHM);
37 decCipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
38 encryptedText = encCipher.doFinal(clearText.getBytes());
39 decryptedText = decCipher.doFinal(encryptedText);
40 String sameAsClearText = new String(decryptedText);
41 } catch (Exception e) {
42 // TODO handle this exception
43 }
44 }
45
46}
47
48public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
49 // Number of PBKDF2 hardening rounds to use. Larger values increase
50 // computation time. You should select a value that causes computation
51 // to take >100ms.
52 final int iterations = 1000;
53
54 // Generate a 256-bit key
55 final int outputKeyLength = 256;
56
57 SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
58 KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);
59 SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
60 return secretKey;
61}