CryptoService.java 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.ymwk.icvp.pki.service.impl;
  2. import lombok.Value;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.stereotype.Component;
  5. import javax.crypto.Cipher;
  6. import javax.crypto.spec.GCMParameterSpec;
  7. import javax.crypto.spec.SecretKeySpec;
  8. import java.nio.charset.StandardCharsets;
  9. import java.security.SecureRandom;
  10. import java.util.Base64;
  11. @Component
  12. @Slf4j
  13. public class CryptoService {
  14. private final String masterKey = "12345678901234567890123456789012"; // 32字节的主密钥
  15. private static final String ALGORITHM = "AES/GCM/NoPadding";
  16. private static final int GCM_IV_LENGTH = 12;
  17. private static final int GCM_TAG_LENGTH = 128;
  18. /**
  19. * AES-GCM加密
  20. */
  21. public String encrypt(String plaintext) throws Exception {
  22. byte[] iv = new byte[GCM_IV_LENGTH];
  23. SecureRandom random = new SecureRandom();
  24. random.nextBytes(iv);
  25. Cipher cipher = Cipher.getInstance(ALGORITHM);
  26. SecretKeySpec keySpec = new SecretKeySpec(
  27. masterKey.getBytes(StandardCharsets.UTF_8),
  28. "AES"
  29. );
  30. GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
  31. cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec);
  32. byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
  33. // 将IV和密文合并(Base64编码)
  34. byte[] combined = new byte[iv.length + ciphertext.length];
  35. System.arraycopy(iv, 0, combined, 0, iv.length);
  36. System.arraycopy(ciphertext, 0, combined, iv.length, ciphertext.length);
  37. return Base64.getEncoder().encodeToString(combined);
  38. }
  39. /**
  40. * AES-GCM解密
  41. */
  42. public String decrypt(String ciphertextBase64) throws Exception {
  43. byte[] combined = Base64.getDecoder().decode(ciphertextBase64);
  44. // 提取IV和密文
  45. byte[] iv = new byte[GCM_IV_LENGTH];
  46. byte[] ciphertext = new byte[combined.length - GCM_IV_LENGTH];
  47. System.arraycopy(combined, 0, iv, 0, GCM_IV_LENGTH);
  48. System.arraycopy(combined, GCM_IV_LENGTH, ciphertext, 0, ciphertext.length);
  49. Cipher cipher = Cipher.getInstance(ALGORITHM);
  50. SecretKeySpec keySpec = new SecretKeySpec(
  51. masterKey.getBytes(StandardCharsets.UTF_8),
  52. "AES"
  53. );
  54. GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
  55. cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec);
  56. byte[] plaintext = cipher.doFinal(ciphertext);
  57. return new String(plaintext, StandardCharsets.UTF_8);
  58. }
  59. }