-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAndroidActivityCrypto.java
More file actions
73 lines (67 loc) · 2.19 KB
/
AndroidActivityCrypto.java
File metadata and controls
73 lines (67 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.aes_encrypt;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.TextView;
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String s = "This is my data I want to keep safe.";
String encryptedText = encrypt(s);
String clearText = decrypt(encryptedText);
((TextView)findViewById(R.id.encrypted_text)).setText(encryptedText);
((TextView)findViewById(R.id.clear_text)).setText(clearText);
}
private byte[] getKey() {
byte[] seed = "here_is_your_aes_key".getBytes();
KeyGenerator kg;
try {
kg = KeyGenerator.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
return null;
}
SecureRandom sr;
try {
sr = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
return null;
}
sr.setSeed(seed);
kg.init(128, sr);
SecretKey sk = kg.generateKey();
byte[] key = sk.getEncoded();
return key;
}
private String encrypt(String clearText) {
byte[] encryptedText = null;
try {
SecretKeySpec ks = new SecretKeySpec(getKey(), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, ks);
encryptedText = c.doFinal(clearText.getBytes("UTF-8"));
return Base64.encodeToString(encryptedText, Base64.DEFAULT);
} catch (Exception e) {
return null;
}
}
private String decrypt (String encryptedText) {
byte[] clearText = null;
try {
SecretKeySpec ks = new SecretKeySpec(getKey(), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, ks);
clearText = c.doFinal(Base64.decode(encryptedText, Base64.DEFAULT));
return new String(clearText, "UTF-8");
} catch (Exception e) {
return null;
}
}
}