From 24765d0e35e4e5a390df487bf552b4ad77d3bc20 Mon Sep 17 00:00:00 2001 From: Sun Yimin Date: Mon, 18 Jul 2022 10:13:53 +0800 Subject: [PATCH] supplement unit test cases --- pkcs8/pkcs8_test.go | 2 +- sm4/cbc_cipher_test.go | 60 ++++++++++++++++++++++++++++++++++++++++++ sm9/sm9_key_test.go | 2 +- 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 sm4/cbc_cipher_test.go diff --git a/pkcs8/pkcs8_test.go b/pkcs8/pkcs8_test.go index b2425ea..e35dd1c 100644 --- a/pkcs8/pkcs8_test.go +++ b/pkcs8/pkcs8_test.go @@ -559,7 +559,7 @@ func TestMarshalPrivateKey(t *testing.T) { t.Fatalf("%d: MarshalPrivateKey returned: %s", i, err) } - decodedSM2PrivateKey, _, err := pkcs8.ParsePrivateKey(der, tt.password) + decodedSM2PrivateKey, err := pkcs8.ParsePKCS8PrivateKeySM2(der, tt.password) if err != nil { t.Fatalf("%d: ParsePKCS8PrivateKey returned: %s", i, err) } diff --git a/sm4/cbc_cipher_test.go b/sm4/cbc_cipher_test.go new file mode 100644 index 0000000..8d3f9e7 --- /dev/null +++ b/sm4/cbc_cipher_test.go @@ -0,0 +1,60 @@ +//go:build (amd64 && !generic) || (arm64 && !generic) +// +build amd64,!generic arm64,!generic + +package sm4 + +import ( + "crypto/cipher" + "testing" +) + +// cbcMode is an interface for block ciphers using cipher block chaining. +type cbcMode interface { + cipher.BlockMode + SetIV([]byte) +} + +func TestSetIV(t *testing.T) { + key := make([]byte, 16) + iv := make([]byte, 16) + c, err := NewCipher(key) + if err != nil { + t.Fatal(err) + } + decrypter := cipher.NewCBCDecrypter(c, iv) + cbc, ok := decrypter.(cbcMode) + if !ok { + t.Fatalf("it's not cbc") + } + shouldPanic(t, func() { + cbc.SetIV(iv[1:]) + }) + cbc.SetIV(iv[:]) +} + +func TestCryptBlocks(t *testing.T) { + key := make([]byte, 16) + iv := make([]byte, 16) + src := make([]byte, 32) + c, err := NewCipher(key) + if err != nil { + t.Fatal(err) + } + + decrypter := cipher.NewCBCDecrypter(c, iv) + // test len(src) == 0 + decrypter.CryptBlocks(nil, nil) + + // cipher: input not full blocks + shouldPanic(t, func() { + decrypter.CryptBlocks(src, src[1:]) + }) + // cipher: output smaller than input + shouldPanic(t, func() { + decrypter.CryptBlocks(src[1:], src) + }) + // cipher: invalid buffer overlap + shouldPanic(t, func() { + decrypter.CryptBlocks(src[1:17], src[2:18]) + }) +} diff --git a/sm9/sm9_key_test.go b/sm9/sm9_key_test.go index 74adfb5..2b54d1e 100644 --- a/sm9/sm9_key_test.go +++ b/sm9/sm9_key_test.go @@ -78,7 +78,7 @@ func TestEncryptMasterPrivateKeyMarshalASN1(t *testing.T) { if err != nil { t.Fatal(err) } - masterKey2 := new(SignMasterPrivateKey) + masterKey2 := new(EncryptMasterPrivateKey) err = masterKey2.UnmarshalASN1(der) if err != nil { t.Fatal(err)