-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsignature.go
80 lines (62 loc) · 2 KB
/
signature.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
74
75
76
77
78
79
80
// Copyright 2018 ProximaX Limited. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package crypto
import (
"encoding/hex"
"errors"
"math"
"math/big"
"github.com/proximax-storage/go-xpx-utils"
)
// Signature include two part of signature
type Signature struct {
R []byte
S []byte
}
var (
errBadParamNewSignature = errors.New("binary signature representation of r and s must both have 32 bytes length")
errBadParamNewSignatureBigInt = errors.New("bad parameters NewSignatureFromBigInt")
errBadParamNewSignatureFromBytes = errors.New("binary signature representation must be 64 bytes")
)
// NewSignature R and S must fit into 32 bytes
func NewSignature(r []byte, s []byte) (*Signature, error) {
if (len(r) != 32) || (len(s) != 32) {
return nil, errBadParamNewSignature
}
ref := &Signature{r, s}
return ref, nil
}
// NewSignatureFromBigInt create new Signature from big.Int parts
func NewSignatureFromBigInt(rInt, sInt *big.Int) (*Signature, error) {
if (rInt == nil) || (sInt == nil) ||
(rInt.Uint64() > math.MaxInt32) ||
(sInt.Uint64() > math.MaxInt32) {
return nil, errBadParamNewSignatureBigInt
}
r := utils.BigIntToByteArray(rInt, 32)
s := utils.BigIntToByteArray(sInt, 32)
return NewSignature(r, s)
}
// NewSignatureFromBytes Creates a new signature from bytes array 64
func NewSignatureFromBytes(b []byte) (*Signature, error) {
if len(b) < 64 {
return nil, errBadParamNewSignatureFromBytes
}
return NewSignature(b[:32], b[32:])
}
// GetR Gets the R-part of the signature.
func (ref *Signature) GetR() *big.Int {
return utils.BytesToBigInteger(ref.R)
}
// GetS Gets the S-part of the signature.
func (ref *Signature) GetS() *big.Int {
return utils.BytesToBigInteger(ref.S)
}
// Bytes Gets a little-endian 64-byte representation of the signature.
func (ref *Signature) Bytes() []byte {
return append(ref.R, ref.S...)
}
func (ref *Signature) String() string {
return hex.EncodeToString(ref.Bytes())
}