github.com/emmansun/gmsm@v0.29.1/sm9/enc_mode_test.go (about)

     1  package sm9_test
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/aes"
     6  	"crypto/rand"
     7  	"encoding/hex"
     8  	"testing"
     9  
    10  	"github.com/emmansun/gmsm/padding"
    11  	"github.com/emmansun/gmsm/sm9"
    12  )
    13  
    14  func TestInvalidKeySize(t *testing.T) {
    15  	encOpts := []sm9.EncrypterOpts{
    16  		sm9.SM4ECBEncrypterOpts, sm9.SM4CBCEncrypterOpts, sm9.SM4CFBEncrypterOpts, sm9.SM4OFBEncrypterOpts,
    17  	}
    18  	for _, opts := range encOpts {
    19  		_, err := opts.Encrypt(rand.Reader, []byte("123456789012345"), []byte("plaintext"))
    20  		if err.Error() != "sm4: invalid key size 15" {
    21  			t.Fatalf("not expected error: %v\n", err.Error())
    22  		}
    23  		_, err = opts.Decrypt([]byte("123456789012345"), []byte("ciphertext"))
    24  		if err.Error() != "sm4: invalid key size 15" {
    25  			t.Fatalf("not expected error: %v\n", err.Error())
    26  		}
    27  	}
    28  }
    29  
    30  func TestInvalidCiphertextSize(t *testing.T) {
    31  	encOpts := []sm9.EncrypterOpts{
    32  		sm9.SM4CBCEncrypterOpts, sm9.SM4CFBEncrypterOpts, sm9.SM4OFBEncrypterOpts,
    33  	}
    34  	for _, opts := range encOpts {
    35  		_, err := opts.Decrypt([]byte("1234567890123450"), []byte("ciphertext"))
    36  		if err.Error() != "sm9: decryption error" {
    37  			t.Fatalf("not expected error: %v\n", err.Error())
    38  		}
    39  	}
    40  }
    41  
    42  func TestEmptyCiphertext(t *testing.T) {
    43  	encOpts := []sm9.EncrypterOpts{
    44  		sm9.SM4ECBEncrypterOpts, sm9.DefaultEncrypterOpts,
    45  	}
    46  	for _, opts := range encOpts {
    47  		_, err := opts.Decrypt([]byte("1234567890123450"), nil)
    48  		if err.Error() != "sm9: decryption error" {
    49  			t.Fatalf("not expected error: %v\n", err.Error())
    50  		}
    51  	}
    52  }
    53  
    54  func TestAESEncryption(t *testing.T) {
    55  	key, _ := hex.DecodeString("6368616e6765207468697320706173736368616e676520746869732070617373")
    56  	plaintext := []byte("Chinese IBE standard")
    57  	aescbc := sm9.NewCBCEncrypterOpts(padding.NewPKCS7Padding(aes.BlockSize), aes.NewCipher, 32)
    58  
    59  	ciphertext, err := aescbc.Encrypt(rand.Reader, key, plaintext)
    60  	if err != nil {
    61  		t.Fatal(err)
    62  	}
    63  	result, err := aescbc.Decrypt(key, ciphertext)
    64  	if err != nil {
    65  		t.Fatal(err)
    66  	}
    67  	if !bytes.Equal(plaintext, result) {
    68  		t.Fatalf("no same")
    69  	}
    70  }