-
Notifications
You must be signed in to change notification settings - Fork 40
/
encryptor.go
65 lines (51 loc) · 1.67 KB
/
encryptor.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
package unicreds
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
)
// Encrypt AES encryption method which matches the pycrypto package
// using CTR and AES256. Note this routine seeds the counter/iv with a value of 1
// then throws it away?!
func Encrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, len(plaintext))
initialCounter := newCounter()
stream := cipher.NewCTR(block, initialCounter)
stream.XORKeyStream(ciphertext, plaintext)
return ciphertext, nil
}
// ComputeHmac256 compute a hmac256 signature of the supplied message and return
// the value hex encoded
func ComputeHmac256(message, secret []byte) []byte {
h := hmac.New(sha256.New, secret)
h.Write(message)
src := h.Sum(nil)
dst := make([]byte, hex.EncodedLen(len(src)))
hex.Encode(dst, src)
return dst
}
// Decrypt AES encryption method which matches the pycrypto package
// using CTR and AES256. Note this routine seeds the counter/iv with a value of 1
// then throws it away?!
func Decrypt(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
initialCounter := newCounter()
plaintext := ciphertext
stream := cipher.NewCTR(block, initialCounter)
stream.XORKeyStream(plaintext, ciphertext)
return plaintext, nil
}
// start with a counter block with a default of 1 to be compatible with the python encryptor
// see https://pythonhosted.org/pycrypto/Crypto.Util.Counter-module.html for more info
func newCounter() []byte {
return []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1}
}