VppUnCryptoService.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package com.usky.vpp.crypto;
  2. import cn.hutool.core.codec.Base64;
  3. import cn.hutool.crypto.SmUtil;
  4. import cn.hutool.crypto.asymmetric.KeyType;
  5. import cn.hutool.crypto.asymmetric.SM2;
  6. import com.usky.vpp.config.VppUnProperties;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Service;
  11. import org.springframework.util.StringUtils;
  12. import java.nio.charset.StandardCharsets;
  13. /**
  14. * 运管平台 UN/DN 国密加解密与签名(SM2/SM3withSM2)
  15. */
  16. @Service
  17. public class VppUnCryptoService {
  18. private static final Logger log = LoggerFactory.getLogger(VppUnCryptoService.class);
  19. @Autowired
  20. private VppUnProperties properties;
  21. public boolean isActive() {
  22. return Boolean.TRUE.equals(properties.getCryptoEnabled())
  23. && StringUtils.hasText(properties.getUnPublicKey())
  24. && StringUtils.hasText(properties.getDnPrivateKey());
  25. }
  26. public String encryptRequest(String plainJson) {
  27. SM2 sm2 = SmUtil.sm2(null, properties.getUnPublicKey());
  28. return sm2.encryptBase64(plainJson, KeyType.PublicKey);
  29. }
  30. public String signRequest(String cipherBase64) {
  31. SM2 sm2 = SmUtil.sm2(properties.getDnPrivateKey(), null);
  32. byte[] sign = sm2.sign(cipherBase64.getBytes(StandardCharsets.UTF_8));
  33. return Base64.encode(sign);
  34. }
  35. public String decryptResponse(String cipherBase64) {
  36. SM2 sm2 = SmUtil.sm2(properties.getDnPrivateKey(), properties.getDnPublicKey());
  37. return sm2.decryptStr(cipherBase64, KeyType.PrivateKey);
  38. }
  39. public boolean verifyResponse(String cipherBase64, String signBase64) {
  40. return verifyInbound(cipherBase64, signBase64);
  41. }
  42. /** UN→DN 请求验签 */
  43. public boolean verifyInbound(String cipherBase64, String signBase64) {
  44. if (!StringUtils.hasText(signBase64)) {
  45. log.warn("UN 请求缺少 X-Sign,跳过验签");
  46. return true;
  47. }
  48. SM2 sm2 = SmUtil.sm2(null, properties.getUnPublicKey());
  49. return sm2.verify(cipherBase64.getBytes(StandardCharsets.UTF_8), Base64.decode(signBase64));
  50. }
  51. /** UN→DN 请求解密 */
  52. public String decryptInbound(String cipherBase64) {
  53. return decryptResponse(cipherBase64);
  54. }
  55. /** DN→UN 响应加密 */
  56. public String encryptOutbound(String plainJson) {
  57. return encryptRequest(plainJson);
  58. }
  59. /** DN→UN 响应签名 */
  60. public String signOutbound(String cipherBase64) {
  61. return signRequest(cipherBase64);
  62. }
  63. }