· 8 years ago · Nov 28, 2017, 05:32 AM
1byte[] 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'};
2byte[] header = {'a','b','c','d','a','b','c','d','a','b','c','d','a','b','c','d'};
3byte[] updatedHeader = {'A','B','C','D','A','B','C','D','A','B','C','D','A','B','C','D'};
4
5byte[] dBytes = new byte[400];
6int offset =0;
7
8SecretKey secretKey = generateKey();
9
10try {
11 //cipher initialization for Encryption
12 Cipher cipher = Cipher.getInstance("AES");
13 cipher.init(Cipher.ENCRYPT_MODE,secretKey);
14
15 FileOutputStream os = new FileOutputStream(sdCard.getAbsolutePath() + "/Notes/sample.encrypted");
16 CipherOutputStream cos = new CipherOutputStream(os,cipher);
17 FileOutputStream os1 = new FileOutputStream(sdCard.getAbsolutePath() + "/Notes/sample.encrypted");
18 CipherOutputStream cos1 = new CipherOutputStream(os1,cipher);
19
20 Log.d("Encryption", "Writing cipher text to output file");
21 cos.write(header, offset, 10); //Write 10 bytes header data with smallCase array
22 cos.write(data, offset, 40); // write 40 bytes actual data
23 cos.close();
24
25 cos1.write(updatedHeader, offset, 10); // Overwrite header data with capitalCase array data
26 cos1.close();
27
28 //Cipher initialization for decryption
29 Cipher dcipher = Cipher.getInstance("AES");
30 dcipher.init(Cipher.DECRYPT_MODE,secretKey);
31
32 FileInputStream inputStream = new FileInputStream(sdCard.getAbsolutePath() + "/Notes/sample.encrypted");
33
34 CipherInputStream cis = new CipherInputStream(inputStream,dcipher);
35 FileOutputStream dos = new FileOutputStream(sdCard.getAbsolutePath() + "/Notes/sample.decrypted");
36
37 int b = cis.read(dBytes);
38 while(b != -1) {
39 Log.d("Decryption","Bytes decrypted" + b);
40 dos.write(dBytes, 0, b);
41 b = cis.read(dBytes);
42 }
43 cis.close();
44 os.close();
45}catch (Exception e) { e.printStackTrace(); }