-
Notifications
You must be signed in to change notification settings - Fork 3
/
generate.go
77 lines (71 loc) · 1.8 KB
/
generate.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 rsaKit
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/richelieu-yang/chimera/v3/src/core/errorKit"
"github.com/richelieu-yang/chimera/v3/src/file/fileKit"
"os"
)
// GenerateKeyFiles 生成: 公钥 && 私钥
/*
@param bits 512 ||1024 || 2048 || 3072 || 4096
@param format PKCS1 || PKCS8
@param password 私钥的密码(没有则传"")
@param priPath 生成私钥文件的位置
@param pubPath 生成公钥文件的位置
*/
func GenerateKeyFiles(bits int, format KeyFormat, password, priPath, pubPath string, perm os.FileMode) error {
pri, pub, err := GenerateKeys(bits, format, password)
if err != nil {
return err
}
if err := fileKit.WriteToFile(priPath, pri, perm); err != nil {
return err
}
if err := fileKit.WriteToFile(pubPath, pub, perm); err != nil {
return err
}
return nil
}
func GenerateKeys(bits int, format KeyFormat, password string) (pri []byte, pub []byte, err error) {
// 生成私钥
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, nil, err
}
var derStream []byte
switch format {
case PKCS1:
derStream = x509.MarshalPKCS1PrivateKey(privateKey)
case PKCS8:
derStream, err = x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return nil, nil, err
}
default:
return nil, nil, errorKit.Newf("invalid format(%v)", format)
}
block := &pem.Block{
Type: "PRIVATE KEY",
Bytes: derStream,
}
pri = pem.EncodeToMemory(block)
pri, err = EncryptPrivatePEM(pri, format, password)
if err != nil {
return nil, nil, err
}
// 生成公钥
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return nil, nil, err
}
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: derPkix,
}
pub = pem.EncodeToMemory(block)
return pri, pub, nil
}