cranberry

Форк
0
/
signature.go 
88 строк · 2.5 Кб
1
package utility
2

3
import (
4
	"crypto/ecdsa"
5
	"crypto/elliptic"
6
	"crypto/rand"
7
	"crypto/sha256"
8
	"crypto/x509"
9
	"log"
10

11
	"math/big"
12

13
	pbapi "gitverse.ru/IvanTimofeev/cranberry/pkg/grpc"
14
)
15

16
func NewSignature(r, s big.Int) *pbapi.Signature {
17
	return &pbapi.Signature{
18
		R: r.Bytes(),
19
		S: s.Bytes(),
20
	}
21
}
22

23
func GenerateKeys() (*ecdsa.PrivateKey, error) {
24
	return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
25
}
26

27
func SignTx(priv *ecdsa.PrivateKey, tx *pbapi.Tx) (*pbapi.Signature, error) {
28
	hashBytes := TxToHashBytes(tx)
29
	r, s, err := ecdsa.Sign(rand.Reader, priv, hashBytes)
30
	if err != nil {
31
		return nil, err
32
	}
33
	return NewSignature(*r, *s), nil
34
}
35

36
func SignBlock(priv *ecdsa.PrivateKey, bh *pbapi.BlockHeader) (*pbapi.Signature, error) {
37
	hashBytes := BlockHeaderToHashBytes(bh)
38
	r, s, err := ecdsa.Sign(rand.Reader, priv, hashBytes)
39
	if err != nil {
40
		return nil, err
41
	}
42
	return NewSignature(*r, *s), nil
43
}
44

45
func VerifyBlock(pub *ecdsa.PublicKey, signature *pbapi.Signature, bh *pbapi.BlockHeader) bool {
46
	r := new(big.Int).SetBytes(signature.R)
47
	s := new(big.Int).SetBytes(signature.S)
48
	hashBytes := BlockHeaderToHashBytes(bh)
49
	return ecdsa.Verify(pub, hashBytes, r, s)
50
}
51

52
func VerifyTx(pub *ecdsa.PublicKey, txc *pbapi.TxContainer) bool {
53
	r := new(big.Int).SetBytes(txc.Signature.R)
54
	s := new(big.Int).SetBytes(txc.Signature.S)
55
	hashBytes := TxToHashBytes(txc.Tx)
56
	return ecdsa.Verify(pub, hashBytes, r, s)
57
}
58

59
func BytesToPubKey(data []byte) *ecdsa.PublicKey {
60
	pubKey, err := x509.ParsePKIXPublicKey(data)
61
	if err != nil {
62
		log.Fatalf("Ошибка при парсинге публичного ключа: %v", err)
63
	}
64
	ecdsaPubKey, ok := pubKey.(*ecdsa.PublicKey)
65
	if !ok {
66
		log.Fatal("Публичный ключ не является ECDSA публичным ключом")
67
	}
68
	return ecdsaPubKey
69
}
70

71
func PubKeyToBytes(pubKey *ecdsa.PublicKey) []byte {
72
	pubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey)
73
	if err != nil {
74
		log.Fatalf("Ошибка при сериализации публичного ключа: %v", err)
75
	}
76
	return pubKeyBytes
77
}
78

79
func GeneratePrivKeyBySeed(seed string) (*ecdsa.PrivateKey, error) {
80
	hash := sha256.Sum256([]byte(seed))
81
	privateKeyInt := new(big.Int).SetBytes(hash[:])
82
	curve := elliptic.P256()
83
	privateKey := new(ecdsa.PrivateKey)
84
	privateKey.D = privateKeyInt
85
	privateKey.PublicKey.Curve = curve
86
	privateKey.PublicKey.X, privateKey.PublicKey.Y = curve.ScalarBaseMult(privateKey.D.Bytes())
87
	return privateKey, nil
88
}
89

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.