github.com/emmansun/gmsm@v0.29.1/sm9/sm9_test.go (about)

     1  package sm9
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/hex"
     6  	"math/big"
     7  	"testing"
     8  
     9  	"github.com/emmansun/gmsm/internal/bigmod"
    10  	"github.com/emmansun/gmsm/internal/subtle"
    11  	"github.com/emmansun/gmsm/sm3"
    12  	"github.com/emmansun/gmsm/sm9/bn256"
    13  	"golang.org/x/crypto/cryptobyte"
    14  )
    15  
    16  func bigFromHex(s string) *big.Int {
    17  	b, ok := new(big.Int).SetString(s, 16)
    18  	if !ok {
    19  		panic("sm9/elliptic: internal error: invalid encoding")
    20  	}
    21  	return b
    22  }
    23  
    24  func TestHashH1(t *testing.T) {
    25  	expected := "2acc468c3926b0bdb2767e99ff26e084de9ced8dbc7d5fbf418027b667862fab"
    26  	h := hashH1([]byte{0x41, 0x6c, 0x69, 0x63, 0x65, 0x01})
    27  	if hex.EncodeToString(h.Bytes(orderNat)) != expected {
    28  		t.Errorf("got %v, expected %v", h.Bytes(orderNat), expected)
    29  	}
    30  }
    31  
    32  func TestHashH2(t *testing.T) {
    33  	expected := "823c4b21e4bd2dfe1ed92c606653e996668563152fc33f55d7bfbb9bd9705adb"
    34  	zStr := "4368696E65736520494253207374616E6461726481377B8FDBC2839B4FA2D0E0F8AA6853BBBE9E9C4099608F8612C6078ACD7563815AEBA217AD502DA0F48704CC73CABB3C06209BD87142E14CBD99E8BCA1680F30DADC5CD9E207AEE32209F6C3CA3EC0D800A1A42D33C73153DED47C70A39D2E8EAF5D179A1836B359A9D1D9BFC19F2EFCDB829328620962BD3FDF15F2567F58A543D25609AE943920679194ED30328BB33FD15660BDE485C6B79A7B32B013983F012DB04BA59FE88DB889321CC2373D4C0C35E84F7AB1FF33679BCA575D67654F8624EB435B838CCA77B2D0347E65D5E46964412A096F4150D8C5EDE5440DDF0656FCB663D24731E80292188A2471B8B68AA993899268499D23C89755A1A89744643CEAD40F0965F28E1CD2895C3D118E4F65C9A0E3E741B6DD52C0EE2D25F5898D60848026B7EFB8FCC1B2442ECF0795F8A81CEE99A6248F294C82C90D26BD6A814AAF475F128AEF43A128E37F80154AE6CB92CAD7D1501BAE30F750B3A9BD1F96B08E97997363911314705BFB9A9DBB97F75553EC90FBB2DDAE53C8F68E42"
    35  	z, err := hex.DecodeString(zStr)
    36  	if err != nil {
    37  		t.Fatal(err)
    38  	}
    39  	h := hashH2(z)
    40  	if hex.EncodeToString(h.Bytes(orderNat)) != expected {
    41  		t.Errorf("got %v, expected %v", h.Bytes(orderNat), expected)
    42  	}
    43  }
    44  
    45  func TestSign(t *testing.T) {
    46  	masterKey, err := GenerateSignMasterKey(rand.Reader)
    47  	hashed := []byte("Chinese IBS standard")
    48  	uid := []byte("emmansun")
    49  	hid := byte(0x01)
    50  	if err != nil {
    51  		t.Fatal(err)
    52  	}
    53  	userKey, err := masterKey.GenerateUserKey(uid, hid)
    54  	if err != nil {
    55  		t.Fatal(err)
    56  	}
    57  	h, s, err := Sign(rand.Reader, userKey, hashed)
    58  	if err != nil {
    59  		t.Fatal(err)
    60  	}
    61  	if !Verify(masterKey.Public(), uid, hid, hashed, h, s) {
    62  		t.Errorf("Verify failed")
    63  	}
    64  	sNeg := new(bn256.G1).Neg(s)
    65  	if Verify(masterKey.Public(), uid, hid, hashed, h, sNeg) {
    66  		t.Errorf("Verify with s=-s succeeded")
    67  	}
    68  	hashed[0] ^= 0xff
    69  	if Verify(masterKey.Public(), uid, hid, hashed, h, s) {
    70  		t.Errorf("Verify always works!")
    71  	}
    72  }
    73  
    74  func TestNegativeInputs(t *testing.T) {
    75  	masterKey, err := GenerateSignMasterKey(rand.Reader)
    76  	hashed := []byte("Chinese IBS standard")
    77  	uid := []byte("emmansun")
    78  	hid := byte(0x01)
    79  	if err != nil {
    80  		t.Fatal(err)
    81  	}
    82  	h := new(big.Int).SetInt64(1)
    83  	h.Lsh(h, 550 /* larger than any supported curve */)
    84  	h.Neg(h)
    85  	if Verify(masterKey.Public(), uid, hid, hashed, h, bn256.Gen1) {
    86  		t.Errorf("bogus signature accepted")
    87  	}
    88  }
    89  
    90  func TestZeroSignature(t *testing.T) {
    91  	masterKey, err := GenerateSignMasterKey(rand.Reader)
    92  	hashed := []byte("Chinese IBS standard")
    93  	uid := []byte("emmansun")
    94  	hid := byte(0x01)
    95  	if err != nil {
    96  		t.Fatal(err)
    97  	}
    98  	if Verify(masterKey.Public(), uid, hid, hashed, big.NewInt(0), bn256.Gen1) {
    99  		t.Error("Verify with h=0 succeeded")
   100  	}
   101  	if Verify(masterKey.Public(), uid, hid, hashed, bn256.Order, bn256.Gen1) {
   102  		t.Error("Verify with h=order succeeded")
   103  	}
   104  }
   105  
   106  func TestSignASN1(t *testing.T) {
   107  	masterKey, err := GenerateSignMasterKey(rand.Reader)
   108  	hashed := []byte("Chinese IBS standard")
   109  	uid := []byte("emmansun")
   110  	hid := byte(0x01)
   111  	if err != nil {
   112  		t.Fatal(err)
   113  	}
   114  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   115  	if err != nil {
   116  		t.Fatal(err)
   117  	}
   118  	sig, err := userKey.Sign(rand.Reader, hashed, nil)
   119  	if err != nil {
   120  		t.Fatal(err)
   121  	}
   122  	if !masterKey.Public().Verify(uid, hid, hashed, sig) {
   123  		t.Errorf("Verify failed")
   124  	}
   125  	sig[0] = 0xff
   126  	if masterKey.Public().Verify(uid, hid, hashed, sig) {
   127  		t.Errorf("Verify with invalid asn1 format successed")
   128  	}
   129  }
   130  
   131  func TestParseInvalidASN1(t *testing.T) {
   132  	tests := []struct {
   133  		name   string
   134  		sigHex string
   135  	}{
   136  		// TODO: Add test cases.
   137  		{"invalid point format", "30660420723a8b38dd2441c2aa1c3ec092eaa34996c53bf9ca7515272395c012ab6e6e070342000C389fc45b711d9dfd9d91958f64d89d3528cf577c6dc2bc792c2969188e76865e16c2d85419f8f923a0e77c7f269c0eeb97b6c4d7e2735189180ec719a380fe1d"},
   138  		{"invalid point encoding length", "30660420723a8b38dd2441c2aa1c3ec092eaa34996c53bf9ca7515272395c012ab6e6e0703420004389fc45b711d9dfd9d91958f64d89d3528cf577c6dc2bc792c2969188e76865e16c2d85419f8f923a0e77c7f269c0eeb97b6c4d7e2735189180ec719a380fe"},
   139  	}
   140  	for _, tt := range tests {
   141  		sig, err := hex.DecodeString(tt.sigHex)
   142  		if err != nil {
   143  			t.Fatal(err)
   144  		}
   145  		_, _, err = parseSignature(sig)
   146  		if err == nil {
   147  			t.Errorf("%s should be failed", tt.name)
   148  		}
   149  	}
   150  }
   151  
   152  func signMasterPrivateKeyFromHex(s string) (*SignMasterPrivateKey, error) {
   153  	kb, err := hex.DecodeString(s)
   154  	if err != nil {
   155  		return nil, err
   156  	}
   157  	var b cryptobyte.Builder
   158  	b.AddASN1BigInt(new(big.Int).SetBytes(kb))
   159  	kb, _ = b.Bytes()
   160  	testkey := new(SignMasterPrivateKey)
   161  	err = testkey.UnmarshalASN1(kb)
   162  	if err != nil {
   163  		return nil, err
   164  	}
   165  	return testkey, nil
   166  }
   167  
   168  // SM9 Appendix A
   169  func TestSignSM9Sample(t *testing.T) {
   170  	expectedH := bigFromHex("823c4b21e4bd2dfe1ed92c606653e996668563152fc33f55d7bfbb9bd9705adb")
   171  	expectedHNat, err := bigmod.NewNat().SetBytes(expectedH.Bytes(), orderNat)
   172  	if err != nil {
   173  		t.Fatal(err)
   174  	}
   175  	expectedS := "0473bf96923ce58b6ad0e13e9643a406d8eb98417c50ef1b29cef9adb48b6d598c856712f1c2e0968ab7769f42a99586aed139d5b8b3e15891827cc2aced9baa05"
   176  	hash := []byte("Chinese IBS standard")
   177  	hid := byte(0x01)
   178  	uid := []byte("Alice")
   179  	r := bigFromHex("033c8616b06704813203dfd00965022ed15975c662337aed648835dc4b1cbe")
   180  	rNat, err := bigmod.NewNat().SetBytes(r.Bytes(), orderNat)
   181  	if err != nil {
   182  		t.Fatal(err)
   183  	}
   184  
   185  	masterKey, err := signMasterPrivateKeyFromHex("0130E78459D78545CB54C587E02CF480CE0B66340F319F348A1D5B1F2DC5F4")
   186  	if err != nil {
   187  		t.Fatal(err)
   188  	}
   189  
   190  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   191  	if err != nil {
   192  		t.Fatal(err)
   193  	}
   194  	w, err := userKey.SignMasterPublicKey.ScalarBaseMult(bn256.NormalizeScalar(r.Bytes()))
   195  	if err != nil {
   196  		t.Fatal(err)
   197  	}
   198  
   199  	var buffer []byte
   200  	buffer = append(buffer, hash...)
   201  	buffer = append(buffer, w.Marshal()...)
   202  
   203  	h := hashH2(buffer)
   204  	if h.Equal(expectedHNat) == 0 {
   205  		t.Fatal("not same h")
   206  	}
   207  
   208  	rNat.Sub(h, orderNat)
   209  
   210  	s, err := new(bn256.G1).ScalarMult(userKey.PrivateKey, rNat.Bytes(orderNat))
   211  	if err != nil {
   212  		t.Fatal(err)
   213  	}
   214  
   215  	if hex.EncodeToString(s.MarshalUncompressed()) != expectedS {
   216  		t.Fatal("not same S")
   217  	}
   218  }
   219  
   220  // SM9 Appendix B
   221  func TestKeyExchangeSample(t *testing.T) {
   222  	hid := byte(0x02)
   223  	expectedPube := "9174542668e8f14ab273c0945c3690c66e5dd09678b86f734c4350567ed0628354e598c6bf749a3dacc9fffedd9db6866c50457cfc7aa2a4ad65c3168ff74210"
   224  	expectedKey := "c5c13a8f59a97cdeae64f16a2272a9e7"
   225  	expectedSignatureB := "3bb4bcee8139c960b4d6566db1e0d5f0b2767680e5e1bf934103e6c66e40ffee"
   226  	expectedSignatureA := "195d1b7256ba7e0e67c71202a25f8c94ff8241702c2f55d613ae1c6b98215172"
   227  
   228  	masterKey, err := encryptMasterPrivateKeyFromHex("02E65B0762D042F51F0D23542B13ED8CFA2E9A0E7206361E013A283905E31F")
   229  	if err != nil {
   230  		t.Fatal(err)
   231  	}
   232  
   233  	if hex.EncodeToString(masterKey.MasterPublicKey.Marshal()) != expectedPube {
   234  		t.Errorf("not expected master public key")
   235  	}
   236  
   237  	userA := []byte("Alice")
   238  	userB := []byte("Bob")
   239  
   240  	userKey, err := masterKey.GenerateUserKey(userA, hid)
   241  	if err != nil {
   242  		t.Fatal(err)
   243  	}
   244  	initiator := NewKeyExchange(userKey, userA, userB, 16, true)
   245  
   246  	userKey, err = masterKey.GenerateUserKey(userB, hid)
   247  	if err != nil {
   248  		t.Fatal(err)
   249  	}
   250  	responder := NewKeyExchange(userKey, userB, userA, 16, true)
   251  	defer func() {
   252  		initiator.Destroy()
   253  		responder.Destroy()
   254  	}()
   255  	// A1-A4
   256  	k, err := bigmod.NewNat().SetBytes(bigFromHex("5879DD1D51E175946F23B1B41E93BA31C584AE59A426EC1046A4D03B06C8").Bytes(), orderNat)
   257  	if err != nil {
   258  		t.Fatal(err)
   259  	}
   260  	initKeyExchange(initiator, hid, k)
   261  
   262  	if hex.EncodeToString(initiator.secret.Marshal()) != "7cba5b19069ee66aa79d490413d11846b9ba76dd22567f809cf23b6d964bb265a9760c99cb6f706343fed05637085864958d6c90902aba7d405fbedf7b781599" {
   263  		t.Fatal("not same")
   264  	}
   265  
   266  	// B1 - B7
   267  	k, err = bigmod.NewNat().SetBytes(bigFromHex("018B98C44BEF9F8537FB7D071B2C928B3BC65BD3D69E1EEE213564905634FE").Bytes(), orderNat)
   268  	if err != nil {
   269  		t.Fatal(err)
   270  	}
   271  	rB, sigB, err := respondKeyExchange(responder, hid, k, initiator.secret)
   272  	if err != nil {
   273  		t.Fatal(err)
   274  	}
   275  
   276  	if hex.EncodeToString(sigB) != expectedSignatureB {
   277  		t.Errorf("not expected signature B")
   278  	}
   279  
   280  	// A5 -A8
   281  	key1, sigA, err := initiator.ConfirmResponder(rB, sigB)
   282  	if err != nil {
   283  		t.Fatal(err)
   284  	}
   285  	if hex.EncodeToString(key1) != expectedKey {
   286  		t.Errorf("not expected key %v\n", hex.EncodeToString(key1))
   287  	}
   288  	if hex.EncodeToString(sigA) != expectedSignatureA {
   289  		t.Errorf("not expected signature A")
   290  	}
   291  	// B8
   292  	key2, err := responder.ConfirmInitiator(sigA)
   293  	if err != nil {
   294  		t.Fatal(err)
   295  	}
   296  	if hex.EncodeToString(key2) != expectedKey {
   297  		t.Errorf("not expected key %v\n", hex.EncodeToString(key2))
   298  	}
   299  }
   300  
   301  func TestKeyExchange(t *testing.T) {
   302  	hid := byte(0x02)
   303  	userA := []byte("Alice")
   304  	userB := []byte("Bob")
   305  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   306  	if err != nil {
   307  		t.Fatal(err)
   308  	}
   309  
   310  	userKey, err := masterKey.GenerateUserKey(userA, hid)
   311  	if err != nil {
   312  		t.Fatal(err)
   313  	}
   314  	initiator := NewKeyExchange(userKey, userA, userB, 16, true)
   315  
   316  	userKey, err = masterKey.GenerateUserKey(userB, hid)
   317  	if err != nil {
   318  		t.Fatal(err)
   319  	}
   320  	responder := NewKeyExchange(userKey, userB, userA, 16, true)
   321  	defer func() {
   322  		initiator.Destroy()
   323  		responder.Destroy()
   324  	}()
   325  	// A1-A4
   326  	rA, err := initiator.InitKeyExchange(rand.Reader, hid)
   327  	if err != nil {
   328  		t.Fatal(err)
   329  	}
   330  
   331  	// B1 - B7
   332  	rB, sigB, err := responder.RepondKeyExchange(rand.Reader, hid, rA)
   333  	if err != nil {
   334  		t.Fatal(err)
   335  	}
   336  
   337  	// A5 -A8
   338  	key1, sigA, err := initiator.ConfirmResponder(rB, sigB)
   339  	if err != nil {
   340  		t.Fatal(err)
   341  	}
   342  
   343  	// B8
   344  	key2, err := responder.ConfirmInitiator(sigA)
   345  	if err != nil {
   346  		t.Fatal(err)
   347  	}
   348  
   349  	if hex.EncodeToString(key1) != hex.EncodeToString(key2) {
   350  		t.Errorf("got different key")
   351  	}
   352  }
   353  
   354  func TestKeyExchangeWithoutSignature(t *testing.T) {
   355  	hid := byte(0x02)
   356  	userA := []byte("Alice")
   357  	userB := []byte("Bob")
   358  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   359  	if err != nil {
   360  		t.Fatal(err)
   361  	}
   362  
   363  	userKey, err := masterKey.GenerateUserKey(userA, hid)
   364  	if err != nil {
   365  		t.Fatal(err)
   366  	}
   367  	initiator := NewKeyExchange(userKey, userA, userB, 16, false)
   368  
   369  	userKey, err = masterKey.GenerateUserKey(userB, hid)
   370  	if err != nil {
   371  		t.Fatal(err)
   372  	}
   373  	responder := NewKeyExchange(userKey, userB, userA, 16, false)
   374  	defer func() {
   375  		initiator.Destroy()
   376  		responder.Destroy()
   377  	}()
   378  	// A1-A4
   379  	rA, err := initiator.InitKeyExchange(rand.Reader, hid)
   380  	if err != nil {
   381  		t.Fatal(err)
   382  	}
   383  
   384  	// B1 - B7
   385  	rB, sigB, err := responder.RepondKeyExchange(rand.Reader, hid, rA)
   386  	if err != nil {
   387  		t.Fatal(err)
   388  	}
   389  	if len(sigB) != 0 {
   390  		t.Errorf("should no signature")
   391  	}
   392  
   393  	// A5 -A8
   394  	key1, sigA, err := initiator.ConfirmResponder(rB, sigB)
   395  	if err != nil {
   396  		t.Fatal(err)
   397  	}
   398  	if len(sigA) != 0 {
   399  		t.Errorf("should no signature")
   400  	}
   401  
   402  	key2, err := responder.ConfirmInitiator(nil)
   403  	if err != nil {
   404  		t.Fatal(err)
   405  	}
   406  
   407  	if hex.EncodeToString(key1) != hex.EncodeToString(key2) {
   408  		t.Errorf("got different key")
   409  	}
   410  }
   411  
   412  func TestWrapKey(t *testing.T) {
   413  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   414  	hid := byte(0x01)
   415  	uid := []byte("emmansun")
   416  	if err != nil {
   417  		t.Fatal(err)
   418  	}
   419  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   420  	if err != nil {
   421  		t.Fatal(err)
   422  	}
   423  	key, cipher, err := WrapKey(rand.Reader, masterKey.Public(), uid, hid, 16)
   424  	if err != nil {
   425  		t.Fatal(err)
   426  	}
   427  
   428  	key2, err := UnwrapKey(userKey, uid, cipher, 16)
   429  	if err != nil {
   430  		t.Fatal(err)
   431  	}
   432  
   433  	if hex.EncodeToString(key) != hex.EncodeToString(key2) {
   434  		t.Errorf("expected %v, got %v\n", hex.EncodeToString(key), hex.EncodeToString(key2))
   435  	}
   436  }
   437  
   438  func TestWrapKeyASN1(t *testing.T) {
   439  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   440  	hid := byte(0x01)
   441  	uid := []byte("emmansun")
   442  	if err != nil {
   443  		t.Fatal(err)
   444  	}
   445  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   446  	if err != nil {
   447  		t.Fatal(err)
   448  	}
   449  	keyPackage, err := masterKey.Public().WrapKeyASN1(rand.Reader, uid, hid, 16)
   450  	if err != nil {
   451  		t.Fatal(err)
   452  	}
   453  
   454  	key1, cipher, err := UnmarshalSM9KeyPackage(keyPackage)
   455  	if err != nil {
   456  		t.Fatal(err)
   457  	}
   458  
   459  	key2, err := UnwrapKey(userKey, uid, cipher, 16)
   460  	if err != nil {
   461  		t.Fatal(err)
   462  	}
   463  
   464  	if hex.EncodeToString(key1) != hex.EncodeToString(key2) {
   465  		t.Errorf("expected %v, got %v\n", hex.EncodeToString(key1), hex.EncodeToString(key2))
   466  	}
   467  }
   468  
   469  func TestUnmarshalSM9KeyPackage(t *testing.T) {
   470  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   471  	hid := byte(0x01)
   472  	uid := []byte("emmansun")
   473  	if err != nil {
   474  		t.Fatal(err)
   475  	}
   476  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   477  	if err != nil {
   478  		t.Fatal(err)
   479  	}
   480  	p, err := masterKey.Public().WrapKeyASN1(rand.Reader, uid, hid, 16)
   481  	if err != nil {
   482  		t.Fatal(err)
   483  	}
   484  
   485  	key, cipher, err := UnmarshalSM9KeyPackage(p)
   486  	if err != nil {
   487  		t.Fatal(err)
   488  	}
   489  
   490  	key2, err := UnwrapKey(userKey, uid, cipher, 16)
   491  	if err != nil {
   492  		t.Fatal(err)
   493  	}
   494  
   495  	if hex.EncodeToString(key) != hex.EncodeToString(key2) {
   496  		t.Errorf("expected %v, got %v\n", hex.EncodeToString(key), hex.EncodeToString(key2))
   497  	}
   498  }
   499  
   500  func encryptMasterPrivateKeyFromHex(s string) (*EncryptMasterPrivateKey, error) {
   501  	kb, err := hex.DecodeString(s)
   502  	if err != nil {
   503  		return nil, err
   504  	}
   505  	var b cryptobyte.Builder
   506  	b.AddASN1BigInt(new(big.Int).SetBytes(kb))
   507  	kb, _ = b.Bytes()
   508  	testkey := new(EncryptMasterPrivateKey)
   509  	err = testkey.UnmarshalASN1(kb)
   510  	if err != nil {
   511  		return nil, err
   512  	}
   513  	return testkey, nil
   514  }
   515  
   516  // SM9 Appendix C
   517  func TestWrapKeySM9Sample(t *testing.T) {
   518  	expectedMasterPublicKey := "787ed7b8a51f3ab84e0a66003f32da5c720b17eca7137d39abc66e3c80a892ff769de61791e5adc4b9ff85a31354900b202871279a8c49dc3f220f644c57a7b1"
   519  	expectedUserPrivateKey := "94736acd2c8c8796cc4785e938301a139a059d3537b6414140b2d31eecf41683115bae85f5d8bc6c3dbd9e5342979acccf3c2f4f28420b1cb4f8c0b59a19b1587aa5e47570da7600cd760a0cf7beaf71c447f3844753fe74fa7ba92ca7d3b55f27538a62e7f7bfb51dce08704796d94c9d56734f119ea44732b50e31cdeb75c1"
   520  	expectedUserPublicKey := "709d165808b0a43e2574e203fa885abcbab16a240c4c1916552e7c43d09763b8693269a6be2456f43333758274786b6051ff87b7f198da4ba1a2c6e336f51fcc"
   521  	expectedCipher := "1edee2c3f465914491de44cefb2cb434ab02c308d9dc5e2067b4fed5aaac8a0f1c9b4c435eca35ab83bb734174c0f78fde81a53374aff3b3602bbc5e37be9a4c"
   522  	expectedKey := "4ff5cf86d2ad40c8f4bac98d76abdbde0c0e2f0a829d3f911ef5b2bce0695480"
   523  
   524  	masterKey, err := encryptMasterPrivateKeyFromHex("01EDEE3778F441F8DEA3D9FA0ACC4E07EE36C93F9A08618AF4AD85CEDE1C22")
   525  	if err != nil {
   526  		t.Fatal(err)
   527  	}
   528  	if hex.EncodeToString(masterKey.MasterPublicKey.Marshal()) != expectedMasterPublicKey {
   529  		t.Errorf("not expected master public key")
   530  	}
   531  
   532  	uid := []byte("Bob")
   533  	hid := byte(0x03)
   534  
   535  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   536  	if err != nil {
   537  		t.Fatal(err)
   538  	}
   539  	if hex.EncodeToString(userKey.PrivateKey.Marshal()) != expectedUserPrivateKey {
   540  		t.Errorf("not expected user private key")
   541  	}
   542  
   543  	q := masterKey.Public().GenerateUserPublicKey(uid, hid)
   544  	if hex.EncodeToString(q.Marshal()) != expectedUserPublicKey {
   545  		t.Errorf("not expected user public key")
   546  	}
   547  
   548  	var r *big.Int = bigFromHex("74015F8489C01EF4270456F9E6475BFB602BDE7F33FD482AB4E3684A6722")
   549  	cipher, err := new(bn256.G1).ScalarMult(q, bn256.NormalizeScalar(r.Bytes()))
   550  	if err != nil {
   551  		t.Fatal(err)
   552  	}
   553  	if hex.EncodeToString(cipher.Marshal()) != expectedCipher {
   554  		t.Errorf("not expected cipher")
   555  	}
   556  
   557  	g := bn256.Pair(masterKey.Public().MasterPublicKey, bn256.Gen2)
   558  	w := new(bn256.GT).ScalarMult(g, r)
   559  
   560  	var buffer []byte
   561  	buffer = append(buffer, cipher.Marshal()...)
   562  	buffer = append(buffer, w.Marshal()...)
   563  	buffer = append(buffer, uid...)
   564  
   565  	key := sm3.Kdf(buffer, 32)
   566  
   567  	if hex.EncodeToString(key) != expectedKey {
   568  		t.Errorf("expected %v, got %v\n", expectedKey, hex.EncodeToString(key))
   569  	}
   570  
   571  	key2, err := UnwrapKey(userKey, uid, cipher, 32)
   572  	if err != nil {
   573  		t.Fatal(err)
   574  	}
   575  	if hex.EncodeToString(key2) != expectedKey {
   576  		t.Errorf("expected %v, got %v\n", expectedKey, hex.EncodeToString(key2))
   577  	}
   578  }
   579  
   580  // SM9 Appendix D
   581  func TestEncryptSM9Sample(t *testing.T) {
   582  	plaintext := []byte("Chinese IBE standard")
   583  	expectedMasterPublicKey := "787ed7b8a51f3ab84e0a66003f32da5c720b17eca7137d39abc66e3c80a892ff769de61791e5adc4b9ff85a31354900b202871279a8c49dc3f220f644c57a7b1"
   584  	expectedUserPrivateKey := "94736acd2c8c8796cc4785e938301a139a059d3537b6414140b2d31eecf41683115bae85f5d8bc6c3dbd9e5342979acccf3c2f4f28420b1cb4f8c0b59a19b1587aa5e47570da7600cd760a0cf7beaf71c447f3844753fe74fa7ba92ca7d3b55f27538a62e7f7bfb51dce08704796d94c9d56734f119ea44732b50e31cdeb75c1"
   585  	expectedUserPublicKey := "709d165808b0a43e2574e203fa885abcbab16a240c4c1916552e7c43d09763b8693269a6be2456f43333758274786b6051ff87b7f198da4ba1a2c6e336f51fcc"
   586  	expectedCipher := "2445471164490618e1ee20528ff1d545b0f14c8bcaa44544f03dab5dac07d8ff42ffca97d57cddc05ea405f2e586feb3a6930715532b8000759f13059ed59ac0"
   587  	expectedKey := "58373260f067ec48667c21c144f8bc33cd3049788651ffd5f738003e51df31174d0e4e402fd87f4581b612f74259db574f67ece6"
   588  	expectedCiphertext := "2445471164490618e1ee20528ff1d545b0f14c8bcaa44544f03dab5dac07d8ff42ffca97d57cddc05ea405f2e586feb3a6930715532b8000759f13059ed59ac0ba672387bcd6de5016a158a52bb2e7fc429197bcab70b25afee37a2b9db9f3671b5f5b0e951489682f3e64e1378cdd5da9513b1c"
   589  
   590  	masterKey, err := encryptMasterPrivateKeyFromHex("01EDEE3778F441F8DEA3D9FA0ACC4E07EE36C93F9A08618AF4AD85CEDE1C22")
   591  	if err != nil {
   592  		t.Fatal(err)
   593  	}
   594  	if hex.EncodeToString(masterKey.MasterPublicKey.Marshal()) != expectedMasterPublicKey {
   595  		t.Errorf("not expected master public key")
   596  	}
   597  
   598  	uid := []byte("Bob")
   599  	hid := byte(0x03)
   600  
   601  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   602  	if err != nil {
   603  		t.Fatal(err)
   604  	}
   605  	if hex.EncodeToString(userKey.PrivateKey.Marshal()) != expectedUserPrivateKey {
   606  		t.Errorf("not expected user private key")
   607  	}
   608  
   609  	q := masterKey.Public().GenerateUserPublicKey(uid, hid)
   610  	if hex.EncodeToString(q.Marshal()) != expectedUserPublicKey {
   611  		t.Errorf("not expected user public key")
   612  	}
   613  
   614  	var r *big.Int = bigFromHex("AAC0541779C8FC45E3E2CB25C12B5D2576B2129AE8BB5EE2CBE5EC9E785C")
   615  	cipher, err := new(bn256.G1).ScalarMult(q, bn256.NormalizeScalar(r.Bytes()))
   616  	if err != nil {
   617  		t.Fatal(err)
   618  	}
   619  	if hex.EncodeToString(cipher.Marshal()) != expectedCipher {
   620  		t.Errorf("not expected cipher")
   621  	}
   622  
   623  	g := bn256.Pair(masterKey.Public().MasterPublicKey, bn256.Gen2)
   624  	w := new(bn256.GT).ScalarMult(g, r)
   625  
   626  	var buffer []byte
   627  	buffer = append(buffer, cipher.Marshal()...)
   628  	buffer = append(buffer, w.Marshal()...)
   629  	buffer = append(buffer, uid...)
   630  
   631  	key := sm3.Kdf(buffer, len(plaintext)+32)
   632  
   633  	if hex.EncodeToString(key) != expectedKey {
   634  		t.Errorf("not expected key")
   635  	}
   636  	subtle.XORBytes(key, key[:len(plaintext)], plaintext)
   637  
   638  	hash := sm3.New()
   639  	hash.Write(key)
   640  	c3 := hash.Sum(nil)
   641  
   642  	ciphertext := append(cipher.Marshal(), c3...)
   643  	ciphertext = append(ciphertext, key[:len(plaintext)]...)
   644  	if hex.EncodeToString(ciphertext) != expectedCiphertext {
   645  		t.Errorf("expected %v, got %v\n", expectedCiphertext, hex.EncodeToString(ciphertext))
   646  	}
   647  }
   648  
   649  func TestEncryptSM9SampleBlockMode(t *testing.T) {
   650  	plaintext := []byte("Chinese IBE standard")
   651  	expectedMasterPublicKey := "787ed7b8a51f3ab84e0a66003f32da5c720b17eca7137d39abc66e3c80a892ff769de61791e5adc4b9ff85a31354900b202871279a8c49dc3f220f644c57a7b1"
   652  	expectedUserPrivateKey := "94736acd2c8c8796cc4785e938301a139a059d3537b6414140b2d31eecf41683115bae85f5d8bc6c3dbd9e5342979acccf3c2f4f28420b1cb4f8c0b59a19b1587aa5e47570da7600cd760a0cf7beaf71c447f3844753fe74fa7ba92ca7d3b55f27538a62e7f7bfb51dce08704796d94c9d56734f119ea44732b50e31cdeb75c1"
   653  	expectedUserPublicKey := "709d165808b0a43e2574e203fa885abcbab16a240c4c1916552e7c43d09763b8693269a6be2456f43333758274786b6051ff87b7f198da4ba1a2c6e336f51fcc"
   654  	expectedCipher := "2445471164490618e1ee20528ff1d545b0f14c8bcaa44544f03dab5dac07d8ff42ffca97d57cddc05ea405f2e586feb3a6930715532b8000759f13059ed59ac0"
   655  	expectedKey := "58373260f067ec48667c21c144f8bc33cd3049788651ffd5f738003e51df31174d0e4e402fd87f4581b612f74259db57"
   656  	expectedCiphertext := "2445471164490618e1ee20528ff1d545b0f14c8bcaa44544f03dab5dac07d8ff42ffca97d57cddc05ea405f2e586feb3a6930715532b8000759f13059ed59ac0fd3c98dd92c44c68332675a370cceede31e0c5cd209c257601149d12b394a2bee05b6fac6f11b965268c994f00dba7a8bb00fd60583546cbdf4649250863f10a"
   657  
   658  	masterKey, err := encryptMasterPrivateKeyFromHex("01EDEE3778F441F8DEA3D9FA0ACC4E07EE36C93F9A08618AF4AD85CEDE1C22")
   659  	if err != nil {
   660  		t.Fatal(err)
   661  	}
   662  	if hex.EncodeToString(masterKey.MasterPublicKey.Marshal()) != expectedMasterPublicKey {
   663  		t.Errorf("not expected master public key")
   664  	}
   665  
   666  	uid := []byte("Bob")
   667  	hid := byte(0x03)
   668  
   669  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   670  	if err != nil {
   671  		t.Fatal(err)
   672  	}
   673  	if hex.EncodeToString(userKey.PrivateKey.Marshal()) != expectedUserPrivateKey {
   674  		t.Errorf("not expected user private key")
   675  	}
   676  
   677  	q := masterKey.Public().GenerateUserPublicKey(uid, hid)
   678  	if hex.EncodeToString(q.Marshal()) != expectedUserPublicKey {
   679  		t.Errorf("not expected user public key")
   680  	}
   681  
   682  	var r *big.Int = bigFromHex("AAC0541779C8FC45E3E2CB25C12B5D2576B2129AE8BB5EE2CBE5EC9E785C")
   683  	cipher, err := new(bn256.G1).ScalarMult(q, bn256.NormalizeScalar(r.Bytes()))
   684  	if err != nil {
   685  		t.Fatal(err)
   686  	}
   687  	if hex.EncodeToString(cipher.Marshal()) != expectedCipher {
   688  		t.Errorf("not expected cipher")
   689  	}
   690  
   691  	g := bn256.Pair(masterKey.Public().MasterPublicKey, bn256.Gen2)
   692  	w := new(bn256.GT).ScalarMult(g, r)
   693  
   694  	var buffer []byte
   695  	buffer = append(buffer, cipher.Marshal()...)
   696  	buffer = append(buffer, w.Marshal()...)
   697  	buffer = append(buffer, uid...)
   698  
   699  	key := sm3.Kdf(buffer, 16+32)
   700  
   701  	if hex.EncodeToString(key) != expectedKey {
   702  		t.Errorf("not expected key, expected %v, got %x\n", expectedKey, key)
   703  	}
   704  
   705  	c2, err := SM4ECBEncrypterOpts.Encrypt(nil, key[:16], plaintext)
   706  	if err != nil {
   707  		t.Fatal(err)
   708  	}
   709  	hash := sm3.New()
   710  	hash.Write(c2)
   711  	hash.Write(key[16:])
   712  	c3 := hash.Sum(nil)
   713  
   714  	ciphertext := append(cipher.Marshal(), c3...)
   715  	ciphertext = append(ciphertext, c2...)
   716  	if hex.EncodeToString(ciphertext) != expectedCiphertext {
   717  		t.Errorf("expected %v, got %v\n", expectedCiphertext, hex.EncodeToString(ciphertext))
   718  	}
   719  }
   720  
   721  func TestEncryptDecrypt(t *testing.T) {
   722  	plaintext := []byte("Chinese IBE standard")
   723  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   724  	hid := byte(0x01)
   725  	uid := []byte("emmansun")
   726  	if err != nil {
   727  		t.Fatal(err)
   728  	}
   729  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   730  	if err != nil {
   731  		t.Fatal(err)
   732  	}
   733  	encTypes := []EncrypterOpts{
   734  		DefaultEncrypterOpts, SM4ECBEncrypterOpts, SM4CBCEncrypterOpts, SM4CFBEncrypterOpts, SM4OFBEncrypterOpts,
   735  	}
   736  	for _, opts := range encTypes {
   737  		cipher, err := Encrypt(rand.Reader, masterKey.Public(), uid, hid, plaintext, opts)
   738  		if err != nil {
   739  			t.Fatal(err)
   740  		}
   741  
   742  		got, err := Decrypt(userKey, uid, cipher, opts)
   743  		if err != nil {
   744  			t.Fatal(err)
   745  		}
   746  		if string(got) != string(plaintext) {
   747  			t.Errorf("expected %v, got %v\n", string(plaintext), string(got))
   748  		}
   749  
   750  		got, err = userKey.Decrypt(uid, cipher, opts)
   751  		if err != nil {
   752  			t.Fatalf("encType %v, first byte %x, %v", opts.GetEncryptType(), cipher[0], err)
   753  		}
   754  
   755  		if string(got) != string(plaintext) {
   756  			t.Errorf("expected %v, got %v\n", string(plaintext), string(got))
   757  		}
   758  	}
   759  }
   760  
   761  func TestEncryptEmptyPlaintext(t *testing.T) {
   762  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   763  	hid := byte(0x01)
   764  	uid := []byte("emmansun")
   765  	if err != nil {
   766  		t.Fatal(err)
   767  	}
   768  	encTypes := []EncrypterOpts{
   769  		DefaultEncrypterOpts, SM4ECBEncrypterOpts, SM4CBCEncrypterOpts, SM4CFBEncrypterOpts, SM4OFBEncrypterOpts,
   770  	}
   771  	for _, opts := range encTypes {
   772  		_, err := Encrypt(rand.Reader, masterKey.Public(), uid, hid, nil, opts)
   773  		if err != ErrEmptyPlaintext {
   774  			t.Fatalf("should be ErrEmptyPlaintext")
   775  		}
   776  	}
   777  }
   778  
   779  func TestEncryptDecryptASN1(t *testing.T) {
   780  	plaintext := []byte("Chinese IBE standard")
   781  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   782  	hid := byte(0x01)
   783  	uid := []byte("emmansun")
   784  	if err != nil {
   785  		t.Fatal(err)
   786  	}
   787  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   788  	if err != nil {
   789  		t.Fatal(err)
   790  	}
   791  	encTypes := []EncrypterOpts{
   792  		DefaultEncrypterOpts, SM4ECBEncrypterOpts, SM4CBCEncrypterOpts, SM4CFBEncrypterOpts, SM4OFBEncrypterOpts,
   793  	}
   794  	for _, opts := range encTypes {
   795  		cipher, err := EncryptASN1(rand.Reader, masterKey.Public(), uid, hid, plaintext, opts)
   796  		if err != nil {
   797  			t.Fatal(err)
   798  		}
   799  
   800  		got, err := DecryptASN1(userKey, uid, cipher)
   801  		if err != nil {
   802  			t.Fatal(err)
   803  		}
   804  
   805  		if string(got) != string(plaintext) {
   806  			t.Errorf("expected %v, got %v\n", string(plaintext), string(got))
   807  		}
   808  
   809  		got, err = userKey.DecryptASN1(uid, cipher)
   810  		if err != nil {
   811  			t.Fatal(err)
   812  		}
   813  
   814  		if string(got) != string(plaintext) {
   815  			t.Errorf("expected %v, got %v\n", string(plaintext), string(got))
   816  		}
   817  	}
   818  }
   819  
   820  func BenchmarkSign(b *testing.B) {
   821  	hashed := []byte("Chinese IBS standard")
   822  	uid := []byte("emmansun")
   823  	hid := byte(0x01)
   824  
   825  	masterKey, err := GenerateSignMasterKey(rand.Reader)
   826  	if err != nil {
   827  		b.Fatal(err)
   828  	}
   829  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   830  	if err != nil {
   831  		b.Fatal(err)
   832  	}
   833  	SignASN1(rand.Reader, userKey, hashed) // fire precompute
   834  
   835  	b.ReportAllocs()
   836  	b.ResetTimer()
   837  	for i := 0; i < b.N; i++ {
   838  		sig, err := SignASN1(rand.Reader, userKey, hashed)
   839  		if err != nil {
   840  			b.Fatal(err)
   841  		}
   842  		// Prevent the compiler from optimizing out the operation.
   843  		hashed[0] = sig[0]
   844  	}
   845  }
   846  
   847  func BenchmarkVerify(b *testing.B) {
   848  	hashed := []byte("Chinese IBS standard")
   849  	uid := []byte("emmansun")
   850  	hid := byte(0x01)
   851  
   852  	masterKey, err := GenerateSignMasterKey(rand.Reader)
   853  	if err != nil {
   854  		b.Fatal(err)
   855  	}
   856  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   857  	if err != nil {
   858  		b.Fatal(err)
   859  	}
   860  	sig, err := SignASN1(rand.Reader, userKey, hashed)
   861  	if err != nil {
   862  		b.Fatal(err)
   863  	}
   864  	b.ReportAllocs()
   865  	b.ResetTimer()
   866  	for i := 0; i < b.N; i++ {
   867  		if !VerifyASN1(masterKey.Public(), uid, hid, hashed, sig) {
   868  			b.Fatal("verify failed")
   869  		}
   870  	}
   871  }
   872  
   873  func BenchmarkEncrypt(b *testing.B) {
   874  	plaintext := []byte("Chinese IBE standard")
   875  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   876  	hid := byte(0x01)
   877  	uid := []byte("emmansun")
   878  	if err != nil {
   879  		b.Fatal(err)
   880  	}
   881  	b.ReportAllocs()
   882  	b.ResetTimer()
   883  	for i := 0; i < b.N; i++ {
   884  		cipher, err := Encrypt(rand.Reader, masterKey.Public(), uid, hid, plaintext, nil)
   885  		if err != nil {
   886  			b.Fatal(err)
   887  		}
   888  		// Prevent the compiler from optimizing out the operation.
   889  		plaintext[0] = cipher[0]
   890  	}
   891  }
   892  
   893  func BenchmarkDecrypt(b *testing.B) {
   894  	plaintext := []byte("Chinese IBE standard")
   895  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   896  	hid := byte(0x01)
   897  	uid := []byte("emmansun")
   898  	if err != nil {
   899  		b.Fatal(err)
   900  	}
   901  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   902  	if err != nil {
   903  		b.Fatal(err)
   904  	}
   905  	cipher, err := Encrypt(rand.Reader, masterKey.Public(), uid, hid, plaintext, nil)
   906  	if err != nil {
   907  		b.Fatal(err)
   908  	}
   909  	b.ReportAllocs()
   910  	b.ResetTimer()
   911  	for i := 0; i < b.N; i++ {
   912  		got, err := Decrypt(userKey, uid, cipher, nil)
   913  		if err != nil {
   914  			b.Fatal(err)
   915  		}
   916  		if string(got) != string(plaintext) {
   917  			b.Errorf("expected %v, got %v\n", string(plaintext), string(got))
   918  		}
   919  	}
   920  }
   921  
   922  func BenchmarkDecryptASN1(b *testing.B) {
   923  	plaintext := []byte("Chinese IBE standard")
   924  	masterKey, err := GenerateEncryptMasterKey(rand.Reader)
   925  	hid := byte(0x01)
   926  	uid := []byte("emmansun")
   927  	if err != nil {
   928  		b.Fatal(err)
   929  	}
   930  	userKey, err := masterKey.GenerateUserKey(uid, hid)
   931  	if err != nil {
   932  		b.Fatal(err)
   933  	}
   934  	cipher, err := EncryptASN1(rand.Reader, masterKey.Public(), uid, hid, plaintext, nil)
   935  	if err != nil {
   936  		b.Fatal(err)
   937  	}
   938  	b.ReportAllocs()
   939  	b.ResetTimer()
   940  	for i := 0; i < b.N; i++ {
   941  		got, err := DecryptASN1(userKey, uid, cipher)
   942  		if err != nil {
   943  			b.Fatal(err)
   944  		}
   945  		if string(got) != string(plaintext) {
   946  			b.Errorf("expected %v, got %v\n", string(plaintext), string(got))
   947  		}
   948  	}
   949  }