java aes encryption

Solutions on MaxInterview for java aes encryption by the best coders in the world

showing results for - "java aes encryption"
Camille
02 Nov 2019
1import java.io.UnsupportedEncodingException;
2import java.security.MessageDigest;
3import java.security.NoSuchAlgorithmException;
4import java.util.Arrays;
5import java.util.Base64;
6 
7import javax.crypto.Cipher;
8import javax.crypto.spec.SecretKeySpec;
9 
10public class AES {
11 
12    private static SecretKeySpec secretKey;
13    private static byte[] key;
14 
15    public static void setKey(String myKey) 
16    {
17        MessageDigest sha = null;
18        try {
19            key = myKey.getBytes("UTF-8");
20            sha = MessageDigest.getInstance("SHA-1");
21            key = sha.digest(key);
22            key = Arrays.copyOf(key, 16); 
23            secretKey = new SecretKeySpec(key, "AES");
24        } 
25        catch (NoSuchAlgorithmException e) {
26            e.printStackTrace();
27        } 
28        catch (UnsupportedEncodingException e) {
29            e.printStackTrace();
30        }
31    }
32 
33    public static String encrypt(String strToEncrypt, String secret) 
34    {
35        try
36        {
37            setKey(secret);
38            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
39            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
40            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
41        } 
42        catch (Exception e) 
43        {
44            System.out.println("Error while encrypting: " + e.toString());
45        }
46        return null;
47    }
48 
49    public static String decrypt(String strToDecrypt, String secret) 
50    {
51        try
52        {
53            setKey(secret);
54            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
55            cipher.init(Cipher.DECRYPT_MODE, secretKey);
56            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
57        } 
58        catch (Exception e) 
59        {
60            System.out.println("Error while decrypting: " + e.toString());
61        }
62        return null;
63    }
64}
65