|
| 1 | +package com.howtodoinjava.core.security.concurrent; |
| 2 | + |
| 3 | +import java.security.SecureRandom; |
| 4 | +import java.security.spec.KeySpec; |
| 5 | +import java.util.Base64; |
| 6 | +import java.util.concurrent.Callable; |
| 7 | +import javax.crypto.Cipher; |
| 8 | +import javax.crypto.SecretKey; |
| 9 | +import javax.crypto.SecretKeyFactory; |
| 10 | +import javax.crypto.spec.IvParameterSpec; |
| 11 | +import javax.crypto.spec.PBEKeySpec; |
| 12 | +import javax.crypto.spec.SecretKeySpec; |
| 13 | + |
| 14 | +public class AES256EncryptionTask implements Callable<String> { |
| 15 | + |
| 16 | + private static final int KEY_LENGTH = 256; |
| 17 | + private static final int ITERATION_COUNT = 65536; |
| 18 | + |
| 19 | + private String strToEncrypt; |
| 20 | + private String secretKey; |
| 21 | + private String salt; |
| 22 | + |
| 23 | + public AES256EncryptionTask(String strToEncrypt, String secretKey, String salt) { |
| 24 | + this.strToEncrypt = strToEncrypt; |
| 25 | + this.secretKey = secretKey; |
| 26 | + this.salt = salt; |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public String call() throws Exception { |
| 31 | + return encrypt(strToEncrypt, secretKey, salt); |
| 32 | + } |
| 33 | + |
| 34 | + public String encrypt(String strToEncrypt, String secretKey, String salt) { |
| 35 | + |
| 36 | + try { |
| 37 | + |
| 38 | + SecureRandom secureRandom = new SecureRandom(); |
| 39 | + byte[] iv = new byte[16]; |
| 40 | + secureRandom.nextBytes(iv); |
| 41 | + IvParameterSpec ivspec = new IvParameterSpec(iv); |
| 42 | + |
| 43 | + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); |
| 44 | + KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), ITERATION_COUNT, |
| 45 | + KEY_LENGTH); |
| 46 | + SecretKey tmp = factory.generateSecret(spec); |
| 47 | + SecretKeySpec secretKeySpec = new SecretKeySpec(tmp.getEncoded(), "AES"); |
| 48 | + |
| 49 | + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); |
| 50 | + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec); |
| 51 | + |
| 52 | + byte[] cipherText = cipher.doFinal(strToEncrypt.getBytes("UTF-8")); |
| 53 | + byte[] encryptedData = new byte[iv.length + cipherText.length]; |
| 54 | + System.arraycopy(iv, 0, encryptedData, 0, iv.length); |
| 55 | + System.arraycopy(cipherText, 0, encryptedData, iv.length, cipherText.length); |
| 56 | + |
| 57 | + return Base64.getEncoder().encodeToString(encryptedData); |
| 58 | + } catch (Exception e) { |
| 59 | + // Handle the exception properly |
| 60 | + e.printStackTrace(); |
| 61 | + return null; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments