-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsm2.go
100 lines (94 loc) · 2.35 KB
/
sm2.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
/*
* Copyright (c) 2020. Aberic - All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gnomon
import (
"encoding/pem"
"github.com/tjfoc/gmsm/sm2"
)
// SM2Generate SM2公钥私钥产生
//
// path 指定公私钥所在生成目录
func SM2Generate() (pri *sm2.PrivateKey, pub *sm2.PublicKey, err error) {
// 生成密钥对
if pri, err = sm2.GenerateKey(); err == nil {
pub = &pri.PublicKey
}
return
}
// SM2GeneratePemBytes SM2公钥私钥产生
func SM2GeneratePemBytes(priPemType, pubPemType, passwd string) (priBytes, pubBytes []byte, err error) {
var (
pri *sm2.PrivateKey
pub *sm2.PublicKey
)
// 生成密钥对
if pri, pub, err = SM2Generate(); nil == err {
if priBytes, err = SM2Pri2PemBytes(priPemType, passwd, pri); nil != err {
return
}
if pubBytes, err = SM2Pub2PemBytes(pubPemType, pub); nil != err {
return
}
}
return
}
// SM2Pri2PemBytes SM2Pri2Bytes
func SM2Pri2PemBytes(priPemType, passwd string, pri *sm2.PrivateKey) (data []byte, err error) {
var (
der, pw []byte
block *pem.Block
)
if StringIsEmpty(passwd) {
pw = nil
} else {
pw = []byte(passwd)
}
if der, err = sm2.MarshalSm2PrivateKey(pri, pw); err == nil {
if StringIsEmpty(priPemType) {
block = &pem.Block{
Type: "PRIVATE KEY",
Bytes: der,
}
} else {
block = &pem.Block{
Type: priPemType,
Bytes: der,
}
}
data = pem.EncodeToMemory(block)
}
return
}
// SM2Pub2PemBytes SM2Pub2PemBytes
func SM2Pub2PemBytes(pubPemType string, pub *sm2.PublicKey) (data []byte, err error) {
var (
der []byte
block *pem.Block
)
if der, err = sm2.MarshalSm2PublicKey(pub); err == nil {
if StringIsEmpty(pubPemType) {
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: der,
}
} else {
block = &pem.Block{
Type: pubPemType,
Bytes: der,
}
}
data = pem.EncodeToMemory(block)
}
return
}