· 7 years ago · Apr 25, 2018, 03:08 AM
1KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
2keyGenerator.init(128, new SecureRandom());
3SecretKey secretKey = keyGenerator.generateKey();
4
5Cipher cipher = Cipher.getInstance("AES");
6
7String plainText = "This is supposed to be encrypted";
8String plainKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT);
9
10//encrypt
11cipher.init(Cipher.ENCRYPT_MODE, secretKey);
12byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
13String encryptedText = Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
14
15//decrypt
16cipher.init(Cipher.DECRYPT_MODE, secretKey);
17byte[]decryptedBytes = cipher.doFinal(encryptedBytes);
18String decryptedText = Base64.encodeToString(decryptedBytes, Base64.DEFAULT);
19
20SecretKeySpec sks = null;
21 try {
22 SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
23 sr.setSeed("Complex Key for encryption".getBytes());
24 KeyGenerator kg = KeyGenerator.getInstance("AES");
25 kg.init(128, sr);
26 sks = new SecretKeySpec((kg.generateKey()).getEncoded(), "AES");
27 } catch (Exception e) {
28 Log.e(TAG, "AES secret key spec error");
29 }
30
31 // Encode the original data with AES
32 byte[] encodedBytes = null;
33 try {
34 Cipher c = Cipher.getInstance("AES");
35 c.init(Cipher.ENCRYPT_MODE, sks);
36 encodedBytes = c.doFinal(theTestText.getBytes());
37 } catch (Exception e) {
38 Log.e(TAG, "AES encryption error");
39 }
40 TextView tvencoded = (TextView)findViewById(R.id.textitem2);
41 tvencoded.setText("[ENCODED]:n" +
42 Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "n");
43
44 // Decode the encoded data with AES
45 byte[] decodedBytes = null;
46 try {
47 Cipher c = Cipher.getInstance("AES");
48 c.init(Cipher.DECRYPT_MODE, sks);
49 decodedBytes = c.doFinal(encodedBytes);
50 } catch (Exception e) {
51 Log.e(TAG, "AES decryption error");
52 }
53 TextView tvdecoded = (TextView)findViewById(R.id.textitem3);
54 tvdecoded.setText("[DECODED]:n" + new String(decodedBytes) + "n");