2026-04-23 21:02:09 +08:00
|
|
|
package sm_test
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
|
|
"apigo.cc/go/crypto-sm"
|
|
|
|
|
"github.com/emmansun/gmsm/sm3"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func TestSM2_AllModes(t *testing.T) {
|
|
|
|
|
priv, pub, _ := sm.GenerateSM2KeyPair()
|
|
|
|
|
data := []byte("sm2 comprehensive test")
|
|
|
|
|
|
|
|
|
|
a, _ := sm.NewSM2AndEraseKey(priv, pub)
|
|
|
|
|
|
2026-04-23 21:49:25 +08:00
|
|
|
// MustSign
|
|
|
|
|
sig := a.MustSign(data)
|
|
|
|
|
if len(sig) == 0 { t.Error("MustSign failed") }
|
|
|
|
|
|
|
|
|
|
// MustVerify
|
|
|
|
|
if !a.MustVerify(data, sig) { t.Error("MustVerify failed") }
|
|
|
|
|
|
|
|
|
|
// MustEncrypt
|
|
|
|
|
enc := a.MustEncrypt(data)
|
|
|
|
|
if len(enc) == 0 { t.Error("MustEncrypt failed") }
|
|
|
|
|
|
|
|
|
|
// MustDecrypt
|
|
|
|
|
dec := a.MustDecrypt(enc)
|
|
|
|
|
if !bytes.Equal(data, dec) { t.Error("MustDecrypt failed") }
|
2026-04-23 21:02:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestSM3_Compatibility(t *testing.T) {
|
|
|
|
|
data := []byte("hello sm3")
|
|
|
|
|
|
|
|
|
|
h := sm3.New()
|
|
|
|
|
h.Write(data)
|
|
|
|
|
expected := h.Sum(nil)
|
|
|
|
|
|
|
|
|
|
if !bytes.Equal(sm.Sm3(data), expected) {
|
|
|
|
|
t.Error("SM3 hash mismatch")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if sm.Sm3ToHex(data) == "" { t.Error("Sm3ToHex failed") }
|
|
|
|
|
if sm.Sm3ToBase64(data) == "" { t.Error("Sm3ToBase64 failed") }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestSM4_Exhaustive(t *testing.T) {
|
|
|
|
|
key := bytes.Repeat([]byte{0x01}, 16)
|
|
|
|
|
iv := bytes.Repeat([]byte{0x02}, 16)
|
|
|
|
|
data := []byte("sm4 exhaustive testing")
|
|
|
|
|
|
|
|
|
|
cipher, _ := sm.NewSM4CBCWithOutEraseKey(key, iv)
|
|
|
|
|
|
|
|
|
|
// 1. CBC
|
2026-04-23 21:49:25 +08:00
|
|
|
enc := cipher.MustEncrypt(data)
|
|
|
|
|
if len(enc) == 0 { t.Fatal("MustEncrypt failed") }
|
|
|
|
|
|
|
|
|
|
dec := cipher.MustDecrypt(enc)
|
2026-04-23 21:02:09 +08:00
|
|
|
if !bytes.Equal(data, dec) { t.Error("SM4 CBC roundtrip failed") }
|
|
|
|
|
|
|
|
|
|
// 2. GCM
|
|
|
|
|
gcm, _ := sm.NewSM4GCMWithOutEraseKey(key, iv[:12])
|
2026-04-23 21:49:25 +08:00
|
|
|
encG := gcm.MustEncrypt(data)
|
|
|
|
|
decG := gcm.MustDecrypt(encG)
|
2026-04-23 21:02:09 +08:00
|
|
|
if !bytes.Equal(data, decG) { t.Error("SM4 GCM roundtrip failed") }
|
|
|
|
|
|
2026-04-23 21:49:25 +08:00
|
|
|
// 3. TryDecrypt
|
2026-04-23 21:02:09 +08:00
|
|
|
damaged := append([]byte(nil), enc...)
|
|
|
|
|
damaged[len(damaged)-1] ^= 0xFF
|
2026-04-23 21:49:25 +08:00
|
|
|
|
|
|
|
|
// TryDecrypt should return the damaged data
|
|
|
|
|
decT := cipher.TryDecrypt(damaged)
|
|
|
|
|
if !bytes.Equal(decT, damaged) {
|
|
|
|
|
t.Error("TryDecrypt should return original damaged data")
|
2026-04-23 21:02:09 +08:00
|
|
|
}
|
|
|
|
|
}
|