-
Notifications
You must be signed in to change notification settings - Fork 25
/
create.go
122 lines (98 loc) · 2.69 KB
/
create.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
114
115
116
117
118
119
120
121
122
package gost
import (
"errors"
"crypto/rand"
"encoding/pem"
"github.com/deatil/go-cryptobin/gost"
"github.com/deatil/go-cryptobin/pkcs8"
)
type (
// 配置
Opts = pkcs8.Opts
// PBKDF2 配置
PBKDF2Opts = pkcs8.PBKDF2Opts
// Scrypt 配置
ScryptOpts = pkcs8.ScryptOpts
)
var (
// 获取 Cipher 类型
GetCipherFromName = pkcs8.GetCipherFromName
// 获取 hash 类型
GetHashFromName = pkcs8.GetHashFromName
)
// 生成私钥 pem 数据
func (this Gost) CreatePrivateKey() Gost {
return this.CreatePKCS8PrivateKey()
}
// 生成私钥带密码 pem 数据
func (this Gost) CreatePrivateKeyWithPassword(password string, opts ...any) Gost {
return this.CreatePKCS8PrivateKeyWithPassword(password, opts...)
}
// 生成公钥 pem 数据
func (this Gost) CreatePublicKey() Gost {
return this.CreatePKCS8PublicKey()
}
// ==========
// 生成 pkcs8 私钥 pem 数据
func (this Gost) CreatePKCS8PrivateKey() Gost {
if this.privateKey == nil {
err := errors.New("privateKey empty.")
return this.AppendError(err)
}
privateKeyBytes, err := gost.MarshalPrivateKey(this.privateKey)
if err != nil {
return this.AppendError(err)
}
privateBlock := &pem.Block{
Type: "PRIVATE KEY",
Bytes: privateKeyBytes,
}
this.keyData = pem.EncodeToMemory(privateBlock)
return this
}
// 生成 PKCS8 私钥带密码 pem 数据
func (this Gost) CreatePKCS8PrivateKeyWithPassword(password string, opts ...any) Gost {
if this.privateKey == nil {
err := errors.New("privateKey empty.")
return this.AppendError(err)
}
opt, err := pkcs8.ParseOpts(opts...)
if err != nil {
return this.AppendError(err)
}
// 生成私钥
privateKeyBytes, err := gost.MarshalPrivateKey(this.privateKey)
if err != nil {
return this.AppendError(err)
}
// 生成加密数据
privateBlock, err := pkcs8.EncryptPEMBlock(
rand.Reader,
"ENCRYPTED PRIVATE KEY",
privateKeyBytes,
[]byte(password),
opt,
)
if err != nil {
return this.AppendError(err)
}
this.keyData = pem.EncodeToMemory(privateBlock)
return this
}
// 生成公钥 pem 数据
func (this Gost) CreatePKCS8PublicKey() Gost {
if this.publicKey == nil {
err := errors.New("publicKey empty.")
return this.AppendError(err)
}
publicKeyBytes, err := gost.MarshalPublicKey(this.publicKey)
if err != nil {
return this.AppendError(err)
}
publicBlock := &pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyBytes,
}
this.keyData = pem.EncodeToMemory(publicBlock)
return this
}