-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsa_manager.go
73 lines (58 loc) · 1.37 KB
/
rsa_manager.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
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"os"
"path/filepath"
)
func GenerateRsaKeys(dir string, name string) error {
// Obtenemos el directorio actual
rpath, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return err
}
// Generamos y formateamos las llaves
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
privateKeyByteCode := x509.MarshalPKCS1PrivateKey(privateKey)
privateKeyBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privateKeyByteCode,
}
publicKeyByteCode, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
return err
}
publicKeyBlock := pem.Block{
Type: "RSA PUBLIC KEY",
Headers: nil,
Bytes: publicKeyByteCode,
}
// Creamos y escribimos los ficheros
filepublic, err := os.Create(rpath + string(os.PathSeparator) + name + ".public")
if err != nil {
return err
}
defer filepublic.Close()
_, err = filepublic.Write([]byte(pem.EncodeToMemory(&publicKeyBlock)))
if err != nil {
return err
}
filepublic.Sync()
fileprivate, err := os.Create(rpath + string(os.PathSeparator) + name + ".private")
if err != nil {
return err
}
defer fileprivate.Close()
_, err = fileprivate.Write([]byte(pem.EncodeToMemory(&privateKeyBlock)))
if err != nil {
return err
}
fileprivate.Sync()
return nil
}