github.com/defanghe/fabric@v2.1.1+incompatible/internal/cryptogen/csp/csp_internal_test.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 package csp 7 8 import ( 9 "crypto/ecdsa" 10 "crypto/elliptic" 11 "math/big" 12 "testing" 13 14 "github.com/stretchr/testify/assert" 15 ) 16 17 func TestToLowS(t *testing.T) { 18 curve := elliptic.P256() 19 halfOrder := new(big.Int).Div(curve.Params().N, big.NewInt(2)) 20 21 for _, test := range []struct { 22 name string 23 sig ECDSASignature 24 expectedSig ECDSASignature 25 }{ 26 { 27 name: "HighS", 28 sig: ECDSASignature{ 29 R: big.NewInt(1), 30 // set S to halfOrder + 1 31 S: new(big.Int).Add(halfOrder, big.NewInt(1)), 32 }, 33 // expected signature should be (sig.R, -sig.S mod N) 34 expectedSig: ECDSASignature{ 35 R: big.NewInt(1), 36 S: new(big.Int).Mod(new(big.Int).Neg(new(big.Int).Add(halfOrder, big.NewInt(1))), curve.Params().N), 37 }, 38 }, 39 { 40 name: "LowS", 41 sig: ECDSASignature{ 42 R: big.NewInt(1), 43 // set S to halfOrder - 1 44 S: new(big.Int).Sub(halfOrder, big.NewInt(1)), 45 }, 46 // expected signature should be sig 47 expectedSig: ECDSASignature{ 48 R: big.NewInt(1), 49 S: new(big.Int).Sub(halfOrder, big.NewInt(1)), 50 }, 51 }, 52 { 53 name: "HalfOrder", 54 sig: ECDSASignature{ 55 R: big.NewInt(1), 56 // set S to halfOrder 57 S: halfOrder, 58 }, 59 // expected signature should be sig 60 expectedSig: ECDSASignature{ 61 R: big.NewInt(1), 62 S: halfOrder, 63 }, 64 }, 65 } { 66 t.Run(test.name, func(t *testing.T) { 67 curve := elliptic.P256() 68 key := ecdsa.PublicKey{ 69 Curve: curve, 70 } 71 assert.Equal(t, test.expectedSig, toLowS(key, test.sig)) 72 }) 73 } 74 }