-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcfbBlockCipher.go
More file actions
64 lines (56 loc) · 1.61 KB
/
cfbBlockCipher.go
File metadata and controls
64 lines (56 loc) · 1.61 KB
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
package blockEncryption
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
"io/ioutil"
)
type CFBBlockCipher struct {
key []byte
}
func NewCFBBlockCipher(secret []byte) *CFBBlockCipher {
return &CFBBlockCipher{key: secret}
}
func (cfb *CFBBlockCipher) EncryptFile(fileName string) ([]byte, error){
//read the file as cyphertext
plainText, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
return cfb.EncryptMessage(plainText)
}
func (cfb *CFBBlockCipher) EncryptMessage(message []byte) ([]byte, error) {
//create new aes cypher
block, err := aes.NewCipher(cfb.key)
if err != nil {
return nil, err
}
//Secure AES require an unique IV, adding additional bytes in beginning of the block
cipherText := make([]byte, aes.BlockSize+len(message))
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:], message)
return cipherText, nil
}
func (cfb *CFBBlockCipher) Decrypt(cipherText []byte) ([]byte, error){
block, err := aes.NewCipher(cfb.key)
if err != nil {
return nil, err
}
if len(cipherText) < aes.BlockSize {
return nil, errors.New("invalid ciphertext block")
}
plaintext := make([]byte, aes.BlockSize+len(cipherText))
//An unique IV needs to be in the beginning
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
// XORKeyStream can work in-place if the two arguments are the same.
stream.XORKeyStream(plaintext, cipherText)
return plaintext, nil
}