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