· 7 years ago · Aug 31, 2018, 06:56 PM
1
2
3
4
5public static String encrypt(String kunci, String plaintext, int tipe) throws Exception
6 {
7 byte[] rawKey = rawKey(kunci.getBytes(),tipe);
8 byte[] hasil = encrypt(rawKey,plaintext.getBytes());
9 return k_hexa(hasil);
10 }
11
12private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
13 SecretKeySpec s_kunci_rahasia = new SecretKeySpec(raw, "AES");
14 Cipher cipher = Cipher.getInstance("AES");
15 cipher.init(Cipher.ENCRYPT_MODE, s_kunci_rahasia);
16 byte[] encrypted = cipher.doFinal(clear);
17 return encrypted;
18 }
19
20 private static byte[] rawKey(byte[] kunci,int tipe) throws Exception
21 {
22 KeyGenerator kunci_gen = KeyGenerator.getInstance("AES");
23 SecureRandom acak = SecureRandom.getInstance("SHA1PRNG");
24 acak.setSeed(kunci);
25 kunci_gen.init(tipe, acak);
26 SecretKey kunci_rahasia = kunci_gen.generateKey();
27 byte[] raw = kunci_rahasia.getEncoded();
28 return raw;
29 }
30
31public static String k_hexa(byte[] buffer) {
32 if (buffer == null)
33 {
34 return "";
35 }
36 StringBuffer hasil = new StringBuffer(2 * buffer.length);
37 for (int i = 0; i < buffer.length; i++)
38 {
39 appendHex(hasil, buffer[i]);
40 }
41 return hasil.toString();
42
43 }
44
45
46private final static String hexa = "0123456789ABCDEF";
47
48 private static void appendHex(StringBuffer str_buffer, byte b) {
49 str_buffer.append(hexa.charAt((b >> 4) & 0x0f)).append(hexa.charAt(b & 0x0f));
50 }