forked from nknorg/crypto
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcipher.go
More file actions
46 lines (36 loc) · 1.08 KB
/
cipher.go
File metadata and controls
46 lines (36 loc) · 1.08 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
package crypto
import (
"crypto/aes"
"crypto/cipher"
"errors"
"fmt"
)
func ToAesKey(pwd []byte) []byte {
return SHA256.Hash(SHA256.Hash(pwd))
}
func AesEncrypt(plaintext []byte, key []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("AesEncrypt: Invalid key. %v\n", err)
}
if (len(plaintext) % block.BlockSize()) != 0 {
return nil, errors.New("AesEncrypt: input not full blocks.")
}
ciphertext := make([]byte, len(plaintext))
blockMode := cipher.NewCBCEncrypter(block, iv)
blockMode.CryptBlocks(ciphertext, plaintext)
return ciphertext, nil
}
func AesDecrypt(ciphertext []byte, key []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("AesDecrypt: invalid key. %v\n", err)
}
if (len(ciphertext) % block.BlockSize()) != 0 {
return nil, errors.New("AesDecrypt: input not full blocks.")
}
plaintext := make([]byte, len(ciphertext))
blockModel := cipher.NewCBCDecrypter(block, iv)
blockModel.CryptBlocks(plaintext, ciphertext)
return plaintext, nil
}