· 8 years ago · Dec 21, 2017, 09:42 AM
1protected void EncryptAndroid() {
2 byte[] data = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',};
4 byte[] header = {'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd',
5 'a', 'b', 'c', 'd',};
6 byte[] updatedHeader = {'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D',
7 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D'};
8 byte[] encryptedBytes = new byte[100];
9
10 try {
11 SecretKey secret = null;
12 // key generation using AndroidKeyStore provider
13 KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
14 keyGenerator.init(
15 new KeyGenParameterSpec.Builder("key2",
16 KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
17 .setKeySize(256)
18 .setBlockModes(KeyProperties.BLOCK_MODE_CTR)
19 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
20 .build());
21 secret = keyGenerator.generateKey();
22
23 // Cipher object initialization
24 Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
25 cipher.init(Cipher.ENCRYPT_MODE, secret);
26
27 // Getting IV
28 AlgorithmParameters params = cipher.getParameters();
29 byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
30
31 RandomAccessFile fd = new RandomAccessFile(sdCard.getAbsolutePath() + "/Notes/sample.encrypted","rw");
32
33 int offset = 0;
34 encryptedBytes = cipher.doFinal(header, offset, 10);
35 fd.write(encryptedBytes);
36 encryptedBytes = cipher.doFinal(data, offset, 40);
37 fd.write(encryptedBytes);
38
39 FileOutputStream ivStream = new FileOutputStream(sdCard.getAbsolutePath() + "/Notes/iv.dat");
40 if (ivStream != null) {
41 Log.d("Encryption", "Writing iv data to output file");
42 ivStream.write(iv);
43 }
44
45 ivStream.close();
46 fd.close();
47 }catch (Exception e) {
48 e.printStackTrace();
49 }
50}