arnaucube
arnaucube/slowlorisdbPublic Self-hosted repository
slowlorisdb/core/keys.go
core/keys.goRaw
 1package core
 2
 3import (
 4	"crypto/ecdsa"
 5	"crypto/elliptic"
 6	"crypto/rand"
 7	"encoding/hex"
 8	"errors"
 9	"math/big"
10)
11
12// Address is the type data for addresses
13type Address [32]byte
14
15func (addr Address) String() string {
16	return hex.EncodeToString(addr[:])
17}
18
19func NewKey() (*ecdsa.PrivateKey, error) {
20	curve := elliptic.P256()
21
22	privatekey := new(ecdsa.PrivateKey)
23	privatekey, err := ecdsa.GenerateKey(curve, rand.Reader)
24	if err != nil {
25		return nil, err
26	}
27
28	return privatekey, err
29}
30
31func PackPubK(pubK *ecdsa.PublicKey) []byte {
32	return elliptic.Marshal(pubK.Curve, pubK.X, pubK.Y)
33}
34func UnpackPubK(b []byte) *ecdsa.PublicKey {
35	x, y := elliptic.Unmarshal(elliptic.P256(), b)
36	return &ecdsa.PublicKey{
37		Curve: elliptic.P256(),
38		X:     x,
39		Y:     y,
40	}
41}
42
43func AddressFromPrivK(privK *ecdsa.PrivateKey) Address {
44	h := HashBytes(PackPubK(&privK.PublicKey))
45	return Address(h)
46}
47
48func (sig *Signature) Bytes() []byte {
49	b := sig.R.Bytes()
50	b = append(b, sig.S.Bytes()...)
51	return b
52}
53
54func SignatureFromBytes(b []byte) (*Signature, error) {
55	if len(b) != 64 {
56		return nil, errors.New("Invalid signature")
57	}
58	rBytes := b[:32]
59	sBytes := b[32:]
60
61	r := new(big.Int).SetBytes(rBytes)
62	s := new(big.Int).SetBytes(sBytes)
63
64	sig := &Signature{
65		R: r,
66		S: s,
67	}
68	return sig, nil
69}
70
71type Signature struct {
72	R *big.Int
73	S *big.Int
74}
75
76func Sign(privK *ecdsa.PrivateKey, m []byte) (*Signature, error) {
77	r := big.NewInt(0)
78	s := big.NewInt(0)
79
80	hashMsg := HashBytes(m)
81
82	r, s, err := ecdsa.Sign(rand.Reader, privK, hashMsg[:])
83	if err != nil {
84		return nil, err
85	}
86	sig := &Signature{
87		R: r,
88		S: s,
89	}
90
91	return sig, nil
92
93}
94
95func VerifySignature(pubK *ecdsa.PublicKey, m []byte, sig Signature) bool {
96	hashMsg := HashBytes(m)
97	verified := ecdsa.Verify(pubK, hashMsg[:], sig.R, sig.S)
98	return verified
99}