mirror of
https://github.com/apricote/hcloud-upload-image.git
synced 2026-01-13 21:31:03 +00:00
feat: initial library code
This commit is contained in:
parent
b331ddba81
commit
4f57df5b66
10 changed files with 575 additions and 0 deletions
45
util/sshkey/ssh_key.go
Normal file
45
util/sshkey/ssh_key.go
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
package sshkey
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"encoding/pem"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
func GenerateKeyPair() ([]byte, []byte, error) {
|
||||
pub, priv, err := ed25519.GenerateKey(nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
pubBytes, err := encodePublicKey(pub)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
privBytes, err := encodePrivateKey(priv)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return pubBytes, privBytes, nil
|
||||
}
|
||||
|
||||
func encodePublicKey(pub ed25519.PublicKey) ([]byte, error) {
|
||||
sshPub, err := ssh.NewPublicKey(pub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ssh.MarshalAuthorizedKey(sshPub), nil
|
||||
}
|
||||
|
||||
func encodePrivateKey(priv ed25519.PrivateKey) ([]byte, error) {
|
||||
privPem, err := ssh.MarshalPrivateKey(priv, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pem.EncodeToMemory(privPem), nil
|
||||
}
|
||||
25
util/sshkey/ssh_key_test.go
Normal file
25
util/sshkey/ssh_key_test.go
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
package sshkey
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGenerateSSHKeyPair(t *testing.T) {
|
||||
pubBytes, privBytes, err := GenerateKeyPair()
|
||||
assert.Nil(t, err)
|
||||
|
||||
pub := string(pubBytes)
|
||||
priv := string(privBytes)
|
||||
|
||||
if !(strings.HasPrefix(priv, "-----BEGIN OPENSSH PRIVATE KEY-----\n") &&
|
||||
strings.HasSuffix(priv, "-----END OPENSSH PRIVATE KEY-----\n")) {
|
||||
assert.Fail(t, "private key is invalid", priv)
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(pub, "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA") {
|
||||
assert.Fail(t, "public key is invalid", pub)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue