/
helper.go
76 lines (57 loc) · 1.69 KB
/
helper.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
package crypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"errors"
. "github.com/nknorg/nkn/common"
)
func ToAesKey(pwd []byte) []byte {
pwdhash := sha256.Sum256(pwd)
pwdhash2 := sha256.Sum256(pwdhash[:])
// Fixme clean the password buffer
// ClearBytes(pwd,len(pwd))
ClearBytes(pwdhash[:], 32)
return pwdhash2[:]
}
func AesEncrypt(plaintext []byte, key []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, errors.New("invalid decrypt key")
}
//blockSize := block.BlockSize()
//plaintext = PKCS5Padding(plaintext, blockSize)
blockMode := cipher.NewCBCEncrypter(block, iv)
ciphertext := make([]byte, len(plaintext))
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, errors.New("invalid decrypt key")
}
blockSize := block.BlockSize()
if len(ciphertext) < blockSize {
return nil, errors.New("ciphertext too short")
}
if len(ciphertext)%blockSize != 0 {
return nil, errors.New("ciphertext is not a multiple of the block size")
}
blockModel := cipher.NewCBCDecrypter(block, iv)
plaintext := make([]byte, len(ciphertext))
blockModel.CryptBlocks(plaintext, ciphertext)
//plaintext = PKCS5UnPadding(plaintext)
return plaintext, nil
}
func PKCS5Padding(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func PKCS5UnPadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}