2017-05-02 23:33:51 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/x509"
|
|
|
|
"encoding/pem"
|
|
|
|
"io/ioutil"
|
2017-08-14 15:43:33 +00:00
|
|
|
"errors"
|
|
|
|
"crypto/rand"
|
2017-05-02 23:33:51 +00:00
|
|
|
)
|
|
|
|
|
2017-07-04 18:29:11 +00:00
|
|
|
const (
|
|
|
|
InvalidPrivateKeyFileError = Error("InvalidPrivateKeyFileError")
|
2017-08-14 15:43:33 +00:00
|
|
|
RICOCHET_KEY_SIZE = 1024
|
2017-07-04 18:29:11 +00:00
|
|
|
)
|
|
|
|
|
2017-08-14 15:43:33 +00:00
|
|
|
// Generate a private key for use
|
|
|
|
func GeneratePrivateKey() (*rsa.PrivateKey, error) {
|
|
|
|
privateKey, err := rsa.GenerateKey(rand.Reader, RICOCHET_KEY_SIZE)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.New("Could not generate key: " + err.Error())
|
|
|
|
}
|
|
|
|
privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey)
|
|
|
|
return x509.ParsePKCS1PrivateKey(privateKeyDer)
|
|
|
|
}
|
|
|
|
|
2017-05-02 23:33:51 +00:00
|
|
|
// LoadPrivateKeyFromFile loads a private key from a file...
|
|
|
|
func LoadPrivateKeyFromFile(filename string) (*rsa.PrivateKey, error) {
|
|
|
|
pemData, err := ioutil.ReadFile(filename)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2017-08-14 15:43:33 +00:00
|
|
|
return ParsePrivateKey(pemData)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Convert a private key string to a usable private key
|
|
|
|
func ParsePrivateKey(pemData []byte) (*rsa.PrivateKey, error) {
|
2017-05-02 23:33:51 +00:00
|
|
|
block, _ := pem.Decode(pemData)
|
|
|
|
if block == nil || block.Type != "RSA PRIVATE KEY" {
|
2017-07-04 18:29:11 +00:00
|
|
|
return nil, InvalidPrivateKeyFileError
|
2017-05-02 23:33:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return x509.ParsePKCS1PrivateKey(block.Bytes)
|
|
|
|
}
|
2017-08-14 15:43:33 +00:00
|
|
|
|
|
|
|
// turn a private key into storable string
|
|
|
|
func PrivateKeyToString(privateKey *rsa.PrivateKey) string {
|
|
|
|
privateKeyBlock := pem.Block{
|
|
|
|
Type: "RSA PRIVATE KEY",
|
|
|
|
Headers: nil,
|
|
|
|
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(pem.EncodeToMemory(&privateKeyBlock))
|
|
|
|
}
|