2015-06-08 02:36:07 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2016-01-27 03:01:39 +02:00
|
|
|
"crypto"
|
|
|
|
"crypto/ecdsa"
|
|
|
|
"crypto/elliptic"
|
2015-06-08 02:36:07 +02:00
|
|
|
"crypto/rand"
|
|
|
|
"crypto/x509"
|
|
|
|
"encoding/pem"
|
2016-01-27 03:01:39 +02:00
|
|
|
"errors"
|
2015-06-08 02:36:07 +02:00
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2016-01-27 03:01:39 +02:00
|
|
|
func generatePrivateKey(file string) (crypto.PrivateKey, error) {
|
|
|
|
|
|
|
|
privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
keyBytes, err := x509.MarshalECPrivateKey(privateKey)
|
2015-06-08 02:36:07 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2016-01-27 03:01:39 +02:00
|
|
|
pemKey := pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}
|
2015-06-08 02:36:07 +02:00
|
|
|
|
|
|
|
certOut, err := os.Create(file)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
pem.Encode(certOut, &pemKey)
|
|
|
|
certOut.Close()
|
|
|
|
|
|
|
|
return privateKey, nil
|
|
|
|
}
|
|
|
|
|
2016-01-27 03:01:39 +02:00
|
|
|
func loadPrivateKey(file string) (crypto.PrivateKey, error) {
|
2015-06-08 02:36:07 +02:00
|
|
|
keyBytes, err := ioutil.ReadFile(file)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
keyBlock, _ := pem.Decode(keyBytes)
|
2016-01-27 03:01:39 +02:00
|
|
|
|
|
|
|
switch keyBlock.Type {
|
|
|
|
case "RSA PRIVATE KEY":
|
2016-02-06 23:41:29 +02:00
|
|
|
return x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
|
2016-01-27 03:01:39 +02:00
|
|
|
case "EC PRIVATE KEY":
|
|
|
|
return x509.ParseECPrivateKey(keyBlock.Bytes)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, errors.New("Unknown private key type.")
|
2015-06-08 02:36:07 +02:00
|
|
|
}
|