forked from MixinNetwork/mobilecoin-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemo.go
69 lines (55 loc) · 1.4 KB
/
memo.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
package api
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha512"
"encoding/hex"
"io"
"golang.org/x/crypto/hkdf"
)
func EncryptMemo(plain string, public, private string) ([]byte, error) {
secret := createSharedSecret(hexToPoint(public), hexToScalar(private))
hash := sha512.New
salt := []byte("mc-memo-okm")
hkdf := hkdf.New(hash, secret.Bytes(), salt, []byte(""))
key := make([]byte, 48)
_, err := io.ReadFull(hkdf, key)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key[:32])
if err != nil {
return nil, err
}
data, err := hex.DecodeString(plain)
if err != nil {
return nil, err
}
stream := cipher.NewCTR(block, key[32:])
ciphertext := make([]byte, len(data))
stream.XORKeyStream(ciphertext, data)
return ciphertext, nil
}
func DecryptMemo(text string, public, private string) ([]byte, error) {
secret := createSharedSecret(hexToPoint(public), hexToScalar(private))
hash := sha512.New
salt := []byte("mc-memo-okm")
hkdf := hkdf.New(hash, secret.Bytes(), salt, []byte(""))
key := make([]byte, 48)
_, err := io.ReadFull(hkdf, key)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key[:32])
if err != nil {
return nil, err
}
data, err := hex.DecodeString(text)
if err != nil {
return nil, err
}
stream := cipher.NewCTR(block, key[32:])
plaintext := make([]byte, len(data))
stream.XORKeyStream(plaintext, data)
return plaintext, nil
}