-
Notifications
You must be signed in to change notification settings - Fork 23
/
ecies.go
104 lines (82 loc) · 2.36 KB
/
ecies.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package eciesgo
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"math/big"
)
// Encrypt encrypts a passed message with a receiver public key, returns ciphertext or encryption error
func Encrypt(pubkey *PublicKey, msg []byte) ([]byte, error) {
var ct bytes.Buffer
// Generate ephemeral key
ek, err := GenerateKey()
if err != nil {
return nil, err
}
ct.Write(ek.PublicKey.Bytes(false))
// Derive shared secret
ss, err := ek.Encapsulate(pubkey)
if err != nil {
return nil, err
}
// AES encryption
block, err := aes.NewCipher(ss)
if err != nil {
return nil, fmt.Errorf("cannot create new aes block: %w", err)
}
nonce := make([]byte, 16)
if _, err := rand.Read(nonce); err != nil {
return nil, fmt.Errorf("cannot read random bytes for nonce: %w", err)
}
ct.Write(nonce)
aesgcm, err := cipher.NewGCMWithNonceSize(block, 16)
if err != nil {
return nil, fmt.Errorf("cannot create aes gcm: %w", err)
}
ciphertext := aesgcm.Seal(nil, nonce, msg, nil)
tag := ciphertext[len(ciphertext)-aesgcm.NonceSize():]
ct.Write(tag)
ciphertext = ciphertext[:len(ciphertext)-len(tag)]
ct.Write(ciphertext)
return ct.Bytes(), nil
}
// Decrypt decrypts a passed message with a receiver private key, returns plaintext or decryption error
func Decrypt(privkey *PrivateKey, msg []byte) ([]byte, error) {
// Message cannot be less than length of public key (65) + nonce (16) + tag (16)
if len(msg) <= (1 + 32 + 32 + 16 + 16) {
return nil, fmt.Errorf("invalid length of message")
}
// Ephemeral sender public key
ethPubkey := &PublicKey{
Curve: getCurve(),
X: new(big.Int).SetBytes(msg[1:33]),
Y: new(big.Int).SetBytes(msg[33:65]),
}
// Shift message
msg = msg[65:]
// Derive shared secret
ss, err := ethPubkey.Decapsulate(privkey)
if err != nil {
return nil, err
}
// AES decryption part
nonce := msg[:16]
tag := msg[16:32]
// Create Golang-accepted ciphertext
ciphertext := bytes.Join([][]byte{msg[32:], tag}, nil)
block, err := aes.NewCipher(ss)
if err != nil {
return nil, fmt.Errorf("cannot create new aes block: %w", err)
}
gcm, err := cipher.NewGCMWithNonceSize(block, 16)
if err != nil {
return nil, fmt.Errorf("cannot create gcm cipher: %w", err)
}
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("cannot decrypt ciphertext: %w", err)
}
return plaintext, nil
}