2014-06-05 00:25:38 +03:00
|
|
|
package sshutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/x509"
|
2015-08-14 04:37:29 +02:00
|
|
|
"encoding/base64"
|
2014-06-05 00:25:38 +03:00
|
|
|
"encoding/pem"
|
2015-08-14 04:37:29 +02:00
|
|
|
"hash"
|
2014-06-05 00:25:38 +03:00
|
|
|
|
2015-05-22 20:37:40 +02:00
|
|
|
"github.com/drone/drone/Godeps/_workspace/src/code.google.com/p/go.crypto/ssh"
|
2014-06-05 00:25:38 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
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 02:46:29 +02:00
|
|
|
func MarshalPublicKey(pubkey *rsa.PublicKey) []byte {
|
2014-06-05 00:25:38 +03:00
|
|
|
pk, err := ssh.NewPublicKey(pubkey)
|
|
|
|
if err != nil {
|
2015-05-17 02:46:29 +02:00
|
|
|
return []byte{}
|
2014-06-05 00:25:38 +03:00
|
|
|
}
|
|
|
|
|
2015-05-17 02:46:29 +02:00
|
|
|
return ssh.MarshalAuthorizedKey(pk)
|
2014-06-05 00:25:38 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// helper function that marshalls an RSA Private Key to
|
|
|
|
// a PEM encoded file.
|
2015-05-17 02:46:29 +02:00
|
|
|
func MarshalPrivateKey(privkey *rsa.PrivateKey) []byte {
|
2014-06-05 00:25:38 +03:00
|
|
|
privateKeyMarshaled := x509.MarshalPKCS1PrivateKey(privkey)
|
|
|
|
privateKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Headers: nil, Bytes: privateKeyMarshaled})
|
2015-05-17 02:46:29 +02:00
|
|
|
return privateKeyPEM
|
2014-06-05 00:25:38 +03:00
|
|
|
}
|
2015-08-04 19:55:27 +02:00
|
|
|
|
2015-08-14 04:37:29 +02:00
|
|
|
// Encrypt is helper function to encrypt a plain-text string using
|
2015-08-04 19:55:27 +02:00
|
|
|
// an RSA public key.
|
2015-08-14 04:37:29 +02:00
|
|
|
func Encrypt(hash hash.Hash, pubkey *rsa.PublicKey, msg string) (string, error) {
|
|
|
|
src, err := rsa.EncryptOAEP(hash, rand.Reader, pubkey, []byte(msg), nil)
|
|
|
|
|
|
|
|
return base64.StdEncoding.EncodeToString(src), err
|
2015-08-04 19:55:27 +02:00
|
|
|
}
|
|
|
|
|
2015-08-14 04:37:29 +02:00
|
|
|
// Decrypt is helper function to encrypt a plain-text string using
|
2015-08-04 19:55:27 +02:00
|
|
|
// an RSA public key.
|
2015-08-14 04:37:29 +02:00
|
|
|
func Decrypt(hash hash.Hash, privkey *rsa.PrivateKey, secret string) (string, error) {
|
|
|
|
decoded, err := base64.StdEncoding.DecodeString(secret)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
out, err := rsa.DecryptOAEP(hash, rand.Reader, privkey, decoded, nil)
|
|
|
|
|
|
|
|
return string(out), err
|
2015-08-04 19:55:27 +02:00
|
|
|
}
|