-
Notifications
You must be signed in to change notification settings - Fork 63
/
utils.go
106 lines (85 loc) · 2.16 KB
/
utils.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
package util
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/youmark/pkcs8"
"time"
)
const LegacyPem = "legacy-pem"
func ConvertSecondsToTime(t int64) time.Time {
return time.Unix(0, t*int64(time.Second))
}
func GetJsonAsString(i interface{}) (s string) {
byte, _ := json.MarshalIndent(i, "", " ")
s = string(byte)
return
}
func DecryptPkcs8PrivateKey(privateKey, password string) (string, error) {
block, _ := pem.Decode([]byte(privateKey))
key, _, err := pkcs8.ParsePrivateKey(block.Bytes, []byte(password))
if err != nil {
return "", err
}
var pemType string
switch key.(type) {
case *rsa.PrivateKey:
pemType = "RSA PRIVATE KEY"
case *ecdsa.PrivateKey:
pemType = "EC PRIVATE KEY"
case ed25519.PrivateKey:
pemType = "PRIVATE KEY"
default:
return "", fmt.Errorf("failed to determine private key type")
}
privateKeyBytes, err := pkcs8.MarshalPrivateKey(key, nil, nil)
if err != nil {
return "", err
}
pemBytes := pem.EncodeToMemory(&pem.Block{Type: pemType, Bytes: privateKeyBytes})
return string(pemBytes), nil
}
func EncryptPkcs1PrivateKey(privateKey, password string) (string, error) {
block, _ := pem.Decode([]byte(privateKey))
keyType := GetPrivateKeyType(privateKey, password)
var encrypted *pem.Block
var err error
if keyType == "RSA PRIVATE KEY" {
encrypted, err = X509EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", block.Bytes, []byte(password), PEMCipherAES256)
if err != nil {
return "", nil
}
} else if keyType == "EC PRIVATE KEY" {
encrypted, err = X509EncryptPEMBlock(rand.Reader, "EC PRIVATE KEY", block.Bytes, []byte(password), PEMCipherAES256)
if err != nil {
return "", nil
}
}
return string(pem.EncodeToMemory(encrypted)), nil
}
func GetBooleanRef(val bool) *bool {
return &val
}
func GetIntRef(val int) *int {
return &val
}
func GetPrivateKeyType(pk, pass string) string {
p, _ := pem.Decode([]byte(pk))
if p == nil {
return ""
}
var keyType string
switch p.Type {
case "EC PRIVATE KEY":
keyType = "EC PRIVATE KEY"
case "RSA PRIVATE KEY":
keyType = "RSA PRIVATE KEY"
default:
keyType = ""
}
return keyType
}