-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathaes.go
48 lines (39 loc) · 996 Bytes
/
aes.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
package lnurl
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
)
func AESCipher(key, plaintext []byte) (ciphertext []byte, iv []byte, err error) {
pad := aes.BlockSize - (len(plaintext) % aes.BlockSize)
padding := make([]byte, pad)
for i := 0; i < pad; i++ {
padding[i] = byte(pad)
}
plaintext = append(plaintext, padding...)
block, err := aes.NewCipher(key)
if err != nil {
return
}
ciphertext = make([]byte, len(plaintext))
iv = make([]byte, aes.BlockSize)
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
return
}
cbc := cipher.NewCBCEncrypter(block, iv)
cbc.CryptBlocks(ciphertext, plaintext)
return
}
func AESDecipher(key, ciphertext, iv []byte) (plaintext []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
size := len(ciphertext)
pad := ciphertext[size-1]
plaintext = ciphertext[:size-int(pad)]
return plaintext, nil
}