status-go/protocol/common/crypto.go

70 lines
1.4 KiB
Go
Raw Normal View History

package common
2020-07-03 08:02:28 +00:00
import (
"crypto/aes"
"crypto/cipher"
"crypto/ecdsa"
"errors"
2020-07-03 08:02:28 +00:00
"github.com/status-im/status-go/eth-node/crypto"
"golang.org/x/crypto/sha3"
"io"
)
const nonceLength = 12
var ErrInvalidCiphertextLength = errors.New("invalid cyphertext length")
func HashPublicKey(pk *ecdsa.PublicKey) []byte {
return Shake256(crypto.CompressPubkey(pk))
2020-07-03 08:02:28 +00:00
}
func Decrypt(cyphertext []byte, key []byte) ([]byte, error) {
2020-07-03 08:02:28 +00:00
if len(cyphertext) < nonceLength {
return nil, ErrInvalidCiphertextLength
}
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := cyphertext[:nonceLength]
return gcm.Open(nil, nonce, cyphertext[nonceLength:], nil)
}
func Encrypt(plaintext []byte, key []byte, reader io.Reader) ([]byte, error) {
2020-07-03 08:02:28 +00:00
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func Shake256(buf []byte) []byte {
2020-07-03 08:02:28 +00:00
h := make([]byte, 64)
sha3.ShakeSum256(h, buf)
return h
}
// IsPubKeyEqual checks that two public keys are equal
func IsPubKeyEqual(a, b *ecdsa.PublicKey) bool {
// the curve is always the same, just compare the points
return a.X.Cmp(b.X) == 0 && a.Y.Cmp(b.Y) == 0
}