· 7 years ago · Sep 25, 2018, 10:21 AM
1package ammase.com.description;
2
3import android.support.v7.app.AppCompatActivity;
4import android.os.Bundle;
5import android.util.Base64;
6import android.view.View;
7import android.widget.Button;
8import android.widget.EditText;
9import android.widget.TextView;
10
11import java.security.MessageDigest;
12
13import javax.crypto.Cipher;
14import javax.crypto.SecretKey;
15import javax.crypto.spec.SecretKeySpec;
16
17
18public class MainActivity extends AppCompatActivity {
19
20 EditText inputText, passwordTextView;
21 Button onBnt, btn_decrypt;
22 TextView outtext;
23 String outputString;
24 String AES = "AES";
25
26 @Override
27 protected void onCreate(Bundle savedInstanceState) {
28 super.onCreate(savedInstanceState);
29 setContentView(R.layout.activity_main);
30
31 inputText = (EditText) findViewById(R.id.et_messange);
32 passwordTextView = (EditText) findViewById(R.id.et_password);
33 outtext = (TextView) findViewById(R.id.textView);
34 onBnt = (Button) findViewById(R.id.button);
35 btn_decrypt = (Button) findViewById(R.id.btn_decrypt);
36
37 onBnt.setOnClickListener(new View.OnClickListener() {
38 @Override
39 public void onClick(View view) {
40 try {
41 outputString = encrypt (inputText.getText().toString(), passwordTextView.getText().toString());
42 outtext.setText(outputString);
43 } catch (Exception e) {
44 e.printStackTrace();
45 }
46 }
47 });
48
49
50 btn_decrypt.setOnClickListener(new View.OnClickListener() {
51 @Override
52 public void onClick(View view) {
53 try {
54 outputString = decrypt(outputString, passwordTextView.getText().toString());
55 outtext.setText(outputString);
56 } catch (Exception e) {
57 e.printStackTrace();
58 }
59
60
61 }
62 });
63 }
64
65 private String decrypt(String outputString, String password) throws Exception {
66 SecretKey key = generateKey(password);
67 Cipher c = Cipher.getInstance(AES);
68 c.init(Cipher.DECRYPT_MODE,key);
69 byte[] decodeValue = Base64.decode(outputString, Base64.DEFAULT);
70 byte[] decValue = c.doFinal(decodeValue);
71 String decrypteValue = new String(decValue);
72 return decrypteValue;
73 }
74
75 private String encrypt(String data, String password) throws Exception {
76 SecretKey key = generateKey(password);
77 Cipher c = Cipher.getInstance(AES);
78 c.init(Cipher.ENCRYPT_MODE,key);
79 byte[] encVal = c.doFinal(data.getBytes());
80 String encrypteValue = Base64.encodeToString(encVal, Base64.DEFAULT);
81 return encrypteValue;
82 }
83
84 private SecretKey generateKey(String password) throws Exception {
85 final MessageDigest digest = MessageDigest.getInstance("SHA-256");
86 byte[] bytes = password.getBytes("UTF-8");
87 digest.update(bytes, 0, bytes.length);
88 byte[]key = digest.digest();
89 SecretKeySpec secretKeySpec = new SecretKeySpec(key, AES);
90 return secretKeySpec;
91 }
92}