-
Notifications
You must be signed in to change notification settings - Fork 21
/
utils.go
73 lines (55 loc) · 1.65 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package gost
import (
"math/big"
)
// Reverse bytes
func Reverse(b []byte) []byte {
d := make([]byte, len(b))
copy(d, b)
for i, j := 0, len(d)-1; i < j; i, j = i+1, j-1 {
d[i], d[j] = d[j], d[i]
}
return d
}
func bytesToBigint(b []byte) *big.Int {
return new(big.Int).SetBytes(b)
}
// Marshal converts a point on the curve into the uncompressed
func Marshal(curve *Curve, x, y *big.Int) []byte {
panicIfNotOnCurve(curve, x, y)
byteLen := curve.PointSize()
ret := make([]byte, 2*byteLen)
y.FillBytes(ret[0 : byteLen])
x.FillBytes(ret[byteLen:2*byteLen])
return Reverse(ret)
}
// Unmarshal converts a point, serialized by Marshal, into an x, y pair. It is
// an error if the point is not in uncompressed form, is not on the curve, or is
// the point at infinity. On error, x = nil.
func Unmarshal(curve *Curve, data []byte) (x, y *big.Int) {
byteLen := curve.PointSize()
if len(data) != 2*byteLen {
return nil, nil
}
data = Reverse(data)
y = new(big.Int).SetBytes(data[:byteLen])
x = new(big.Int).SetBytes(data[byteLen:])
p := curve.Params().P
if x.Cmp(p) >= 0 || y.Cmp(p) >= 0 {
return nil, nil
}
if !curve.IsOnCurve(x, y) {
return nil, nil
}
return
}
func panicIfNotOnCurve(curve *Curve, x, y *big.Int) {
// (0, 0) is the point at infinity by convention. It's ok to operate on it,
// although IsOnCurve is documented to return false for it. See Issue 37294.
if x.Sign() == 0 && y.Sign() == 0 {
return
}
if !curve.IsOnCurve(x, y) {
panic("cryptobin/gost: attempted operation on invalid point")
}
}