gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/sm4soft/padding/bloc_cryptor_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  	"crypto/cipher"
    19  	"crypto/rand"
    20  	"fmt"
    21  	"testing"
    22  
    23  	"gitee.com/ks-custle/core-gm/sm4soft"
    24  )
    25  
    26  func TestP7BlockDecrypt(t *testing.T) {
    27  	src := bytes.Repeat([]byte{7}, 16)
    28  
    29  	srcIn := bytes.NewBuffer(src)
    30  	encOut := bytes.NewBuffer(make([]byte, 0, 1024))
    31  
    32  	key := make([]byte, 16)
    33  	iv := make([]byte, 16)
    34  	_, _ = rand.Read(key)
    35  	_, _ = rand.Read(iv)
    36  	fmt.Printf("key: %02X\n", key)
    37  	fmt.Printf("iv : %02X\n", iv)
    38  	block, err := sm4soft.NewCipher(key)
    39  	if err != nil {
    40  		t.Fatal(err)
    41  	}
    42  	encrypter := cipher.NewCBCEncrypter(block, iv)
    43  
    44  	err = P7BlockEnc(encrypter, srcIn, encOut)
    45  	if err != nil {
    46  		t.Fatal(err)
    47  	}
    48  	fmt.Printf("原文: %02X\n", src)
    49  	fmt.Printf("加密: %02X\n", encOut.Bytes())
    50  
    51  	decrypter := cipher.NewCBCDecrypter(block, iv)
    52  	decOut := bytes.NewBuffer(make([]byte, 0, 1024))
    53  	err = P7BlockDecrypt(decrypter, encOut, decOut)
    54  	if err != nil {
    55  		t.Fatal(err)
    56  	}
    57  
    58  	fmt.Printf("解密: %02X\n", decOut.Bytes())
    59  	if !bytes.Equal(src, decOut.Bytes()) {
    60  		t.Fatalf("实际解密结果: %02X, 期待结果: %02X", decOut.Bytes(), src)
    61  	}
    62  }