本文整理匯總了Golang中crypto/ecdsa.GenerateKey函數的典型用法代碼示例。如果您正苦於以下問題:Golang GenerateKey函數的具體用法?Golang GenerateKey怎麽用?Golang GenerateKey使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了GenerateKey函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: GenerateSigningTestKey
func GenerateSigningTestKey(sigAlg SignatureAlgorithm) (sig, ver interface{}) {
switch sigAlg {
case RS256, RS384, RS512, PS256, PS384, PS512:
sig = rsaTestKey
ver = &rsaTestKey.PublicKey
case HS256, HS384, HS512:
sig, _, _ = randomKeyGenerator{size: 16}.genKey()
ver = sig
case ES256:
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
sig = key
ver = &key.PublicKey
case ES384:
key, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
sig = key
ver = &key.PublicKey
case ES512:
key, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
sig = key
ver = &key.PublicKey
default:
panic("Must update test case")
}
return
}
示例2: init
func init() {
raw256, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
ecdsaKey, _ = NewSignerFromKey(raw256)
raw384, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
ecdsa384Key, _ = NewSignerFromKey(raw384)
raw521, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
ecdsa521Key, _ = NewSignerFromKey(raw521)
// Create a cert and sign it for use in tests.
testCert := &OpenSSHCertV01{
Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil
Key: ecdsaKey.PublicKey(),
ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage
ValidAfter: 0, // unix epoch
ValidBefore: maxUint64, // The end of currently representable time.
Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil
SignatureKey: rsaKey.PublicKey(),
}
sigBytes, _ := rsaKey.Sign(rand.Reader, testCert.BytesForSigning())
testCert.Signature = &signature{
Format: testCert.SignatureKey.PublicKeyAlgo(),
Blob: sigBytes,
}
testCertKey = &testSigner{
Signer: ecdsaKey,
pub: testCert,
}
}
示例3: TestBadPubs
func TestBadPubs(t *testing.T) {
priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
t.Fatalf("%v", err)
}
bad1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("%v", err)
}
bad2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("%v", err)
}
bad2.Curve = elliptic.P521()
var bad3 *ecdsa.PublicKey
if _, err = ECDH(priv, bad3); err == nil {
t.Fatalf("ECDH should fail with nil key")
} else if _, err = ECDH(priv, &bad1.PublicKey); err == nil {
t.Fatalf("ECDH should fail with mismatched curve")
} else if _, err = ECDH(priv, &bad2.PublicKey); err == nil {
t.Fatalf("ECDH should fail with wrong curve")
}
}
示例4: TestProcessRequestUserKey
func TestProcessRequestUserKey(t *testing.T) {
server, client := setupHttp(200, "application/json", `{"success":true,"message":"my message"}`)
defer server.Close()
// Create Test Keys
userKey := new(ecdsa.PrivateKey)
userKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
partnerKey := new(ecdsa.PrivateKey)
partnerKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
// Sign User's Public Key (SHA1 Hash) with Partner's Key
userPubkey, _ := x509.MarshalPKIXPublicKey(&userKey.PublicKey)
hash := sha1.New().Sum(userPubkey)
r, s, _ := ecdsa.Sign(rand.Reader, partnerKey, hash)
sigToMarshal := &ecdsaSignature{R: r, S: s}
keySig, _ := asn1.Marshal(sigToMarshal)
userKeyPartner := &NetkiPartner{UserKey: userKey, KeySigningKey: &partnerKey.PublicKey, KeySignature: keySig}
requester := &NetkiRequester{HTTPClient: client}
result, err := requester.ProcessRequest(userKeyPartner, "http://domain.com/uri", "GET", "")
assert.Equal(t, nil, err)
assert.NotEqual(t, nil, result)
}
示例5: GenerateKey
// Generates a compatible OpenSSH private key. The key is in the
// raw Go key format. To convert this to a PEM encoded key, see
// MarshalPrivate.
func GenerateKey(keytype Type, size int) (key interface{}, err error) {
switch keytype {
case KEY_RSA:
if size < 2048 {
return nil, ErrInvalidKeySize
}
var rsakey *rsa.PrivateKey
rsakey, err = rsa.GenerateKey(PRNG, size)
if err != nil {
return
}
key = rsakey
case KEY_ECDSA:
var eckey *ecdsa.PrivateKey
switch size {
case 256:
eckey, err = ecdsa.GenerateKey(elliptic.P256(), PRNG)
case 384:
eckey, err = ecdsa.GenerateKey(elliptic.P384(), PRNG)
case 521:
eckey, err = ecdsa.GenerateKey(elliptic.P521(), PRNG)
default:
return nil, ErrInvalidKeySize
}
key = eckey
case KEY_DSA:
var sizes dsa.ParameterSizes
switch size {
case 1024:
sizes = dsa.L1024N160
case 2048:
sizes = dsa.L2048N256
case 3072:
sizes = dsa.L3072N256
default:
err = ErrInvalidKeySize
return
}
params := dsa.Parameters{}
err = dsa.GenerateParameters(¶ms, rand.Reader, sizes)
if err != nil {
return
}
dsakey := &dsa.PrivateKey{
PublicKey: dsa.PublicKey{
Parameters: params,
},
}
err = dsa.GenerateKey(dsakey, rand.Reader)
if err != nil {
return
}
key = dsakey
}
return
}
示例6: TestGenerateKey
func TestGenerateKey(t *testing.T) {
var err error
alicePriv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("%v", err)
}
bobPriv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("%v", err)
}
}
示例7: TestSetupKeys
func TestSetupKeys(t *testing.T) {
var err error
alice, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
t.Fatalf("%v", err)
}
bob, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
t.Fatalf("%v", err)
}
}
示例8: TestLogCache
func TestLogCache(t *testing.T) {
cache := logCache{
logs: make(map[string]*Log),
}
// Adding a log with an invalid base64 public key should error
_, err := cache.AddLog("www.test.com", "1234")
test.AssertError(t, err, "AddLog() with invalid base64 pk didn't error")
// Adding a log with an invalid URI should error
_, err = cache.AddLog(":", "")
test.AssertError(t, err, "AddLog() with an invalid log URI didn't error")
// Create one keypair & base 64 public key
k1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k1")
der1, err := x509.MarshalPKIXPublicKey(&k1.PublicKey)
test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der1) failed")
k1b64 := base64.StdEncoding.EncodeToString(der1)
// Create a second keypair & base64 public key
k2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
test.AssertNotError(t, err, "ecdsa.GenerateKey() failed for k2")
der2, err := x509.MarshalPKIXPublicKey(&k2.PublicKey)
test.AssertNotError(t, err, "x509.MarshalPKIXPublicKey(der2) failed")
k2b64 := base64.StdEncoding.EncodeToString(der2)
// Adding the first log should not produce an error
l1, err := cache.AddLog("http://log.one.example.com", k1b64)
test.AssertNotError(t, err, "cache.AddLog() failed for log 1")
test.AssertEquals(t, cache.Len(), 1)
test.AssertEquals(t, l1.uri, "http://log.one.example.com")
test.AssertEquals(t, l1.logID, k1b64)
// Adding it again should not produce any errors, or increase the Len()
l1, err = cache.AddLog("http://log.one.example.com", k1b64)
test.AssertNotError(t, err, "cache.AddLog() failed for second add of log 1")
test.AssertEquals(t, cache.Len(), 1)
test.AssertEquals(t, l1.uri, "http://log.one.example.com")
test.AssertEquals(t, l1.logID, k1b64)
// Adding a second log should not error and should increase the Len()
l2, err := cache.AddLog("http://log.two.example.com", k2b64)
test.AssertNotError(t, err, "cache.AddLog() failed for log 2")
test.AssertEquals(t, cache.Len(), 2)
test.AssertEquals(t, l2.uri, "http://log.two.example.com")
test.AssertEquals(t, l2.logID, k2b64)
}
示例9: TestSignWithP384
func TestSignWithP384(t *testing.T) {
message := []byte("Hello, world!")
key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
t.Error(err)
return
}
signature, err := Sign(message, key)
if err != nil {
t.Error(err)
return
}
if !Verify(message, signature, &key.PublicKey) {
t.Error("signature was not correct")
return
}
message[0] ^= 0xff
if Verify(message, signature, &key.PublicKey) {
t.Error("signature was good for altered message")
}
}
示例10: Generate
// Generate generates a key as specified in the request. Currently,
// only ECDSA and RSA are supported.
func (kr *BasicKeyRequest) Generate() (crypto.PrivateKey, error) {
log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo(), kr.Size())
switch kr.Algo() {
case "rsa":
if kr.Size() < 2048 {
return nil, errors.New("RSA key is too weak")
}
if kr.Size() > 8192 {
return nil, errors.New("RSA key size too large")
}
return rsa.GenerateKey(rand.Reader, kr.Size())
case "ecdsa":
var curve elliptic.Curve
switch kr.Size() {
case curveP256:
curve = elliptic.P256()
case curveP384:
curve = elliptic.P384()
case curveP521:
curve = elliptic.P521()
default:
return nil, errors.New("invalid curve")
}
return ecdsa.GenerateKey(curve, rand.Reader)
default:
return nil, errors.New("invalid algorithm")
}
}
示例11: Generate
// Generate generates a key as specified in the request. Currently,
// only ECDSA and RSA are supported.
func (kr *KeyRequest) Generate() (interface{}, error) {
log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo, kr.Size)
switch kr.Algo {
case "rsa":
if kr.Size < 2048 {
return nil, errors.New("RSA key is too weak")
}
return rsa.GenerateKey(rand.Reader, kr.Size)
case "ecdsa":
var curve elliptic.Curve
switch kr.Size {
case curveP256:
curve = elliptic.P256()
case curveP384:
curve = elliptic.P384()
case curveP521:
curve = elliptic.P521()
default:
return nil, errors.New("invalid curve")
}
return ecdsa.GenerateKey(curve, rand.Reader)
default:
return nil, errors.New("invalid algorithm")
}
}
示例12: Cert
// Cert generates a new TLS certificate for hostname and signs it using caPrivKey.
func Cert(t *testing.T, caCert *x509.Certificate, caPrivKey *ecdsa.PrivateKey, hostname string, rnd io.Reader) tls.Certificate {
if rnd == nil {
rnd = rand.Reader
}
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rnd)
if err != nil {
t.Fatal(err)
}
certTemplate := &x509.Certificate{
Subject: pkix.Name{CommonName: hostname},
SerialNumber: newSerial(t, rnd),
NotBefore: time.Now(),
NotAfter: time.Now().Add(1 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
}
if ip := net.ParseIP(hostname); ip != nil {
certTemplate.IPAddresses = []net.IP{ip}
}
certDER, err := x509.CreateCertificate(rnd, certTemplate, caCert, &privKey.PublicKey, caPrivKey)
if err != nil {
t.Fatal(err)
}
cert, err := x509.ParseCertificate(certDER)
if err != nil {
t.Fatal(err)
}
return tls.Certificate{Certificate: [][]byte{certDER}, PrivateKey: privKey, Leaf: cert}
}
示例13: createCAKeyPair
func (ca *CA) createCAKeyPair(name string) *ecdsa.PrivateKey {
caLogger.Debug("Creating CA key pair.")
curve := primitives.GetDefaultCurve()
priv, err := ecdsa.GenerateKey(curve, rand.Reader)
if err == nil {
raw, _ := x509.MarshalECPrivateKey(priv)
cooked := pem.EncodeToMemory(
&pem.Block{
Type: "ECDSA PRIVATE KEY",
Bytes: raw,
})
err = ioutil.WriteFile(ca.path+"/"+name+".priv", cooked, 0644)
if err != nil {
caLogger.Panic(err)
}
raw, _ = x509.MarshalPKIXPublicKey(&priv.PublicKey)
cooked = pem.EncodeToMemory(
&pem.Block{
Type: "ECDSA PUBLIC KEY",
Bytes: raw,
})
err = ioutil.WriteFile(ca.path+"/"+name+".pub", cooked, 0644)
if err != nil {
caLogger.Panic(err)
}
}
if err != nil {
caLogger.Panic(err)
}
return priv
}
示例14: newPrincipalKey
// newPrincipalKey generates an ECDSA (public, private) key pair.
func newPrincipalKey() (publicKey, *ecdsa.PrivateKey, error) {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, err
}
return newECDSAPublicKey(&priv.PublicKey), priv, nil
}
示例15: GeneratePrivateKey
// GeneratePrivateKey is a wrapper for ecdsa.GenerateKey that returns a PrivateKey
// instead of the normal ecdsa.PrivateKey.
func GeneratePrivateKey(curve *KoblitzCurve) (*PrivateKey, error) {
key, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return nil, err
}
return (*PrivateKey)(key), nil
}