1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import lombok.extern.slf4j.Slf4j;
import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64;
@Slf4j public class AESEncryptUtils {
public static String encrypt(String input, String keyString, String ivString) { try { SecretKey key = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec iv = new IvParameterSpec(ivString.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); byte[] cipherText = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(cipherText); } catch (InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException | BadPaddingException | InvalidKeyException e) { throw new RuntimeException(e); } }
public static String decrypt(String cipherText, String keyString, String ivString) { try { SecretKey key = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec iv = new IvParameterSpec(ivString.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, iv); byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText)); return new String(plainText, StandardCharsets.UTF_8); } catch (InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException | BadPaddingException | InvalidKeyException e) { throw new RuntimeException(e); } }
public static void main(String[] args) { String keyString = "1234EFghiJklmn56"; String ivString = "abcdEFG890123456"; String plainText = "阿斯蒂芬中文www.baeldung.com符号!@#%……)(*&… …%-——+=)(&^%$#/*-\\|123a阿斯蒂芬"; log.info("plainText:\t\t\t\t{}", plainText); String cipherText = AESEncryptUtils.encrypt(plainText, keyString, ivString); log.info("cipherText:\t\t\t{}", cipherText); String decryptedCipherText = AESEncryptUtils.decrypt(cipherText, keyString, ivString); log.info("decryptedCipherText:\t{}", decryptedCipherText); }
}
|