63 lines
1.3 KiB
Go
63 lines
1.3 KiB
Go
package certifer
|
|
|
|
import (
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"math/big"
|
|
"math/rand"
|
|
"time"
|
|
)
|
|
|
|
const maxCreateKeyRounds = 3
|
|
|
|
var ecdsacurve = elliptic.P256()
|
|
|
|
// KeyParameters hold the ecdsa curve parameters of private (and public, despite these are redundand values) keys.
|
|
type KeyParameters struct {
|
|
D, X, Y *big.Int
|
|
}
|
|
|
|
// NewKeyParameters extracts key information from a given ecdsa private key and returns a KeyParameters instance.
|
|
func NewKeyParameters(key *ecdsa.PrivateKey) *KeyParameters {
|
|
return &KeyParameters{
|
|
D: key.D,
|
|
X: key.X,
|
|
Y: key.Y,
|
|
}
|
|
}
|
|
|
|
// Key creates a new ecdsa.PrivateKey from the given KeyParameters
|
|
func (k *KeyParameters) Key() *ecdsa.PrivateKey {
|
|
priv := new(ecdsa.PrivateKey)
|
|
priv.PublicKey.Curve = ecdsacurve
|
|
priv.D = k.D
|
|
priv.PublicKey.X, priv.PublicKey.Y = k.X, k.Y
|
|
return priv
|
|
}
|
|
|
|
func createKeyPair() *ecdsa.PrivateKey {
|
|
// generate key pair
|
|
var pk *ecdsa.PrivateKey
|
|
var err error
|
|
for i := 0; i < 3; i++ {
|
|
r := getRandom()
|
|
pk, err = ecdsa.GenerateKey(ecdsacurve, r)
|
|
if err != nil {
|
|
//log.WithError(err).Error("cannot create key pair")
|
|
continue
|
|
}
|
|
return pk
|
|
}
|
|
panic(err)
|
|
}
|
|
|
|
var theRand *rand.Rand = nil
|
|
|
|
func getRandom() *rand.Rand {
|
|
if theRand == nil {
|
|
rnd := rand.NewSource(time.Now().Unix())
|
|
theRand = rand.New(rnd)
|
|
}
|
|
return theRand
|
|
}
|