1 // GoGOST -- Pure Go GOST cryptographic functions library
2 // Copyright (C) 2015-2019 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/>.
25 type PrivateKey struct {
31 func NewPrivateKey(curve *Curve, mode Mode, raw []byte) (*PrivateKey, error) {
32 if len(raw) != int(mode) {
33 return nil, errors.New("Invalid private key length")
35 key := make([]byte, int(mode))
36 for i := 0; i < len(key); i++ {
37 key[i] = raw[len(raw)-i-1]
41 return nil, errors.New("Zero private key")
43 return &PrivateKey{curve, mode, k}, nil
46 func GenPrivateKey(curve *Curve, mode Mode, rand io.Reader) (*PrivateKey, error) {
47 raw := make([]byte, int(mode))
48 if _, err := io.ReadFull(rand, raw); err != nil {
51 return NewPrivateKey(curve, mode, raw)
54 func (prv *PrivateKey) Raw() []byte {
55 raw := pad(prv.Key.Bytes(), int(prv.Mode))
60 func (prv *PrivateKey) PublicKey() (*PublicKey, error) {
61 x, y, err := prv.C.Exp(prv.Key, prv.C.X, prv.C.Y)
65 return &PublicKey{prv.C, prv.Mode, x, y}, nil
68 func (prv *PrivateKey) SignDigest(digest []byte, rand io.Reader) ([]byte, error) {
69 e := bytes2big(digest)
74 kRaw := make([]byte, int(prv.Mode))
81 if _, err = io.ReadFull(rand, kRaw); err != nil {
89 r, _, err = prv.C.Exp(k, prv.C.X, prv.C.Y)
101 if s.Cmp(zero) == 0 {
105 pad(s.Bytes(), int(prv.Mode)),
106 pad(r.Bytes(), int(prv.Mode))...,
110 func (prv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
111 return prv.SignDigest(digest, rand)
114 func (prv *PrivateKey) Public() crypto.PublicKey {
115 pub, err := prv.PublicKey()