forked from nknorg/nkn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
55 lines (43 loc) · 1.3 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
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"errors"
"github.com/nknorg/nkn/v2/common"
)
func PasswordHash(password []byte) []byte {
passwordhash := sha256.Sum256(password)
passwordhash2 := sha256.Sum256(passwordhash[:])
passwordhash3 := sha256.Sum256(passwordhash2[:])
common.ClearBytes(passwordhash[:])
common.ClearBytes(passwordhash2[:])
return passwordhash3[:]
}
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")
}
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, 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")
}
plaintext := make([]byte, len(ciphertext))
blockMode := cipher.NewCBCDecrypter(block, iv)
blockMode.CryptBlocks(plaintext, ciphertext)
return plaintext, nil
}