1 // GoGOST -- Pure Go GOST cryptographic functions library
2 // Copyright (C) 2015-2023 Sergey Matveev <stargrave@stargrave.org>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program. If not, see <http://www.gnu.org/licenses/>.
24 type PublicKey struct {
30 // Unmarshal LE(X)||LE(Y) public key. "raw" must be 2*c.PointSize() length.
31 func NewPublicKey(c *Curve, raw []byte) (*PublicKey, error) {
32 pointSize := c.PointSize()
33 key := make([]byte, 2*pointSize)
34 if len(raw) != len(key) {
35 return nil, fmt.Errorf("gogost/gost3410: len(key) != %d", len(key))
37 for i := 0; i < len(key); i++ {
38 key[i] = raw[len(raw)-i-1]
42 bytes2big(key[pointSize : 2*pointSize]),
43 bytes2big(key[:pointSize]),
47 // Marshal LE(X)||LE(Y) public key. raw will be 2*pub.C.PointSize() length.
48 func (pub *PublicKey) Raw() (raw []byte) {
49 pointSize := pub.C.PointSize()
51 pad(pub.Y.Bytes(), pointSize),
52 pad(pub.X.Bytes(), pointSize)...,
58 func (pub *PublicKey) VerifyDigest(digest, signature []byte) (bool, error) {
59 pointSize := pub.C.PointSize()
60 if len(signature) != 2*pointSize {
61 return false, fmt.Errorf("gogost/gost3410: len(signature)=%d != %d", len(signature), 2*pointSize)
63 s := bytes2big(signature[:pointSize])
64 r := bytes2big(signature[pointSize:])
65 if r.Cmp(zero) <= 0 ||
66 r.Cmp(pub.C.Q) >= 0 ||
71 e := bytes2big(digest)
77 v.ModInverse(e, pub.C.Q)
85 p1x, p1y, err := pub.C.Exp(z1, pub.C.X, pub.C.Y)
89 q1x, q1y, err := pub.C.Exp(z2, pub.X, pub.Y)
98 lm.ModInverse(lm, pub.C.P)
107 if lm.Cmp(zero) < 0 {
111 return lm.Cmp(r) == 0, nil
114 func (our *PublicKey) Equal(theirKey crypto.PublicKey) bool {
115 their, ok := theirKey.(*PublicKey)
119 return our.X.Cmp(their.X) == 0 && our.Y.Cmp(their.Y) == 0 && our.C.Equal(their.C)