MCPcopy Create free account
hub / github.com/Raj-m01/Android-Chat-App / AESUtils

Class AESUtils

app/src/main/java/com/example/chatapp/AESUtils.java:7–76  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5import javax.crypto.spec.SecretKeySpec;
6
7public class AESUtils
8{
9
10 private static final byte[] keyValue =
11 new byte[]{'c', 'o', 'd', 'i', 'n', 'g', 'a', 'f', 'f', 'a', 'i', 'r', 's', 'c', 'o', 'm'};
12
13
14 public static String encrypt(String cleartext)
15 throws Exception {
16 byte[] rawKey = getRawKey();
17 byte[] result = encrypt(rawKey, cleartext.getBytes());
18 return toHex(result);
19 }
20
21 public static String decrypt(String encrypted)
22 throws Exception {
23
24 byte[] enc = toByte(encrypted);
25 byte[] result = decrypt(enc);
26 return new String(result);
27 }
28
29 private static byte[] getRawKey() throws Exception {
30 SecretKey key = new SecretKeySpec(keyValue, "AES");
31 byte[] raw = key.getEncoded();
32 return raw;
33 }
34
35 private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
36 SecretKey skeySpec = new SecretKeySpec(raw, "AES");
37 Cipher cipher = Cipher.getInstance("AES");
38 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
39 byte[] encrypted = cipher.doFinal(clear);
40 return encrypted;
41 }
42
43 private static byte[] decrypt(byte[] encrypted)
44 throws Exception {
45 SecretKey skeySpec = new SecretKeySpec(keyValue, "AES");
46 Cipher cipher = Cipher.getInstance("AES");
47 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
48 byte[] decrypted = cipher.doFinal(encrypted);
49 return decrypted;
50 }
51
52 public static byte[] toByte(String hexString) {
53 int len = hexString.length() / 2;
54 byte[] result = new byte[len];
55 for (int i = 0; i < len; i++)
56 result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
57 16).byteValue();
58 return result;
59 }
60
61 public static String toHex(byte[] buf) {
62 if (buf == null)
63 return "";
64 StringBuffer result = new StringBuffer(2 * buf.length);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected