2020-10-02 03:30:26 +00:00
|
|
|
package keypairs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
|
|
|
"crypto/elliptic"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"io"
|
|
|
|
mathrand "math/rand"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var randReader io.Reader = rand.Reader
|
2020-10-02 08:44:26 +00:00
|
|
|
var allowMocking = false
|
2020-10-02 03:30:26 +00:00
|
|
|
|
|
|
|
// KeyOptions are the things that we may need to know about a request to fulfill it properly
|
|
|
|
type keyOptions struct {
|
|
|
|
//Key string `json:"key"`
|
2020-10-02 08:44:26 +00:00
|
|
|
KeyType string `json:"kty"`
|
|
|
|
mockSeed int64 //`json:"-"`
|
2020-10-02 03:30:26 +00:00
|
|
|
//SeedStr string `json:"seed"`
|
|
|
|
//Claims Object `json:"claims"`
|
|
|
|
//Header Object `json:"header"`
|
|
|
|
}
|
|
|
|
|
2020-10-02 08:44:26 +00:00
|
|
|
func (o *keyOptions) nextReader() io.Reader {
|
|
|
|
if allowMocking {
|
|
|
|
return o.maybeMockReader()
|
|
|
|
}
|
2020-10-02 03:30:26 +00:00
|
|
|
return randReader
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewDefaultPrivateKey generates a key with reasonable strength.
|
|
|
|
// Today that means a 256-bit equivalent - either RSA 2048 or EC P-256.
|
|
|
|
func NewDefaultPrivateKey() PrivateKey {
|
2020-10-02 08:44:26 +00:00
|
|
|
// insecure random is okay here,
|
|
|
|
// it's just used for a coin toss
|
2020-10-02 03:30:26 +00:00
|
|
|
mathrand.Seed(time.Now().UnixNano())
|
|
|
|
coin := mathrand.Int()
|
2020-10-02 08:44:26 +00:00
|
|
|
|
|
|
|
// the idea here is that we want to make
|
|
|
|
// it dead simple to support RSA and EC
|
|
|
|
// so it shouldn't matter which is used
|
2020-10-02 03:30:26 +00:00
|
|
|
if 0 == coin%2 {
|
|
|
|
return newPrivateKey(&keyOptions{
|
|
|
|
KeyType: "RSA",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return newPrivateKey(&keyOptions{
|
|
|
|
KeyType: "EC",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// newPrivateKey generates a 256-bit entropy RSA or ECDSA private key
|
|
|
|
func newPrivateKey(opts *keyOptions) PrivateKey {
|
|
|
|
var privkey PrivateKey
|
|
|
|
|
|
|
|
if "RSA" == opts.KeyType {
|
|
|
|
keylen := 2048
|
2020-10-02 08:44:26 +00:00
|
|
|
privkey, _ = rsa.GenerateKey(opts.nextReader(), keylen)
|
|
|
|
if allowMocking {
|
|
|
|
privkey = maybeDerandomizeMockKey(privkey, keylen, opts)
|
|
|
|
}
|
2020-10-02 03:30:26 +00:00
|
|
|
} else {
|
|
|
|
// TODO: EC keys may also suffer the same random problems in the future
|
2020-10-02 08:44:26 +00:00
|
|
|
privkey, _ = ecdsa.GenerateKey(elliptic.P256(), opts.nextReader())
|
2020-10-02 03:30:26 +00:00
|
|
|
}
|
|
|
|
return privkey
|
|
|
|
}
|