/
aesCfb256.go
73 lines (51 loc) · 1.43 KB
/
aesCfb256.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
package account
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func EncryptWithIV(key, iv, plainTxt []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
cipherText := make([]byte, aes.BlockSize+len(plainTxt))
copy(cipherText[:aes.BlockSize], iv)
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], plainTxt)
return cipherText, nil
}
func Encrypt(key []byte, plainTxt []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
cipherText := make([]byte, aes.BlockSize+len(plainTxt))
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], plainTxt)
return cipherText, nil
}
func Decrypt(key []byte, cipherTxt []byte) ([]byte, error) {
_,plainTxt,err:=DecryptAndIV(key,cipherTxt)
return plainTxt,err
}
func DecryptAndIV(key []byte, cipherTxt []byte) (iv, plainTxt []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil,nil, err
}
if len(cipherTxt) < aes.BlockSize {
return nil,nil, fmt.Errorf("cipher text too short")
}
iv = cipherTxt[:aes.BlockSize]
cipherTxt = cipherTxt[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(cipherTxt, cipherTxt)
return iv,cipherTxt, nil
}