-
Notifications
You must be signed in to change notification settings - Fork 24
/
cipher.go
77 lines (58 loc) · 1.49 KB
/
cipher.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
package pkcs1
import(
"io"
"fmt"
"crypto/md5"
"github.com/deatil/go-cryptobin/tool"
)
// 加密接口
type Cipher interface {
// 名称
Name() string
// 块大小
BlockSize() int
// 加密, 返回: [加密后数据, iv, error]
Encrypt(rand io.Reader, key, plaintext []byte) ([]byte, []byte, error)
// 解密
Decrypt(key, iv, ciphertext []byte) ([]byte, error)
}
var ciphers = make(map[string]func() Cipher)
// 添加加密
func AddCipher(name string, cipher func() Cipher) {
ciphers[name] = cipher
}
// 获取加密
func GetCipher(name string) (Cipher, error) {
cipher, ok := ciphers[name]
if !ok {
return nil, fmt.Errorf("pkcs1: unsupported cipher %s", name)
}
newCipher := cipher()
return newCipher, nil
}
// ===============
// 密钥生成器
func DeriveKey(password, salt []byte, keySize int) []byte {
hash := md5.New()
out := make([]byte, keySize)
var digest []byte
for i := 0; i < len(out); i += len(digest) {
hash.Reset()
hash.Write(digest)
hash.Write(password)
hash.Write(salt)
digest = hash.Sum(digest[:0])
copy(out[i:], digest)
}
return out
}
// ===============
var newPadding = tool.NewPadding()
// 明文补码算法
func pkcs7Padding(text []byte, blockSize int) []byte {
return newPadding.PKCS7Padding(text, blockSize)
}
// 明文减码算法
func pkcs7UnPadding(src []byte) ([]byte, error) {
return newPadding.PKCS7UnPadding(src)
}