· 9 years ago · Dec 30, 2016, 04:24 PM
1package it.blowfish.teti.tetiblowfish;
2
3import android.os.Bundle;
4import android.support.v7.app.AppCompatActivity;
5import android.util.Log;
6
7import java.security.GeneralSecurityException;
8
9import javax.crypto.Cipher;
10import javax.crypto.SecretKey;
11import javax.crypto.spec.SecretKeySpec;
12
13public class MainActivity extends AppCompatActivity {
14
15 private final static String ALGORITM = "Blowfish";
16 private final static String KEY = "12345678";
17 private final static String PLAIN_TEXT = "Antonio";
18
19 @Override
20 protected void onCreate(Bundle savedInstanceState) {
21 super.onCreate(savedInstanceState);
22 setContentView(R.layout.activity_main);
23
24 try {
25
26 byte[] encrypted = encrypt("antonio123456789", PLAIN_TEXT);
27 Log.i("FOO", "Encrypted: " + bytesToHex(encrypted));
28
29 String decrypted = decrypt("antonio123456789", encrypted);
30 Log.i("FOO", "Decrypted: " + decrypted);
31
32 } catch (GeneralSecurityException e) {
33 e.printStackTrace();
34 }
35
36
37
38 }
39
40
41 private byte[] encrypt(String key, String plainText) throws GeneralSecurityException {
42
43 SecretKey secret_key = new SecretKeySpec(key.getBytes(), ALGORITM);
44
45 Cipher cipher = Cipher.getInstance(ALGORITM);
46 cipher.init(Cipher.ENCRYPT_MODE, secret_key);
47
48 return cipher.doFinal(plainText.getBytes());
49 }
50
51 private String decrypt(String key, byte[] encryptedText) throws GeneralSecurityException {
52
53 SecretKey secret_key = new SecretKeySpec(key.getBytes(), ALGORITM);
54
55 Cipher cipher = Cipher.getInstance(ALGORITM);
56 cipher.init(Cipher.DECRYPT_MODE, secret_key);
57
58 byte[] decrypted = cipher.doFinal(encryptedText);
59
60 return new String(decrypted);
61 }
62
63 public static String bytesToHex(byte[] data) {
64
65 if (data == null)
66 return null;
67
68 String str = "";
69
70 for (int i = 0; i < data.length; i++) {
71 if ((data[i] & 0xFF) < 16)
72 str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
73 else
74 str = str + java.lang.Integer.toHexString(data[i] & 0xFF);
75 }
76
77 return str;
78
79 }
80}