github.com/emmansun/gmsm@v0.29.1/cipher/ofbnlf_test.go (about)

     1  package cipher_test
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/rand"
     6  	"encoding/hex"
     7  	"io"
     8  	"testing"
     9  
    10  	"github.com/emmansun/gmsm/cipher"
    11  	"github.com/emmansun/gmsm/sm4"
    12  )
    13  
    14  var ofbnlfSM4TestVectors = []struct {
    15  	key        string
    16  	iv         string
    17  	plaintext  string
    18  	ciphertext string
    19  }{
    20  	{
    21  		"2B7E151628AED2A6ABF7158809CF4F3C",
    22  		"000102030405060708090A0B0C0D0E0F",
    23  		"6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710",
    24  		"00A5B5C9E645557C20CE7F267736F308A18037828850B9D78883CA622851F86CB7CAEFDFB6D4CABA6AE2D2FCE369CEB31001DD71FDDA9341F8D221CB720FF27B",
    25  	},
    26  }
    27  
    28  func TestOFBNLF(t *testing.T) {
    29  	for i, test := range ofbnlfSM4TestVectors {
    30  		key, _ := hex.DecodeString(test.key)
    31  		iv, _ := hex.DecodeString(test.iv)
    32  		plaintext, _ := hex.DecodeString(test.plaintext)
    33  		ciphertext, _ := hex.DecodeString(test.ciphertext)
    34  		got := make([]byte, len(plaintext))
    35  		encrypter, err := cipher.NewOFBNLFEncrypter(sm4.NewCipher, key, iv)
    36  		if err != nil {
    37  			t.Fatal(err)
    38  		}
    39  		encrypter.CryptBlocks(got, plaintext)
    40  		if !bytes.Equal(got, ciphertext) {
    41  			t.Fatalf("%v case encrypt failed, got %x\n", i+1, got)
    42  		}
    43  
    44  		decrypter, err := cipher.NewOFBNLFDecrypter(sm4.NewCipher, key, iv)
    45  		if err != nil {
    46  			t.Fatal(err)
    47  		}
    48  		decrypter.CryptBlocks(got, ciphertext)
    49  		if !bytes.Equal(got, plaintext) {
    50  			t.Fatalf("%v case decrypt failed, got %x\n", i+1, got)
    51  		}
    52  	}
    53  }
    54  
    55  func TestSM4OFBNLFRandom(t *testing.T) {
    56  	key, _ := hex.DecodeString(ofbnlfSM4TestVectors[0].key)
    57  	iv := []byte("0123456789ABCDEF")
    58  	encrypter, _ := cipher.NewOFBNLFEncrypter(sm4.NewCipher, key, iv)
    59  	decrypter, _ := cipher.NewOFBNLFDecrypter(sm4.NewCipher, key, iv)
    60  	for i := 1; i <= 50; i++ {
    61  		plaintext := make([]byte, i*16)
    62  		ciphertext := make([]byte, i*16)
    63  		got := make([]byte, i*16)
    64  		io.ReadFull(rand.Reader, plaintext)
    65  		encrypter.CryptBlocks(ciphertext, plaintext)
    66  		decrypter.CryptBlocks(got, ciphertext)
    67  		if !bytes.Equal(got, plaintext) {
    68  			t.Errorf("test %v blocks failed", i)
    69  		}
    70  	}
    71  }