woodpecker/pkg/utils/sshutil/sshutil.go

40 lines
1,008 B
Go
Raw Normal View History

2014-06-04 21:25:38 +00:00
package sshutil
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"code.google.com/p/go.crypto/ssh"
)
const (
RSA_BITS = 2048 // Default number of bits in an RSA key
RSA_BITS_MIN = 768 // Minimum number of bits in an RSA key
)
// helper function to generate an RSA Private Key.
func GeneratePrivateKey() (*rsa.PrivateKey, error) {
return rsa.GenerateKey(rand.Reader, RSA_BITS)
}
// helper function that marshalls an RSA Public Key to an SSH
// .authorized_keys format
2015-05-17 00:46:29 +00:00
func MarshalPublicKey(pubkey *rsa.PublicKey) []byte {
2014-06-04 21:25:38 +00:00
pk, err := ssh.NewPublicKey(pubkey)
if err != nil {
2015-05-17 00:46:29 +00:00
return []byte{}
2014-06-04 21:25:38 +00:00
}
2015-05-17 00:46:29 +00:00
return ssh.MarshalAuthorizedKey(pk)
2014-06-04 21:25:38 +00:00
}
// helper function that marshalls an RSA Private Key to
// a PEM encoded file.
2015-05-17 00:46:29 +00:00
func MarshalPrivateKey(privkey *rsa.PrivateKey) []byte {
2014-06-04 21:25:38 +00:00
privateKeyMarshaled := x509.MarshalPKCS1PrivateKey(privkey)
privateKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Headers: nil, Bytes: privateKeyMarshaled})
2015-05-17 00:46:29 +00:00
return privateKeyPEM
2014-06-04 21:25:38 +00:00
}