Guest User

Untitled

a guest
Apr 24th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
  2. keyGenerator.init(128, new SecureRandom());
  3. SecretKey secretKey = keyGenerator.generateKey();
  4.  
  5. Cipher cipher = Cipher.getInstance("AES");
  6.  
  7. String plainText = "This is supposed to be encrypted";
  8. String plainKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT);
  9.  
  10. //encrypt
  11. cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  12. byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
  13. String encryptedText = Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
  14.  
  15. //decrypt
  16. cipher.init(Cipher.DECRYPT_MODE, secretKey);
  17. byte[]decryptedBytes = cipher.doFinal(encryptedBytes);
  18. String decryptedText = Base64.encodeToString(decryptedBytes, Base64.DEFAULT);
  19.  
  20. SecretKeySpec 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");
Add Comment
Please, Sign In to add comment