-
Notifications
You must be signed in to change notification settings - Fork 21
/
cipher_blockcbc.go
113 lines (90 loc) · 2.81 KB
/
cipher_blockcbc.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
package pkcs8pbe
import (
"hash"
"errors"
"crypto/cipher"
"encoding/asn1"
)
// pbe 数据
type pbeBlockParams struct {
Salt []byte
IterationCount int
}
// cbc 模式加密
type CipherBlockCBC struct {
// 对称加密
cipherFunc func(key []byte) (cipher.Block, error)
// hash 摘要
hashFunc func() hash.Hash
// 密钥生成
derivedKeyFunc func(password string, salt string, iter int, keyLen int, h func() hash.Hash) ([]byte, []byte)
// 与 key 长度相关
keySize int
// 与 iv 长度相关
blockSize int
// 迭代次数
iterationCount int
// oid
oid asn1.ObjectIdentifier
}
// 值大小
func (this CipherBlockCBC) KeySize() int {
return this.keySize
}
// oid
func (this CipherBlockCBC) OID() asn1.ObjectIdentifier {
return this.oid
}
// 加密
func (this CipherBlockCBC) Encrypt(password, plaintext []byte) ([]byte, []byte, error) {
// 加密数据补码
plaintext = pkcs7Padding(plaintext, this.blockSize)
salt, err := genRandom(this.blockSize)
if err != nil {
return nil, nil, errors.New(err.Error() + " failed to generate salt")
}
key, iv := this.derivedKeyFunc(string(password), string(salt), this.iterationCount, this.keySize, this.hashFunc)
iv = iv[:this.blockSize]
block, err := this.cipherFunc(key)
if err != nil {
return nil, nil, errors.New("pkcs8:" + err.Error() + " failed to create cipher")
}
// 需要保存的加密数据
encrypted := make([]byte, len(plaintext))
enc := cipher.NewCBCEncrypter(block, iv)
enc.CryptBlocks(encrypted, plaintext)
// 返回数据
paramBytes, err := asn1.Marshal(pbeBlockParams{
Salt: salt,
IterationCount: this.iterationCount,
})
if err != nil {
return nil, nil, err
}
return encrypted, paramBytes, nil
}
// 解密
func (this CipherBlockCBC) Decrypt(password, params, ciphertext []byte) ([]byte, error) {
var param pbeBlockParams
if _, err := asn1.Unmarshal(params, ¶m); err != nil {
return nil, errors.New("pkcs8: invalid PBES2 parameters")
}
key, iv := this.derivedKeyFunc(string(password), string(param.Salt), param.IterationCount, this.keySize, this.hashFunc)
iv = iv[:this.blockSize]
block, err := this.cipherFunc(key)
if err != nil {
return nil, err
}
// 判断数据是否为填充数据
blockSize := block.BlockSize()
dlen := len(ciphertext)
if dlen == 0 || dlen%blockSize != 0 {
return nil, errors.New("pkcs8: invalid padding")
}
plaintext := make([]byte, len(ciphertext))
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(plaintext, ciphertext)
// 解析加密数据
plaintext = pkcs7UnPadding(plaintext)
return plaintext, nil
}