-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkeys_test.go
73 lines (66 loc) · 1.82 KB
/
keys_test.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 sshkeys_test
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"golang.org/x/crypto/ssh"
)
func generatePrivateRSAKey(bitSize int) (*rsa.PrivateKey, error) {
// Private Key generation
privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
return nil, fmt.Errorf("unable to generate key: %w", err)
}
// Validate Private Key
err = privateKey.Validate()
if err != nil {
return nil, fmt.Errorf("unable to validate key: %w", err)
}
return privateKey, nil
}
func createRSAKey(bitSize int) (ssh.Signer, error) {
pk, err := generatePrivateRSAKey(bitSize)
if err != nil {
return nil, fmt.Errorf("unable to create private key: %w", err)
}
privateKey, err := ssh.ParsePrivateKey(pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: x509.MarshalPKCS1PrivateKey(pk),
}))
if err != nil {
return nil, fmt.Errorf("unable to parse private key: %w", err)
}
return privateKey, nil
}
func generatePrivateECDSAKey(curve elliptic.Curve) (*ecdsa.PrivateKey, error) {
// Private Key generation
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return nil, fmt.Errorf("unable to generate key: %w", err)
}
return privateKey, nil
}
func createECDSAKey(curve elliptic.Curve) (ssh.Signer, error) {
pk, err := generatePrivateECDSAKey(curve)
if err != nil {
return nil, fmt.Errorf("unable to create private key: %w", err)
}
buf, err := x509.MarshalECPrivateKey(pk)
if err != nil {
return nil, fmt.Errorf("unable to marshal private key: %w", err)
}
privateKey, err := ssh.ParsePrivateKey(pem.EncodeToMemory(&pem.Block{
Type: "EC PRIVATE KEY",
Headers: nil,
Bytes: buf,
}))
if err != nil {
return nil, fmt.Errorf("unable to parse private key: %w", err)
}
return privateKey, nil
}