gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/sm4soft/padding/pkcs7_padding_io_test.go (about) 1 // Copyright (c) 2022 zhaochun 2 // core-gm is licensed under Mulan PSL v2. 3 // You can use this software according to the terms and conditions of the Mulan PSL v2. 4 // You may obtain a copy of Mulan PSL v2 at: 5 // http://license.coscl.org.cn/MulanPSL2 6 // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 7 // See the Mulan PSL v2 for more details. 8 9 /* 10 sm4soft 是sm4的纯软实现,基于tjfoc国密算法库`tjfoc/gmsm`做了少量修改。 11 对应版权声明: thrid_licenses/github.com/tjfoc/gmsm/版权声明 12 */ 13 14 package padding 15 16 import ( 17 "bytes" 18 "io" 19 "testing" 20 ) 21 22 // 测试P7填充Reader 23 func TestPaddingFileReader_Read(t *testing.T) { 24 srcIn := bytes.NewBuffer(bytes.Repeat([]byte{'A'}, 16)) 25 p := NewPKCS7PaddingReader(srcIn, 16) 26 27 tests := []struct { 28 name string 29 buf []byte 30 want int 31 wantErr error 32 }{ 33 {"读取文件 1B", make([]byte, 1), 1, nil}, 34 {"交叉读取 15B 文件 1B", make([]byte, 16), 16, nil}, 35 {"填充读取 3B", make([]byte, 3), 3, nil}, 36 {"超过填充读取 16B", make([]byte, 16), 12, nil}, 37 {"文件结束 16B", make([]byte, 16), 0, io.EOF}, 38 } 39 for _, tt := range tests { 40 t.Run(tt.name, func(t *testing.T) { 41 got, err := p.Read(tt.buf) 42 if err != tt.wantErr { 43 t.Errorf("Read() error = %v, wantErr %v", err, tt.wantErr) 44 return 45 } 46 if got != tt.want { 47 t.Errorf("Read() 读取到了 = %v, 但是需要 %v", got, tt.want) 48 } 49 }) 50 } 51 } 52 53 // 测试P7填充Writer 54 func TestPKCS7PaddingWriter_Write(t *testing.T) { 55 src := []byte{ 56 0, 1, 2, 3, 4, 5, 6, 7, 57 } 58 paddedSrc := append(src, bytes.Repeat([]byte{0x08}, 8)...) 59 reader := bytes.NewReader(paddedSrc) 60 out := bytes.NewBuffer(make([]byte, 0, 64)) 61 writer := NewPKCS7PaddingWriter(out, 8) 62 63 for { 64 buf := make([]byte, 3) 65 n, err := reader.Read(buf) 66 if err != nil && err != io.EOF { 67 t.Fatal(err) 68 } 69 if n == 0 { 70 break 71 } 72 _, err = writer.Write(buf[:n]) 73 if err != nil { 74 t.Fatal(err) 75 } 76 } 77 err := writer.Final() 78 if err != nil { 79 t.Fatal(err) 80 } 81 82 if !bytes.Equal(out.Bytes(), src) { 83 t.Fatalf("去除填充后实际为 %02X,期待去除填充之后的结果为 %02X", out.Bytes(), src) 84 } 85 }