|
| 1 | +package com.howtodoinjava.core.security; |
| 2 | + |
| 3 | +import javax.crypto.Cipher; |
| 4 | +import javax.crypto.SecretKey; |
| 5 | +import javax.crypto.SecretKeyFactory; |
| 6 | +import javax.crypto.spec.IvParameterSpec; |
| 7 | +import javax.crypto.spec.PBEKeySpec; |
| 8 | +import javax.crypto.spec.SecretKeySpec; |
| 9 | +import java.nio.charset.StandardCharsets; |
| 10 | +import java.security.spec.KeySpec; |
| 11 | +import java.util.Base64; |
| 12 | + |
| 13 | +public class AES256 { |
| 14 | + private static final String SECRET_KEY = "my_super_secret_key_ho_ho_ho"; |
| 15 | + private static final String SALT = "ssshhhhhhhhhhh!!!!"; |
| 16 | + |
| 17 | + public static String encrypt(String strToEncrypt) { |
| 18 | + try { |
| 19 | + byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; |
| 20 | + IvParameterSpec ivspec = new IvParameterSpec(iv); |
| 21 | + |
| 22 | + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); |
| 23 | + KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256); |
| 24 | + SecretKey tmp = factory.generateSecret(spec); |
| 25 | + SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); |
| 26 | + |
| 27 | + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); |
| 28 | + cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec); |
| 29 | + return Base64.getEncoder() |
| 30 | + .encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8))); |
| 31 | + } catch (Exception e) { |
| 32 | + System.out.println("Error while encrypting: " + e.toString()); |
| 33 | + } |
| 34 | + return null; |
| 35 | + } |
| 36 | + |
| 37 | + public static String decrypt(String strToDecrypt) { |
| 38 | + try { |
| 39 | + byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; |
| 40 | + IvParameterSpec ivspec = new IvParameterSpec(iv); |
| 41 | + |
| 42 | + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); |
| 43 | + KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256); |
| 44 | + SecretKey tmp = factory.generateSecret(spec); |
| 45 | + SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); |
| 46 | + |
| 47 | + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); |
| 48 | + cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec); |
| 49 | + return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); |
| 50 | + } catch (Exception e) { |
| 51 | + System.out.println("Error while decrypting: " + e.toString()); |
| 52 | + } |
| 53 | + return null; |
| 54 | + } |
| 55 | +} |
0 commit comments