13
pbapi "gitverse.ru/IvanTimofeev/cranberry/pkg/grpc"
16
func NewSignature(r, s big.Int) *pbapi.Signature {
17
return &pbapi.Signature{
23
func GenerateKeys() (*ecdsa.PrivateKey, error) {
24
return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
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)
33
return NewSignature(*r, *s), nil
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)
42
return NewSignature(*r, *s), nil
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)
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)
59
func BytesToPubKey(data []byte) *ecdsa.PublicKey {
60
pubKey, err := x509.ParsePKIXPublicKey(data)
62
log.Fatalf("Ошибка при парсинге публичного ключа: %v", err)
64
ecdsaPubKey, ok := pubKey.(*ecdsa.PublicKey)
66
log.Fatal("Публичный ключ не является ECDSA публичным ключом")
71
func PubKeyToBytes(pubKey *ecdsa.PublicKey) []byte {
72
pubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey)
74
log.Fatalf("Ошибка при сериализации публичного ключа: %v", err)
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