github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/sm4soft/padding/pkcs7_padding_io_test.go (about)

     1  // Copyright 2022 s1ren@github.com/hxx258456.
     2  
     3  /*
     4  sm4soft 是sm4的纯软实现,基于tjfoc国密算法库`tjfoc/gmsm`做了少量修改。
     5  对应版权声明: thrid_licenses/github.com/tjfoc/gmsm/版权声明
     6  */
     7  
     8  package padding
     9  
    10  import (
    11  	"bytes"
    12  	"io"
    13  	"testing"
    14  )
    15  
    16  // 测试P7填充Reader
    17  func TestPaddingFileReader_Read(t *testing.T) {
    18  	srcIn := bytes.NewBuffer(bytes.Repeat([]byte{'A'}, 16))
    19  	p := NewPKCS7PaddingReader(srcIn, 16)
    20  
    21  	tests := []struct {
    22  		name    string
    23  		buf     []byte
    24  		want    int
    25  		wantErr error
    26  	}{
    27  		{"读取文件 1B", make([]byte, 1), 1, nil},
    28  		{"交叉读取 15B 文件 1B", make([]byte, 16), 16, nil},
    29  		{"填充读取 3B", make([]byte, 3), 3, nil},
    30  		{"超过填充读取 16B", make([]byte, 16), 12, nil},
    31  		{"文件结束 16B", make([]byte, 16), 0, io.EOF},
    32  	}
    33  	for _, tt := range tests {
    34  		t.Run(tt.name, func(t *testing.T) {
    35  			got, err := p.Read(tt.buf)
    36  			if err != tt.wantErr {
    37  				t.Errorf("Read() error = %v, wantErr %v", err, tt.wantErr)
    38  				return
    39  			}
    40  			if got != tt.want {
    41  				t.Errorf("Read() 读取到了 = %v, 但是需要 %v", got, tt.want)
    42  			}
    43  		})
    44  	}
    45  }
    46  
    47  // 测试P7填充Writer
    48  func TestPKCS7PaddingWriter_Write(t *testing.T) {
    49  	src := []byte{
    50  		0, 1, 2, 3, 4, 5, 6, 7,
    51  	}
    52  	paddedSrc := append(src, bytes.Repeat([]byte{0x08}, 8)...)
    53  	reader := bytes.NewReader(paddedSrc)
    54  	out := bytes.NewBuffer(make([]byte, 0, 64))
    55  	writer := NewPKCS7PaddingWriter(out, 8)
    56  
    57  	for {
    58  		buf := make([]byte, 3)
    59  		n, err := reader.Read(buf)
    60  		if err != nil && err != io.EOF {
    61  			t.Fatal(err)
    62  		}
    63  		if n == 0 {
    64  			break
    65  		}
    66  		_, err = writer.Write(buf[:n])
    67  		if err != nil {
    68  			t.Fatal(err)
    69  		}
    70  	}
    71  	err := writer.Final()
    72  	if err != nil {
    73  		t.Fatal(err)
    74  	}
    75  
    76  	if !bytes.Equal(out.Bytes(), src) {
    77  		t.Fatalf("去除填充后实际为 %02X,期待去除填充之后的结果为 %02X", out.Bytes(), src)
    78  	}
    79  }