Skip to content

Commit 437322c

Browse files
committed
feat: 新增生成SSHKey接口
1 parent 26dbce5 commit 437322c

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

api/keypair/keygen.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package keypair
2+
3+
import (
4+
"github.com/gin-gonic/gin"
5+
6+
"tdp-cloud/helper/secure"
7+
)
8+
9+
func keygen(c *gin.Context) {
10+
11+
var rq struct {
12+
KeyType string
13+
}
14+
15+
if err := c.ShouldBind(&rq); err != nil {
16+
c.Set("Error", err)
17+
return
18+
}
19+
20+
var (
21+
err error
22+
privateKey, publicKey string
23+
)
24+
25+
switch rq.KeyType {
26+
case "ssh":
27+
privateKey, publicKey, err = secure.NewSSHKeypair()
28+
}
29+
30+
if err == nil {
31+
c.Set("Payload", gin.H{"PrivateKey": privateKey, "PublicKey": publicKey})
32+
} else {
33+
c.Set("Error", err)
34+
}
35+
36+
}

api/keypair/router.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ func Router(api *gin.RouterGroup) {
1818
rg.POST("/detail", detail)
1919
rg.POST("/update", update)
2020
rg.POST("/delete", delete)
21+
22+
rg.POST("/keygen", keygen)
2123
}
2224

2325
}

helper/secure/ssh.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package secure
2+
3+
import (
4+
"crypto/rand"
5+
"crypto/rsa"
6+
"crypto/x509"
7+
"encoding/pem"
8+
9+
"golang.org/x/crypto/ssh"
10+
)
11+
12+
func NewSSHKeypair() (string, string, error) {
13+
14+
privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
15+
if err != nil {
16+
return "", "", err
17+
}
18+
19+
privateKeyBytes := pem.EncodeToMemory(&pem.Block{
20+
Type: "RSA PRIVATE KEY",
21+
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
22+
})
23+
24+
publicKeyBytes, err := NewSSHPublicKey(&privateKey.PublicKey)
25+
if err != nil {
26+
return "", "", err
27+
}
28+
29+
return string(privateKeyBytes), string(publicKeyBytes), nil
30+
31+
}
32+
33+
func NewSSHPublicKey(privatekey *rsa.PublicKey) ([]byte, error) {
34+
35+
publicKey, err := ssh.NewPublicKey(privatekey)
36+
if err != nil {
37+
return nil, err
38+
}
39+
40+
publicKeyBytes := ssh.MarshalAuthorizedKey(publicKey)
41+
42+
return publicKeyBytes, nil
43+
44+
}

0 commit comments

Comments
 (0)