github.com/flyinox/gosm@v0.0.0-20171117061539-16768cb62077/src/crypto/sm/sm2/sm2_test.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package sm2 implements china crypto standards. 6 package sm2 7 8 import ( 9 "crypto/rand" 10 "crypto/sha256" 11 "fmt" 12 "testing" 13 "crypto/sm/sm3" 14 ) 15 16 func TestSignVerify(t *testing.T) { 17 msg := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} 18 priv, err := GenerateKey(rand.Reader) 19 if err != nil { 20 panic("GenerateKey failed") 21 } 22 23 hfunc := sha256.New() 24 hfunc.Write(msg) 25 hash := hfunc.Sum(nil) 26 27 r, s, err := Sign(rand.Reader, priv, hash) 28 if err != nil { 29 panic(err) 30 } 31 32 ret := Verify(&priv.PublicKey, hash, r, s) 33 fmt.Println(ret) 34 } 35 36 func TestKeyGeneration(t *testing.T) { 37 priv, err := GenerateKey(rand.Reader) 38 if err != nil { 39 t.Errorf("error: %s", err) 40 return 41 } 42 43 if !priv.PublicKey.Curve.IsOnCurve(priv.PublicKey.X, priv.PublicKey.Y) { 44 t.Errorf("public key invalid: %s", err) 45 } 46 } 47 48 func BenchmarkSign(b *testing.B) { 49 b.ResetTimer() 50 hashed := []byte("testing") 51 priv, _ := GenerateKey(rand.Reader) 52 53 b.ResetTimer() 54 for i := 0; i < b.N; i++ { 55 _, _, _ = Sign(rand.Reader, priv, hashed) 56 } 57 } 58 59 func TestSignAndVerify(t *testing.T) { 60 priv, _ := GenerateKey(rand.Reader) 61 62 origin := []byte("testintestintestintestintestintestinggggggtesting") 63 hash := sm3.New() 64 hash.Write(origin) 65 hashed := hash.Sum(nil) 66 r, s, err := Sign(rand.Reader, priv, hashed) 67 if err != nil { 68 t.Errorf(" error signing: %s", err) 69 return 70 } 71 72 if !Verify(&priv.PublicKey, hashed, r, s) { 73 t.Errorf(" Verify failed") 74 } 75 76 //hashed[0] ^= 0xff 77 hashed[0] = 0x53 78 for i := 0; i < len(hashed); i++ { 79 hashed[i] = byte(i) 80 } 81 if Verify(&priv.PublicKey, hashed, r, s) { 82 t.Errorf("Verify always works!") 83 } 84 } 85