crypto-sm/sm_test.go

63 lines
1.4 KiB
Go
Raw Normal View History

package sm_test
import (
"bytes"
"testing"
"apigo.cc/go/cast"
"apigo.cc/go/crypto-sm"
)
func TestSM2(t *testing.T) {
priv, pub, err := sm.GenerateSM2KeyPair()
if err != nil { t.Fatal(err) }
a, err := sm.NewSM2AndEraseKey(priv, pub)
if err != nil { t.Fatal(err) }
data := []byte("hello sm2")
// Sign with cast.As
sig := cast.As(a.Sign(data))
if len(sig) == 0 { t.Error("Sign failed") }
// Verify
valid, _ := a.Verify(data, sig)
if !valid { t.Error("Verify failed") }
// Encrypt with cast.As
enc := cast.As(a.EncryptBytes(data))
if len(enc) == 0 { t.Error("EncryptBytes failed") }
// Decrypt with cast.As
dec := cast.As(a.DecryptBytes(enc))
if !bytes.Equal(data, dec) { t.Error("DecryptBytes failed") }
}
func TestSM3(t *testing.T) {
data := []byte("hello sm3")
h1 := sm.Sm3(data)
h2 := sm.Sm3(data)
if !bytes.Equal(h1, h2) { t.Error("SM3 non-deterministic") }
}
func TestSM4(t *testing.T) {
key := []byte("1234567890123456")
iv := []byte("1234567890123456")
data := []byte("hello sm4")
// CBC
cipher, _ := sm.NewSM4CBCAndEraseKey(key, iv)
enc := cast.As(cipher.EncryptBytes(data))
if len(enc) == 0 { t.Fatal("EncryptBytes failed") }
dec := cast.As(cipher.DecryptBytes(enc))
if !bytes.Equal(data, dec) { t.Error("DecryptBytes failed") }
// GCM
gcm, _ := sm.NewSM4GCMAndEraseKey(key, iv)
encG := cast.As(gcm.EncryptBytes(data))
decG := cast.As(gcm.DecryptBytes(encG))
if !bytes.Equal(data, decG) { t.Error("GCM failed") }
}