在Java中实现SM4加密,你可以使用Java自带的javax.crypto
包。以下是一个简单的示例,展示了如何使用SM4进行加密和解密:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class SM4Encryption { public static void main(String[] args) throws Exception { // 生成密钥 SecretKey secretKey = generateSM4Key(); // 加密 String plainText = "Hello, SM4!"; String encryptedText = encrypt(plainText, secretKey); System.out.println("Encrypted text: " + encryptedText); // 解密 String decryptedText = decrypt(encryptedText, secretKey); System.out.println("Decrypted text: " + decryptedText); } // 生成SM4密钥 public static SecretKey generateSM4Key() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("SM4"); keyGenerator.init(128); return keyGenerator.generateKey(); } // SM4加密 public static String encrypt(String plainText, SecretKey secretKey) throws Exception { Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } // SM4解密 public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception { Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); return new String(decryptedBytes); } }
这个示例中,我们首先生成一个SM4密钥,然后使用该密钥对明文进行加密,并将加密后的密文进行Base64编码以便于显示和传输。接着,我们使用相同的密钥对密文进行解密,恢复原始的明文。
注意:在实际应用中,你可能需要考虑密钥的存储和管理,以及加密和解密过程中的异常处理。