概述
本文详细介绍了如何在Java和Golang中使用SM4算法进行对称加密和解密操作。通过使用CBC模式和PKCS5填充,成功实现了跨语言的数据加密和解密。无论是Java加密后在Golang解密,还是Golang加密后在Java解密,均通过了测试验证,保证了两种语言在处理国密SM4算法时的兼容性和一致性。
前期准备
Java 国密库
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
Golang 国密库
<!--https://github.com/Hyperledger-TWGC/ccs-gm-->
go get github.com/Hyperledger-TWGC/ccs-gm
国密SM4对称加解密
Java 加密 Golang 解密
Java 加密
/**
* 生成SM4密钥和密文 必须使用CBC模式
*
* @param data 需要加密的数据
*/
publicstaticvoidgenerateKeyAndCiphertext(byte[] data){
// 生成SM4密钥
KeyGeneratorkeyGen=null;
try{
// 生成SM4密钥
keyGen =KeyGenerator.getInstance("SM4","BC");
keyGen.init(128);// SM4使用128位密钥
SecretKeysecretKey= keyGen.generateKey();
byte[] key = secretKey.getEncoded();
// 生成随机的IV向量
byte[] iv =newbyte[16];
SecureRandomrandom=newSecureRandom();
random.nextBytes(iv);
IvParameterSpecivSpec=newIvParameterSpec(iv);
// 使用SM4进行加密
Ciphercipher=Cipher.getInstance("SM4/CBC/PKCS5Padding","BC");
cipher.init(Cipher.ENCRYPT_MODE,newSecretKeySpec(key,"SM4"), ivSpec);
byte[] encrypted = cipher.doFinal(data);
// 编码密钥、IV和密文为Base64
StringkeyBase64=Base64.toBase64String(key);
StringivBase64=Base64.toBase64String(iv);
StringencryptedBase64=Base64.toBase64String(encrypted);
// 输出Base64编码的密钥、IV和密文
System.out.println("Key (Base64): "+ keyBase64);
System.out.println("IV (Base64): "+ ivBase64);
System.out.println("Encrypted Data (Base64): "+ encryptedBase64);
}catch(Exception e){
thrownewRuntimeException(e);
}
}
Golang 解密
/**
* SM4解密
* @param keyBase64 密钥Base64编码
* @param encryptedBase64 密文Base64编码
*/
func DecodeCiphertext(keyBase64, ivBase64, encryptedBase64 string)[]byte{
// 解码Base64编码的密钥、IV和密文
key, err := base64.StdEncoding.DecodeString(keyBase64)
if err !=nil{
log.Fatalf("Failed to decode key: %v", err)
}
iv, err := base64.StdEncoding.DecodeString(ivBase64)
if err !=nil{
log.Fatalf("Failed to decode IV: %v", err)
}
encryptedData, err := base64.StdEncoding.DecodeString(encryptedBase64)
if err !=nil{
log.Fatalf("Failed to decode encrypted data: %v", err)
}
// 创建SM4解密器
block, err := sm4.NewCipher(key)
if err !=nil{
log.Fatalf("Failed to create SM4 cipher: %v", err)
}
// 创建CBC解密模式
mode := cipher.NewCBCDecrypter(block, iv)
// 解密数据
decryptedData :=make([]byte,len(encryptedData))
mode.CryptBlocks(decryptedData, encryptedData)
// 移除PKCS5填充
decryptedData, err =RemovePKCS5Padding(decryptedData)
if err !=nil{
log.Fatalf("Failed to remove padding: %v", err)
}
fmt.Printf("Decrypted Data: %s\n",string(decryptedData))
return decryptedData
}
结果对比
Java
sm.generateKeyAndCiphertext("hello world".getBytes(StandardCharsets.UTF_8));
Key (Base64): 7TD7k33kyXB4d8VWK/HcDQ==
IV (Base64): x2MZrm+WXlZSSoyoqf/e6A==
Encrypted Data (Base64): GmZPfuyGYJAGWKpIQdeTpQ==
golang
func TestDecodeCiphertext(t *testing.T) {
keyBase64 := "7TD7k33kyXB4d8VWK/HcDQ=="
encryptedBase64 := "GmZPfuyGYJAGWKpIQdeTpQ=="
t.Log(DecodeCiphertext(keyBase64, "x2MZrm+WXlZSSoyoqf/e6A==", encryptedBase64))
}
=== RUN TestDecodeCiphertext
DecryptedData: hello world
sm_test.go:25:[10410110810811132119111114108100]
--- PASS:TestDecodeCiphertext(0.00s)
PASS
Golang 加密 Java 解密
Golang 加密
/**
* SM4加密
* @param data 待加密数据
* @return keyBase64 密钥Base64编码
*/
func EncodeChainText(data []byte)(keyBase64, ivBase64, encryptedBase64 string){
// 生成SM4密钥
key :=make([]byte,16)
if _, err := io.ReadFull(rand.Reader, key); err !=nil{
log.Fatalf("Failed to generate key: %v", err)
}
// 生成随机的IV向量
iv :=make([]byte,16)
if _, err := io.ReadFull(rand.Reader, iv); err !=nil{
log.Fatalf("Failed to generate IV: %v", err)
}
// 创建SM4加密器
block, err := sm4.NewCipher(key)
if err !=nil{
log.Fatalf("Failed to create SM4 cipher: %v", err)
}
// 使用CBC模式加密
mode := cipher.NewCBCEncrypter(block, iv)
// 添加PKCS5填充
paddedData := PKCS5Padding(data, block.BlockSize())
// 加密数据
encryptedData :=make([]byte,len(paddedData))
mode.CryptBlocks(encryptedData, paddedData)
// 编码密钥、IV和密文为Base64
keyBase64 = base64.StdEncoding.EncodeToString(key)
ivBase64 = base64.StdEncoding.EncodeToString(iv)
encryptedBase64 = base64.StdEncoding.EncodeToString(encryptedData)
// 输出Base64编码的密钥、IV和密文
fmt.Println("Key (Base64):", keyBase64)
fmt.Println("IV (Base64):", ivBase64)
fmt.Println("Encrypted Data (Base64):", encryptedBase64)
return keyBase64, ivBase64, encryptedBase64
}
Java 解密
/**
* SM4 解密
*
* @param keyBase64 key
* @param ivBase64 iv
* @param encryptedBase64 密文
*/
publicstaticvoidDecodeCipertext(String keyBase64, String ivBase64, String encryptedBase64){
// 解码Base64编码的密钥、IV和密文
byte[] key =Base64.decode(keyBase64);
byte[] iv =Base64.decode(ivBase64);
byte[] encryptedData =Base64.decode(encryptedBase64);
// 使用SM4进行解密
Ciphercipher=null;
try{
cipher =Cipher.getInstance("SM4/CBC/PKCS5Padding","BC");
cipher.init(Cipher.DECRYPT_MODE,newSecretKeySpec(key,"SM4"),newIvParameterSpec(iv));
byte[] decryptedData = cipher.doFinal(encryptedData);
// 输出解密后的数据
System.out.println("Decrypted Data: "+newString(decryptedData,"UTF-8"));
}catch(Exception e){
thrownewRuntimeException(e);
}
}
结果对比
golang
func TestEncodeChainText(t *testing.T) {
EncodeChainText([]byte("hello go"))
}
=== RUN TestEncodeChainText
Key (Base64): SxxgXVsnCpwak5go/wTqMg==
IV (Base64): xenl6HJR+yvvfMonpjYYug==
Encrypted Data (Base64): XgiZU0fklp+Asc0kJBfYqg==
--- PASS: TestEncodeChainText (0.00s)
PASS
java
sm.DecodeCipertext("SxxgXVsnCpwak5go/wTqMg==", "xenl6HJR+yvvfMonpjYYug==", "XgiZU0fklp+Asc0kJBfYqg==");
Decrypted Data: hello go
Process finished with exit code 0
总结
-
1. SM4加解密使用CBC模式,测试通过