-
Notifications
You must be signed in to change notification settings - Fork 27
/
encryption.go
114 lines (92 loc) · 2.05 KB
/
encryption.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
* knoxite
* Copyright (c) 2016-2018, Christian Muehlhaeuser <muesli@gmail.com>
*
* For license see LICENSE
*/
package knoxite
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"errors"
)
// Available encryption algos.
const (
EncryptionNone = iota
EncryptionAES
)
// Error declarations.
var (
ErrInvalidPassword = errors.New("empty password not permitted")
)
// Encryptor is a pipeline processor that encrypts data.
type Encryptor struct {
Method uint16
iv []byte
block cipher.Block
}
// NewEncryptor returns a newly configured Encryptor.
func NewEncryptor(method uint16, password string) (Encryptor, error) {
e := Encryptor{
Method: method,
}
if method == EncryptionAES {
if len(password) == 0 {
return e, ErrInvalidPassword
}
key := sha256.Sum256([]byte(password))
e.iv = key[:aes.BlockSize]
var err error
e.block, err = aes.NewCipher(key[:])
if err != nil {
return e, err
}
}
return e, nil
}
// Process encrypts the data.
func (e Encryptor) Process(data []byte) ([]byte, error) {
if e.Method == EncryptionNone {
return data, nil
}
b := make([]byte, len(data))
encrypter := cipher.NewCFBEncrypter(e.block, e.iv)
encrypter.XORKeyStream(b, data)
return b, nil
}
// Decryptor is a pipeline processor that decrypts data.
type Decryptor struct {
Method uint16
iv []byte
block cipher.Block
}
// NewDecryptor returns a newly configured Decryptor.
func NewDecryptor(method uint16, password string) (Decryptor, error) {
e := Decryptor{
Method: method,
}
if method == EncryptionAES {
if len(password) == 0 {
return e, ErrInvalidPassword
}
key := sha256.Sum256([]byte(password))
e.iv = key[:aes.BlockSize]
var err error
e.block, err = aes.NewCipher(key[:])
if err != nil {
return e, err
}
}
return e, nil
}
// Process decrypts the data.
func (e Decryptor) Process(data []byte) ([]byte, error) {
if e.Method == EncryptionNone {
return data, nil
}
b := make([]byte, len(data))
decrypter := cipher.NewCFBDecrypter(e.block, e.iv)
decrypter.XORKeyStream(b, data)
return b, nil
}