2018-09-24 18:07:34 +00:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
2020-01-10 18:59:01 +00:00
|
|
|
"context"
|
2018-09-24 18:07:34 +00:00
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
2018-09-27 13:07:32 +00:00
|
|
|
"crypto/ecdsa"
|
2018-09-24 18:07:34 +00:00
|
|
|
"crypto/rand"
|
2018-09-27 13:07:32 +00:00
|
|
|
"encoding/hex"
|
2018-09-24 18:07:34 +00:00
|
|
|
"errors"
|
2018-10-04 16:53:48 +00:00
|
|
|
"fmt"
|
2020-01-15 11:36:49 +00:00
|
|
|
|
2020-01-10 18:59:01 +00:00
|
|
|
"golang.org/x/crypto/sha3"
|
2019-06-12 09:16:00 +00:00
|
|
|
|
2020-01-15 11:36:49 +00:00
|
|
|
types "github.com/status-im/status-go/eth-node/types"
|
|
|
|
|
2019-11-23 17:57:05 +00:00
|
|
|
gethcrypto "github.com/ethereum/go-ethereum/crypto"
|
2018-09-24 18:07:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
aesNonceLength = 12
|
|
|
|
)
|
|
|
|
|
2019-11-23 17:57:05 +00:00
|
|
|
// Sign calculates an ECDSA signature.
|
|
|
|
//
|
|
|
|
// This function is susceptible to chosen plaintext attacks that can leak
|
|
|
|
// information about the private key that is used for signing. Callers must
|
|
|
|
// be aware that the given digest cannot be chosen by an adversery. Common
|
|
|
|
// solution is to hash any input before calculating the signature.
|
|
|
|
//
|
|
|
|
// The produced signature is in the [R || S || V] format where V is 0 or 1.
|
|
|
|
func Sign(digestHash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
|
|
|
|
return gethcrypto.Sign(digestHash, prv)
|
|
|
|
}
|
|
|
|
|
2019-10-09 14:22:53 +00:00
|
|
|
// SignBytes signs the hash of arbitrary data.
|
2019-11-23 17:57:05 +00:00
|
|
|
func SignBytes(data []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
|
|
|
|
return Sign(Keccak256(data), prv)
|
2019-10-09 14:22:53 +00:00
|
|
|
}
|
|
|
|
|
2019-11-23 17:57:05 +00:00
|
|
|
// SignBytesAsHex signs the Keccak256 hash of arbitrary data and returns its hex representation.
|
2019-10-09 14:22:53 +00:00
|
|
|
func SignBytesAsHex(data []byte, identity *ecdsa.PrivateKey) (string, error) {
|
|
|
|
signature, err := SignBytes(data, identity)
|
2018-09-27 13:07:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return hex.EncodeToString(signature), nil
|
|
|
|
}
|
|
|
|
|
2019-10-09 14:22:53 +00:00
|
|
|
// SignStringAsHex signs the Keccak256 hash of arbitrary string and returns its hex representation.
|
|
|
|
func SignStringAsHex(data string, identity *ecdsa.PrivateKey) (string, error) {
|
|
|
|
return SignBytesAsHex([]byte(data), identity)
|
|
|
|
}
|
|
|
|
|
|
|
|
// VerifySignatures verifies tuples of signatures content/hash/public key
|
2018-09-27 13:07:32 +00:00
|
|
|
func VerifySignatures(signaturePairs [][3]string) error {
|
|
|
|
for _, signaturePair := range signaturePairs {
|
2019-11-23 17:57:05 +00:00
|
|
|
content := Keccak256([]byte(signaturePair[0]))
|
2018-09-27 13:07:32 +00:00
|
|
|
|
|
|
|
signature, err := hex.DecodeString(signaturePair[1])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
publicKeyBytes, err := hex.DecodeString(signaturePair[2])
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-11-23 17:57:05 +00:00
|
|
|
publicKey, err := UnmarshalPubkey(publicKeyBytes)
|
2018-09-27 13:07:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-11-23 17:57:05 +00:00
|
|
|
recoveredKey, err := SigToPub(
|
2018-09-27 13:07:32 +00:00
|
|
|
content,
|
|
|
|
signature,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-11-23 17:57:05 +00:00
|
|
|
if PubkeyToAddress(*recoveredKey) != PubkeyToAddress(*publicKey) {
|
2018-09-27 13:07:32 +00:00
|
|
|
return errors.New("identity key and signature mismatch")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-10-04 16:53:48 +00:00
|
|
|
// ExtractSignatures extract from tuples of signatures content a public key
|
2019-10-14 14:10:48 +00:00
|
|
|
// DEPRECATED: use ExtractSignature
|
2018-10-04 16:53:48 +00:00
|
|
|
func ExtractSignatures(signaturePairs [][2]string) ([]string, error) {
|
|
|
|
response := make([]string, len(signaturePairs))
|
|
|
|
for i, signaturePair := range signaturePairs {
|
2019-11-23 17:57:05 +00:00
|
|
|
content := Keccak256([]byte(signaturePair[0]))
|
2018-10-04 16:53:48 +00:00
|
|
|
|
|
|
|
signature, err := hex.DecodeString(signaturePair[1])
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-11-23 17:57:05 +00:00
|
|
|
recoveredKey, err := SigToPub(
|
2018-10-04 16:53:48 +00:00
|
|
|
content,
|
|
|
|
signature,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-11-23 17:57:05 +00:00
|
|
|
response[i] = fmt.Sprintf("%x", FromECDSAPub(recoveredKey))
|
2018-10-04 16:53:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return response, nil
|
|
|
|
}
|
|
|
|
|
2019-10-14 14:10:48 +00:00
|
|
|
// ExtractSignature returns a public key for a given data and signature.
|
|
|
|
func ExtractSignature(data, signature []byte) (*ecdsa.PublicKey, error) {
|
2019-11-23 17:57:05 +00:00
|
|
|
dataHash := Keccak256(data)
|
|
|
|
return SigToPub(dataHash, signature)
|
2019-10-14 14:10:48 +00:00
|
|
|
}
|
|
|
|
|
2018-09-24 18:07:34 +00:00
|
|
|
func EncryptSymmetric(key, plaintext []byte) ([]byte, error) {
|
|
|
|
block, err := aes.NewCipher(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
|
|
|
|
salt, err := generateSecureRandomData(aesNonceLength)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
aesgcm, err := cipher.NewGCM(block)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-06-12 09:16:00 +00:00
|
|
|
encrypted := aesgcm.Seal(nil, salt, plaintext, nil)
|
2018-09-24 18:07:34 +00:00
|
|
|
return append(encrypted, salt...), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func DecryptSymmetric(key []byte, cyphertext []byte) ([]byte, error) {
|
|
|
|
// symmetric messages are expected to contain the 12-byte nonce at the end of the payload
|
|
|
|
if len(cyphertext) < aesNonceLength {
|
|
|
|
return nil, errors.New("missing salt or invalid payload in symmetric message")
|
|
|
|
}
|
|
|
|
salt := cyphertext[len(cyphertext)-aesNonceLength:]
|
|
|
|
|
|
|
|
block, err := aes.NewCipher(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
aesgcm, err := cipher.NewGCM(block)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
decrypted, err := aesgcm.Open(nil, salt, cyphertext[:len(cyphertext)-aesNonceLength], nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return decrypted, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func containsOnlyZeros(data []byte) bool {
|
|
|
|
for _, b := range data {
|
|
|
|
if b != 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func validateDataIntegrity(k []byte, expectedSize int) bool {
|
|
|
|
if len(k) != expectedSize {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if containsOnlyZeros(k) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func generateSecureRandomData(length int) ([]byte, error) {
|
|
|
|
res := make([]byte, length)
|
|
|
|
|
|
|
|
_, err := rand.Read(res)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if !validateDataIntegrity(res, length) {
|
|
|
|
return nil, errors.New("crypto/rand failed to generate secure random data")
|
|
|
|
}
|
|
|
|
|
|
|
|
return res, nil
|
|
|
|
}
|
2020-01-10 18:59:01 +00:00
|
|
|
|
|
|
|
// TextHash is a helper function that calculates a hash for the given message that can be
|
|
|
|
// safely used to calculate a signature from.
|
|
|
|
//
|
|
|
|
// The hash is calulcated as
|
|
|
|
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
|
|
|
|
//
|
|
|
|
// This gives context to the signed message and prevents signing of transactions.
|
|
|
|
func TextHash(data []byte) []byte {
|
|
|
|
hash, _ := TextAndHash(data)
|
|
|
|
return hash
|
|
|
|
}
|
|
|
|
|
|
|
|
// TextAndHash is a helper function that calculates a hash for the given message that can be
|
|
|
|
// safely used to calculate a signature from.
|
|
|
|
//
|
|
|
|
// The hash is calulcated as
|
|
|
|
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
|
|
|
|
//
|
|
|
|
// This gives context to the signed message and prevents signing of transactions.
|
|
|
|
func TextAndHash(data []byte) ([]byte, string) {
|
|
|
|
msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), string(data))
|
|
|
|
hasher := sha3.NewLegacyKeccak256()
|
|
|
|
hasher.Write([]byte(msg))
|
|
|
|
return hasher.Sum(nil), msg
|
|
|
|
}
|
|
|
|
|
|
|
|
func EcRecover(ctx context.Context, data types.HexBytes, sig types.HexBytes) (types.Address, error) {
|
|
|
|
// Returns the address for the Account that was used to create the signature.
|
|
|
|
//
|
|
|
|
// Note, this function is compatible with eth_sign and personal_sign. As such it recovers
|
|
|
|
// the address of:
|
|
|
|
// hash = keccak256("\x19${byteVersion}Ethereum Signed Message:\n${message length}${message}")
|
|
|
|
// addr = ecrecover(hash, signature)
|
|
|
|
//
|
|
|
|
// Note, the signature must conform to the secp256k1 curve R, S and V values, where
|
|
|
|
// the V value must be be 27 or 28 for legacy reasons.
|
|
|
|
//
|
|
|
|
// https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
|
|
|
|
if len(sig) != 65 {
|
|
|
|
return types.Address{}, fmt.Errorf("signature must be 65 bytes long")
|
|
|
|
}
|
|
|
|
if sig[64] != 27 && sig[64] != 28 {
|
|
|
|
return types.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
|
|
|
|
}
|
|
|
|
sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
|
|
|
|
hash := TextHash(data)
|
|
|
|
rpk, err := SigToPub(hash, sig)
|
|
|
|
if err != nil {
|
|
|
|
return types.Address{}, err
|
|
|
|
}
|
|
|
|
return PubkeyToAddress(*rpk), nil
|
|
|
|
}
|