· 6 years ago · Aug 11, 2019, 07:44 AM
1Cipher cipher;
2SecretKey secretKey;
3
4String password = "password123";
5
6byte[] encodedKey = Base64.getEncoder().encode(password.getBytes());
7
8try {
9 MessageDigest sha = MessageDigest.getInstance("SHA-1");
10 encodedKey = sha.digest(encodedKey);
11 encodedKey = Arrays.copyOf(encodedKey, 16);
12 key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
13 return key;
14} catch (Exception e) {
15 e.printStackTrace();
16}
17
18Cipher cipher;
19
20try {
21 cipher = Cipher.getInstance("AES");
22 cipher.init(Cipher.ENCRYPT_MODE, key);
23
24 byte[] cipherText = cipher.doFinal("thisisamessage".getBytes());
25
26 System.out.println(cipherText);
27} catch(Exception e) {
28 e.printStackTrace();
29}
30
31Cipher cipher;
32
33try {
34 cipher = Cipher.getInstance("AES");
35 cipher.init(Cipher.DECRYPT_MODE, key);
36
37 byte[] plainText= cipher.doFinal(encrypted_message.getBytes());
38
39 System.out.println(plainText);
40} catch(Exception e) {
41 e.printStackTrace();
42}