Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encrypt decrypt #2130

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 35 additions & 0 deletions btcec/ciphering.go
Expand Up @@ -5,6 +5,11 @@
package btcec

import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"fmt"
secp "github.com/decred/dcrd/dcrec/secp256k1/v4"
)

Expand All @@ -14,3 +19,33 @@ import (
func GenerateSharedSecret(privkey *PrivateKey, pubkey *PublicKey) []byte {
return secp.GenerateSharedSecret(privkey, pubkey)
}

// Encrypt encrypts data for the target public key using AES-128-GCM
yemmyharry marked this conversation as resolved.
Show resolved Hide resolved
func Encrypt(pubKey *PublicKey, msg []byte) ([]byte, error) {
yemmyharry marked this conversation as resolved.
Show resolved Hide resolved
ephemeral, err := NewPrivateKey()
if err != nil {
return nil, fmt.Errorf("failed to generate private key: %v", err)
}

ecdhKey := GenerateSharedSecret(ephemeral, pubKey)
hashedSecret := sha256.Sum256(ecdhKey)
encryptionKey := hashedSecret[:16]
block, err := aes.NewCipher(encryptionKey)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like you sliced the shared secret to 16 bytes here

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes for compatibility with AES-128-GCM encryption

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohh thought you said AES-256-GCM here: a2245a6#r1570762508 but looks like the comment has been updated.

if err != nil {
return nil, err
}

nonce := make([]byte, 16)
if _, err := rand.Read(nonce); err != nil {
return nil, err
}

gcm, err := cipher.NewGCMWithNonceSize(block, 16)
if err != nil {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to understand why it has to be a nonce size of 16 instead of the default 12

return nil, err
}

ciphertext := gcm.Seal(nil, nonce, msg, nil)
ciphertext = append(nonce, ciphertext...)
return ciphertext, nil
}