github.com/emmansun/gmsm@v0.29.1/cipher/ofb_sm4_test.go (about) 1 package cipher_test 2 3 import ( 4 "bytes" 5 "crypto/cipher" 6 "testing" 7 8 "github.com/emmansun/gmsm/internal/cryptotest" 9 "github.com/emmansun/gmsm/sm4" 10 ) 11 12 type ofbTest struct { 13 name string 14 key []byte 15 iv []byte 16 in []byte 17 out []byte 18 } 19 20 var ofbTests = []ofbTest{ 21 { 22 "OFB-SM4", 23 []byte{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}, 24 []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, 25 []byte{ 26 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 27 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 28 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, 29 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10, 30 }, 31 []byte{ 32 0xbc, 0x71, 0x0d, 0x76, 0x2d, 0x07, 0x0b, 0x26, 0x36, 0x1d, 0xa8, 0x2b, 0x54, 0x56, 0x5e, 0x46, 33 0x07, 0xa0, 0xc6, 0x28, 0x34, 0x74, 0x0a, 0xd3, 0x24, 0x0d, 0x23, 0x91, 0x25, 0xe1, 0x16, 0x21, 34 0xd4, 0x76, 0xb2, 0x1c, 0xc9, 0xf0, 0x49, 0x51, 0xf0, 0x74, 0x1d, 0x2e, 0xf9, 0xe0, 0x94, 0x98, 35 0x15, 0x84, 0xfc, 0x14, 0x2b, 0xf1, 0x3a, 0xa6, 0x26, 0xb8, 0x2f, 0x9d, 0x7d, 0x07, 0x6c, 0xce, 36 }, 37 }, 38 } 39 40 func TestOFB(t *testing.T) { 41 for _, tt := range ofbTests { 42 test := tt.name 43 44 c, err := sm4.NewCipher(tt.key) 45 if err != nil { 46 t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err) 47 continue 48 } 49 50 for j := 0; j <= 5; j += 5 { 51 plaintext := tt.in[0 : len(tt.in)-j] 52 ofb := cipher.NewOFB(c, tt.iv) 53 ciphertext := make([]byte, len(plaintext)) 54 ofb.XORKeyStream(ciphertext, plaintext) 55 if !bytes.Equal(ciphertext, tt.out[:len(plaintext)]) { 56 t.Errorf("%s/%d: encrypting\ninput % x\nhave % x\nwant % x", test, len(plaintext), plaintext, ciphertext, tt.out) 57 } 58 } 59 60 for j := 0; j <= 5; j += 5 { 61 ciphertext := tt.out[0 : len(tt.in)-j] 62 ofb := cipher.NewOFB(c, tt.iv) 63 plaintext := make([]byte, len(ciphertext)) 64 ofb.XORKeyStream(plaintext, ciphertext) 65 if !bytes.Equal(plaintext, tt.in[:len(ciphertext)]) { 66 t.Errorf("%s/%d: decrypting\nhave % x\nwant % x", test, len(ciphertext), plaintext, tt.in) 67 } 68 } 69 70 if t.Failed() { 71 break 72 } 73 } 74 } 75 76 func TestOFBStream(t *testing.T) { 77 t.Run("SM4", func(t *testing.T) { 78 rng := newRandReader(t) 79 80 key := make([]byte, 16) 81 rng.Read(key) 82 83 block, err := sm4.NewCipher(key) 84 if err != nil { 85 panic(err) 86 } 87 88 cryptotest.TestStreamFromBlock(t, block, cipher.NewOFB) 89 }) 90 }