· 7 years ago · Nov 09, 2018, 12:50 AM
1private final static String ALGORITM = "Blowfish";
2private final static String KEY = "2356a3a42ba5781f80a72dad3f90aeee8ba93c7637aaf218a8b8c18c";
3private final static String PLAIN_TEXT = "here is your text";
4
5public void run(View v) {
6
7 try {
8
9 byte[] encrypted = encrypt(KEY, PLAIN_TEXT);
10 Log.i("FOO", "Encrypted: " + bytesToHex(encrypted));
11
12 String decrypted = decrypt(KEY, encrypted);
13 Log.i("FOO", "Decrypted: " + decrypted);
14
15 } catch (GeneralSecurityException e) {
16 e.printStackTrace();
17 }
18}
19
20private byte[] encrypt(String key, String plainText) throws GeneralSecurityException {
21
22 SecretKey secret_key = new SecretKeySpec(key.getBytes(), ALGORITM);
23
24 Cipher cipher = Cipher.getInstance(ALGORITM);
25 cipher.init(Cipher.ENCRYPT_MODE, secret_key);
26
27 return cipher.doFinal(plainText.getBytes());
28}
29
30private String decrypt(String key, byte[] encryptedText) throws GeneralSecurityException {
31
32 SecretKey secret_key = new SecretKeySpec(key.getBytes(), ALGORITM);
33
34 Cipher cipher = Cipher.getInstance(ALGORITM);
35 cipher.init(Cipher.DECRYPT_MODE, secret_key);
36
37 byte[] decrypted = cipher.doFinal(encryptedText);
38
39 return new String(decrypted);
40}
41
42public static String bytesToHex(byte[] data) {
43
44 if (data == null)
45 return null;
46
47 String str = "";
48
49 for (int i = 0; i < data.length; i++) {
50 if ((data[i] & 0xFF) < 16)
51 str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
52 else
53 str = str + java.lang.Integer.toHexString(data[i] & 0xFF);
54 }
55
56 return str;
57
58}