| | |
| | | */ |
| | | public class SM4Util { |
| | | private static final String ALGORITHM_NAME = "SM4"; |
| | | |
| | | |
| | | private static final String ALGORITHM_MODE = "SM4/ECB/PKCS5Padding"; |
| | | |
| | | |
| | | |
| | | |
| | | static { |
| | | Security.addProvider(new BouncyCastleProvider()); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 生成 SM4 密钥 |
| | | * @return 密钥的 Base64 编码字符串 |
| | |
| | | SecretKey secretKey = kg.generateKey(); |
| | | return Base64.getEncoder().encodeToString(secretKey.getEncoded()); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * SM4 加密 |
| | | * @param plainText 明文 |
| | |
| | | byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); |
| | | return Base64.getEncoder().encodeToString(encryptedBytes); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * SM4 解密 |
| | | * @param cipherText 密文的 Base64 编码字符串 |
| | |
| | | byte[] decryptedBytes = cipher.doFinal(cipherBytes); |
| | | return new String(decryptedBytes, StandardCharsets.UTF_8); |
| | | } |
| | | |
| | | |
| | | public static void main(String[] args) { |
| | | try { |
| | | // 生成密钥 |
| | | String key = generateKey(); |
| | | System.out.println("生成的密钥: " + key); |
| | | |
| | | |
| | | // 明文 |
| | | String plainText = "Hello, SM4!"; |
| | | System.out.println("明文: " + plainText); |
| | | |
| | | |
| | | // 加密 |
| | | String cipherText = encrypt(plainText, key); |
| | | System.out.println("密文: " + cipherText); |
| | | |
| | | |
| | | // 解密 |
| | | String decryptedText = decrypt(cipherText, key); |
| | | System.out.println("解密后的明文: " + decryptedText); |
| | |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | |
| | | |
| | | } |