package org.jeecg.modules.dnc.service.impl; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.Security; @Service public class SecurityService { private static final String ALGORITHM = "SM4/ECB/PKCS5Padding"; private final String secretKey; static { Security.addProvider(new BouncyCastleProvider()); } @Autowired public SecurityService(@Value("${security.encryption-key}") String secretKey) { this.secretKey = secretKey; } public byte[] encrypt(byte[] data) { try { Cipher cipher = Cipher.getInstance(ALGORITHM, "BC"); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "SM4"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); return cipher.doFinal(data); } catch (Exception e) { throw new RuntimeException("加密失败", e); } } public byte[] decrypt(byte[] encryptedData) { try { Cipher cipher = Cipher.getInstance(ALGORITHM, "BC"); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "SM4"); cipher.init(Cipher.DECRYPT_MODE, keySpec); return cipher.doFinal(encryptedData); } catch (Exception e) { throw new RuntimeException("解密失败", e); } } }