github.com/emmansun/gmsm@v0.29.1/sm4/cbc_cipher_test.go (about)

     1  //go:build (amd64 || arm64 || ppc64 || ppc64le) && !purego
     2  
     3  package sm4
     4  
     5  import (
     6  	"crypto/cipher"
     7  	"testing"
     8  )
     9  
    10  // cbcMode is an interface for block ciphers using cipher block chaining.
    11  type cbcMode interface {
    12  	cipher.BlockMode
    13  	SetIV([]byte)
    14  }
    15  
    16  func TestSetIV(t *testing.T) {
    17  	key := make([]byte, 16)
    18  	iv := make([]byte, 16)
    19  	c, err := NewCipher(key)
    20  	if err != nil {
    21  		t.Fatal(err)
    22  	}
    23  	decrypter := cipher.NewCBCDecrypter(c, iv)
    24  	cbc, ok := decrypter.(cbcMode)
    25  	if !ok {
    26  		t.Fatalf("it's not cbc")
    27  	}
    28  	shouldPanic(t, func() {
    29  		cbc.SetIV(iv[1:])
    30  	})
    31  	cbc.SetIV(iv[:])
    32  }
    33  
    34  func TestCryptBlocks(t *testing.T) {
    35  	key := make([]byte, 16)
    36  	iv := make([]byte, 16)
    37  	src := make([]byte, 32)
    38  	c, err := NewCipher(key)
    39  	if err != nil {
    40  		t.Fatal(err)
    41  	}
    42  
    43  	decrypter := cipher.NewCBCDecrypter(c, iv)
    44  	// test len(src) == 0
    45  	decrypter.CryptBlocks(nil, nil)
    46  
    47  	// cipher: input not full blocks
    48  	shouldPanic(t, func() {
    49  		decrypter.CryptBlocks(src, src[1:])
    50  	})
    51  	// cipher: output smaller than input
    52  	shouldPanic(t, func() {
    53  		decrypter.CryptBlocks(src[1:], src)
    54  	})
    55  	// cipher: invalid buffer overlap
    56  	shouldPanic(t, func() {
    57  		decrypter.CryptBlocks(src[1:17], src[2:18])
    58  	})
    59  }