/
Crypto.java
50 lines (40 loc) · 1.61 KB
/
Crypto.java
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
package com.lifebox.lifeboxapp;
import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class Crypto {
private byte[] keyBytes;
public Crypto(String key) throws Exception {
keyBytes = Base64ToByte(key);
}
public byte[] encrypt(byte[] plainText) throws Exception {
Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
return cipher.doFinal(plainText);
}
public byte[] decrypt(byte[] encrypted) throws Exception {
Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
return cipher.doFinal(encrypted);
}
private Cipher getCipher(int cipherMode) throws Exception {
String encryptionAlgorithm = "AES";
SecretKeySpec keySpecification = new SecretKeySpec(keyBytes, encryptionAlgorithm);
Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
cipher.init(cipherMode, keySpecification);
return cipher;
}
public static String makeKey(String password, String salt) throws Exception {
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes("UTF-8"), 1000, 128);
SecretKeyFactory skf;
skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] key = skf.generateSecret(spec).getEncoded();
return ByteToBase64(key);
}
public static String ByteToBase64(byte[] input) {
return Base64.encodeToString(input, Base64.DEFAULT);
}
public static byte[] Base64ToByte(String input) {
return Base64.decode(input, Base64.DEFAULT);
}
}