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 PackSignature(r, s *big.Int) []byte {
49	sig := r.Bytes()
50	sig = append(sig, s.Bytes()...)
51	return sig
52}
53
54func UnpackSignature(sig []byte) (*big.Int, *big.Int, error) {
55	if len(sig) != 64 {
56		return nil, nil, errors.New("Invalid signature")
57	}
58	rBytes := sig[:32]
59	sBytes := sig[32:]
60
61	r := new(big.Int).SetBytes(rBytes)
62	s := new(big.Int).SetBytes(sBytes)
63
64	return r, s, nil
65}
66
67func Sign(privK *ecdsa.PrivateKey, m []byte) ([]byte, error) {
68	r := big.NewInt(0)
69	s := big.NewInt(0)
70
71	hashMsg := HashBytes(m)
72
73	r, s, err := ecdsa.Sign(rand.Reader, privK, hashMsg[:])
74	if err != nil {
75		return []byte{}, err
76	}
77
78	sig := PackSignature(r, s)
79
80	return sig, nil
81
82}
83
84func VerifySignature(pubK *ecdsa.PublicKey, m []byte, sig []byte) bool {
85	hashMsg := HashBytes(m)
86
87	r, s, err := UnpackSignature(sig)
88	if err != nil {
89		return false
90	}
91
92	verified := ecdsa.Verify(pubK, hashMsg[:], r, s)
93	return verified
94}