Debian Codegraph @

cert/p256/p256.go

raw
1 package p256
2
3 import (
4 "crypto/elliptic"
5 "errors"
6 "math/big"
7
8 "filippo.io/bigmod"
9
10 "golang.org/x/crypto/cryptobyte"
11 "golang.org/x/crypto/cryptobyte/asn1"
12 )
13
14 var halfN = new(big.Int).Rsh(elliptic.P256().Params().N, 1)
15 var nMod *bigmod.Modulus
16
17 func init() {
18 n, err := bigmod.NewModulus(elliptic.P256().Params().N.Bytes())
19 if err != nil {
20 panic(err)
21 }
22 nMod = n
23 }
24
25 func IsNormalized(sig []byte) (bool, error) {
26 r, s, err := parseSignature(sig)
27 if err != nil {
28 return false, err
29 }
30 return checkLowS(r, s), nil
31 }
32
33 func checkLowS(_, s []byte) bool {
34 bigS := new(big.Int).SetBytes(s)
35 // Check if S <= (N/2), because we want to include the midpoint in the set of low-s
36 return bigS.Cmp(halfN) <= 0
37 }
38
39 func swap(r, s []byte) ([]byte, []byte, error) {
40 var err error
41 bigS, err := bigmod.NewNat().SetBytes(s, nMod)
42 if err != nil {
43 return nil, nil, err
44 }
45 sNormalized := nMod.Nat().Sub(bigS, nMod)
46
47 result := sNormalized.Bytes(nMod)
48 for len(result) > 1 && result[0] == 0 {
49 result = result[1:]
50 }
51
52 return r, result, nil
53 }
54
55 func Normalize(sig []byte) ([]byte, error) {
56 r, s, err := parseSignature(sig)
57 if err != nil {
58 return nil, err
59 }
60
61 if checkLowS(r, s) {
62 return sig, nil
63 }
64
65 newR, newS, err := swap(r, s)
66 if err != nil {
67 return nil, err
68 }
69
70 return encodeSignature(newR, newS)
71 }
72
73 // Swap will change sig between its current form to the opposite high or low form.
74 func Swap(sig []byte) ([]byte, error) {
75 r, s, err := parseSignature(sig)
76 if err != nil {
77 return nil, err
78 }
79
80 newR, newS, err := swap(r, s)
81 if err != nil {
82 return nil, err
83 }
84
85 return encodeSignature(newR, newS)
86 }
87
88 // parseSignature taken exactly from crypto/ecdsa/ecdsa.go
89 func parseSignature(sig []byte) (r, s []byte, err error) {
90 var inner cryptobyte.String
91 input := cryptobyte.String(sig)
92 if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
93 !input.Empty() ||
94 !inner.ReadASN1Integer(&r) ||
95 !inner.ReadASN1Integer(&s) ||
96 !inner.Empty() {
97 return nil, nil, errors.New("invalid ASN.1")
98 }
99 return r, s, nil
100 }
101
102 func encodeSignature(r, s []byte) ([]byte, error) {
103 var b cryptobyte.Builder
104 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
105 addASN1IntBytes(b, r)
106 addASN1IntBytes(b, s)
107 })
108 return b.Bytes()
109 }
110
111 // addASN1IntBytes encodes in ASN.1 a positive integer represented as
112 // a big-endian byte slice with zero or more leading zeroes.
113 func addASN1IntBytes(b *cryptobyte.Builder, bytes []byte) {
114 for len(bytes) > 0 && bytes[0] == 0 {
115 bytes = bytes[1:]
116 }
117 if len(bytes) == 0 {
118 b.SetError(errors.New("invalid integer"))
119 return
120 }
121 b.AddASN1(asn1.INTEGER, func(c *cryptobyte.Builder) {
122 if bytes[0]&0x80 != 0 {
123 c.AddUint8(0)
124 }
125 c.AddBytes(bytes)
126 })
127 }