• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang rsa.GenerateKey函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中crypto/rsa.GenerateKey函数的典型用法代码示例。如果您正苦于以下问题:Golang GenerateKey函数的具体用法?Golang GenerateKey怎么用?Golang GenerateKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了GenerateKey函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestSecret

func TestSecret(t *testing.T) {
	iniKey, _ := rsa.GenerateKey(rand.Reader, 1024)
	accKey, _ := rsa.GenerateKey(rand.Reader, 1024)

	for i, tt := range stsTests {
		iniSes, _ := New(bytes.NewReader(tt.iniExponent.Bytes()), tt.group, tt.generator, tt.cipher, tt.bits, tt.hash)
		accSes, _ := New(bytes.NewReader(tt.accExponent.Bytes()), tt.group, tt.generator, tt.cipher, tt.bits, tt.hash)
		iniExp, _ := iniSes.Initiate()
		accExp, accToken, _ := accSes.Accept(rand.Reader, accKey, iniExp)
		iniToken, _ := iniSes.Verify(rand.Reader, iniKey, &accKey.PublicKey, accExp, accToken)
		accSes.Finalize(&iniKey.PublicKey, iniToken)

		iniSecret, err := iniSes.Secret()
		if err != nil {
			t.Errorf("test %d: failed to retrieve initiator's secret: %v", i, err)
		} else {
			accSecret, err := accSes.Secret()
			if err != nil {
				t.Errorf("test %d: failed to retrieve acceptor's secret: %v", i, err)
			} else {
				if !bytes.Equal(iniSecret, accSecret) {
					t.Errorf("test %d: secret mismatch: initiator %v, acceptor %v", i, iniSecret, accSecret)
				}
			}
		}
	}
}
开发者ID:ibmendoza,项目名称:iris-0.3.2,代码行数:27,代码来源:sts_test.go


示例2: TestGetNotUnique

func (gkms *gpgKeypairMgrSuite) TestGetNotUnique(c *C) {
	mockGPG := func(prev asserts.GPGRunner, input []byte, args ...string) ([]byte, error) {
		if args[1] == "--list-secret-keys" {
			return prev(input, args...)
		}
		c.Assert(args[1], Equals, "--export")

		pk1, err := rsa.GenerateKey(rand.Reader, 512)
		c.Assert(err, IsNil)
		pk2, err := rsa.GenerateKey(rand.Reader, 512)
		c.Assert(err, IsNil)

		buf := new(bytes.Buffer)
		err = packet.NewRSAPublicKey(time.Now(), &pk1.PublicKey).Serialize(buf)
		c.Assert(err, IsNil)
		err = packet.NewRSAPublicKey(time.Now(), &pk2.PublicKey).Serialize(buf)
		c.Assert(err, IsNil)

		return buf.Bytes(), nil
	}
	restore := asserts.MockRunGPG(mockGPG)
	defer restore()

	_, err := gkms.keypairMgr.Get(assertstest.DevKeyID)
	c.Check(err, ErrorMatches, `cannot load GPG public key with fingerprint "[A-F0-9]+": cannot select exported public key, found many`)
}
开发者ID:niemeyer,项目名称:snapd,代码行数:26,代码来源:gpgkeypairmgr_test.go


示例3: Example_usage

// Full STS communication example illustrated with two concurrent Go routines agreeing on a master key.
func Example_usage() {
	// STS cyclic group parameters, global for the app (small examples, not secure!)
	group := big.NewInt(3910779947)
	generator := big.NewInt(1213725007)

	// STS encryption parameters
	cipher := aes.NewCipher
	bits := 128
	hash := crypto.SHA1

	// RSA key-pairs for the communicating parties, obtained from somewhere else (no error checks)
	iniKey, _ := rsa.GenerateKey(rand.Reader, 1024)
	accKey, _ := rsa.GenerateKey(rand.Reader, 1024)

	// Start two Go routines: one initiator and one acceptor communicating on a channel
	transport := make(chan []byte)
	iniOut := make(chan []byte)
	accOut := make(chan []byte)

	go initiator(group, generator, cipher, bits, hash, iniKey, &accKey.PublicKey, transport, iniOut)
	go acceptor(group, generator, cipher, bits, hash, accKey, &iniKey.PublicKey, transport, accOut)

	// Check that the parties agreed upon the same master key
	iniMaster, iniOk := <-iniOut
	accMaster, accOk := <-accOut

	fmt.Printf("Initiator key valid: %v\n", iniOk && iniMaster != nil)
	fmt.Printf("Acceptor key valid: %v\n", accOk && accMaster != nil)
	fmt.Printf("Keys match: %v\n", bytes.Equal(iniMaster, accMaster))

	// Output:
	// Initiator key valid: true
	// Acceptor key valid: true
	// Keys match: true
}
开发者ID:ibmendoza,项目名称:iris-0.3.2,代码行数:36,代码来源:example_test.go


示例4: main

func main() {
	// Instantiate the PKCS11 key
	var pkcs11 struct {
		Module string
		Token  string
		PIN    string
		Label  string
	}
	pkcs11Bytes, err := ioutil.ReadFile(pkcs11FileName)
	panicOnError(err)
	err = json.Unmarshal(pkcs11Bytes, &pkcs11)
	panicOnError(err)
	p11key, err := pkcs11key.New(pkcs11.Module, pkcs11.Token, pkcs11.PIN, pkcs11.Label)
	panicOnError(err)

	// All of the certificates start and end at the same time
	notBefore := time.Now().Truncate(time.Hour).Add(-1 * time.Hour)
	notAfter := notBefore.AddDate(1, 0, 0)

	// Make some keys for the CA and EE
	caKey, err := rsa.GenerateKey(rand.Reader, 2048)
	panicOnError(err)
	eeKey, err := rsa.GenerateKey(rand.Reader, 2048)
	panicOnError(err)

	// Make CA cert with ephemeral key
	template := &x509.Certificate{
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		Subject:               pkix.Name{CommonName: "Happy Hacker Fake CA"},
		BasicConstraintsValid: true,
		IsCA: true,
	}
	caCert := makeCert(template, template, caKey.Public(), caKey)

	// Make EE cert with ephemeral key and print
	template = &x509.Certificate{
		NotBefore: notBefore,
		NotAfter:  notAfter,
		Subject:   pkix.Name{CommonName: "example.com"},
	}
	eeCert := makeCert(template, caCert, eeKey.Public(), caKey)

	// Make OCSP responder cert with PKCS#11 key
	template = &x509.Certificate{
		NotBefore:   notBefore,
		NotAfter:    notAfter,
		Subject:     pkix.Name{CommonName: "Happy Hacker OCSP Signer"},
		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageOCSPSigning},
	}
	ocspCert := makeCert(template, caCert, p11key.Public(), caKey)

	// Write out all the certs in DER and PEM
	ioutil.WriteFile(caCertFileName, caCert.Raw, 0666)
	ioutil.WriteFile(eeCertFileName, eeCert.Raw, 0666)
	ioutil.WriteFile(ocspCertFileName, ocspCert.Raw, 0666)
	ioutil.WriteFile(caCertFileNamePEM, toPEM(caCert), 0666)
	ioutil.WriteFile(eeCertFileNamePEM, toPEM(eeCert), 0666)
	ioutil.WriteFile(ocspCertFileNamePEM, toPEM(ocspCert), 0666)
}
开发者ID:josephyzhou,项目名称:boulder,代码行数:60,代码来源:gentest.go


示例5: TestToken

func TestToken(t *testing.T) {
	iniKey, _ := rsa.GenerateKey(rand.Reader, 1024)
	accKey, _ := rsa.GenerateKey(rand.Reader, 1024)

	for i, tt := range stsTests {
		iniSes, _ := New(bytes.NewReader(tt.iniExponent.Bytes()), tt.group, tt.generator, tt.cipher, tt.bits, tt.hash)
		accSes, _ := New(bytes.NewReader(tt.accExponent.Bytes()), tt.group, tt.generator, tt.cipher, tt.bits, tt.hash)
		iniExp, _ := iniSes.Initiate()

		accExp, accToken, err := accSes.Accept(rand.Reader, accKey, iniExp)
		if err != nil {
			t.Errorf("test %d: failed to accept incoming exchange: %v", i, err)
		} else if tt.accExponential.Cmp(accExp) != 0 {
			t.Errorf("test %d: exponential mismatch: have %v, want %v", i, accExp, tt.accExponential)
		} else {
			iniToken, err := iniSes.Verify(rand.Reader, iniKey, &accKey.PublicKey, accExp, accToken)
			if err != nil {
				t.Errorf("test %d: failed to verify auth token: %v", i, err)
			} else {
				err := accSes.Finalize(&iniKey.PublicKey, iniToken)
				if err != nil {
					t.Errorf("test %d: failed to finalize key exchange: %v", i, err)
				}
			}
		}
	}
}
开发者ID:ibmendoza,项目名称:iris-0.3.2,代码行数:27,代码来源:sts_test.go


示例6: GenerateCerts

func (c *Cert) GenerateCerts(domain string) ([]byte, []byte, []byte, []byte, error) {
	caPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	encodedCAPrivateKey := new(bytes.Buffer)
	if err := pem.Encode(encodedCAPrivateKey, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(caPrivateKey)}); err != nil {
		return nil, nil, nil, nil, err
	}

	caTemplate := c.generateTemplate(domain, true)
	encodedCACertificate, err := c.generateCert(caTemplate, caTemplate, &caPrivateKey.PublicKey, caPrivateKey)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	encodedPrivateKey := new(bytes.Buffer)
	if err := pem.Encode(encodedPrivateKey, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}); err != nil {
		return nil, nil, nil, nil, err
	}

	template := c.generateTemplate(domain, false)
	encodedCertificate, err := c.generateCert(template, caTemplate, &privateKey.PublicKey, caPrivateKey)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	return encodedCertificate, encodedPrivateKey.Bytes(), encodedCACertificate, encodedCAPrivateKey.Bytes(), nil
}
开发者ID:pivotal-cf,项目名称:pcfdev,代码行数:33,代码来源:cert.go


示例7: TestGenerateCertFromKeys

// Test GenerateCert from Keys
func TestGenerateCertFromKeys(t *testing.T) {
	var notBefore time.Time
	notBefore = time.Now()
	validFor := 365 * 24 * time.Hour
	notAfter := notBefore.Add(validFor)

	signingKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal("Can't generate signing key\n")
	}
	derSignerCert, err := GenerateSelfSignedCertFromKey(signingKey, "Cloudproxy Authority",
		"Application Policy Key", GetSerialNumber(), notBefore, notAfter)
	if err != nil {
		t.Fatal("Can't generate signer key\n")
	}
	fmt.Printf("SigningKey: %x\n", signingKey)

	signedKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal("Can't generate privatekey\n")
	}
	newPublic := PublicKeyFromPrivate(signedKey)
	if newPublic == nil {
		t.Fatal("Can't generate privatekey\n")
	}
	cert, err := GenerateCertFromKeys(signingKey, derSignerCert, newPublic,
		"TestKey", "CommonTestKey", GetSerialNumber(),
		notBefore, notAfter)
	if err != nil {
		t.Fatal("Can't generate cert\n")
	}
	fmt.Printf("cert: %x\n", cert)
}
开发者ID:tmroeder,项目名称:cloudproxy,代码行数:34,代码来源:support_test.go


示例8: TestSignCertificate

func TestSignCertificate(t *testing.T) {
	var notBefore time.Time
	notBefore = time.Now()
	validFor := 365 * 24 * time.Hour
	notAfter := notBefore.Add(validFor)

	// Generate Policy Key.
	privatePolicyKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal("Can't generate privatekey\n")
	}

	derPolicyCert, err := GenerateSelfSignedCertFromKey(privatePolicyKey, "PolicyKey",
		"PolicyKey", GetSerialNumber(), notBefore, notAfter)
	if err != nil {
		t.Fatal("Can't parse program certificate ", err, "\n")
	}

	// Generate Program Key.
	privateProgramKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal("Can't generate program privatekey\n")
	}
	derProgramCert, err := GenerateCertFromKeys(privatePolicyKey,
		derPolicyCert, &privateProgramKey.PublicKey,
		"JLM", "Test-program", GetSerialNumber(), notBefore, notAfter)
	if err != nil {
		t.Fatal("Can't generate cert\n")
	}
	ok, err := VerifyDerCert(derProgramCert, derPolicyCert)
	if !ok || err != nil {
		t.Fatal("Can't verify certificate ", err, "\n")
	}
}
开发者ID:tmroeder,项目名称:cloudproxy,代码行数:34,代码来源:support_test.go


示例9: main

func main() {
	in, err := discover.Discover(net.FlagMulticast)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Interface:", in)

	MasterKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal(err)
	}
	SlaveKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal(err)
	}

	Keys := discover.NewPubKeys()
	Keys.Put("slave", &SlaveKey.PublicKey)

	server := &discover.Server{}
	server.Name = "master"
	server.PrivateKey = MasterKey
	server.PubKeys = Keys
	server.Interface = in
	server.AddrVer = discover.Ipv4
	server.Port = "3333"
	server.Protocol = func(addr *net.UDPAddr, req *discover.Request) (resp *discover.Response, err error) {
		if string(req.Data) != "request" {
			return nil, e.New("protocol error")
		}
		return &discover.Response{
			Data: []byte("msg"),
		}, nil
	}
	err = server.Do()
	if err != nil {
		log.Fatal(err)
	}
	defer server.Close()

	client := &discover.Client{}
	client.ServerName = "master"
	client.ServerKey = &MasterKey.PublicKey
	client.Name = "slave"
	client.PrivateKey = SlaveKey
	client.Interface = in
	client.AddrVer = discover.Ipv4
	client.Port = "3333"
	client.Request = func(dst *net.UDPAddr) (*discover.Request, error) {
		return &discover.Request{
			Data: []byte("request"),
		}, nil
	}
	resp, err := client.Discover()
	if err != nil {
		log.Fatal(err)
	}
	log.Println(resp)
}
开发者ID:fcavani,项目名称:discover,代码行数:59,代码来源:example.go


示例10: NewEntity

// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
// single identity composed of the given full name, comment and email, any of
// which may be empty but must not contain any of "()<>\x00".
// If config is nil, sensible defaults will be used.
func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
	currentTime := config.Now()

	uid := packet.NewUserId(name, comment, email)
	if uid == nil {
		return nil, errors.InvalidArgumentError("user id field contained invalid characters")
	}
	signingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
	if err != nil {
		return nil, err
	}
	encryptingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
	if err != nil {
		return nil, err
	}

	e := &Entity{
		PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey),
		PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv),
		Identities: make(map[string]*Identity),
	}
	isPrimaryId := true
	e.Identities[uid.Id] = &Identity{
		Name:   uid.Name,
		UserId: uid,
		SelfSignature: &packet.Signature{
			CreationTime: currentTime,
			SigType:      packet.SigTypePositiveCert,
			PubKeyAlgo:   packet.PubKeyAlgoRSA,
			Hash:         config.Hash(),
			IsPrimaryId:  &isPrimaryId,
			FlagsValid:   true,
			FlagSign:     true,
			FlagCertify:  true,
			IssuerKeyId:  &e.PrimaryKey.KeyId,
		},
	}

	e.Subkeys = make([]Subkey, 1)
	e.Subkeys[0] = Subkey{
		PublicKey:  packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey),
		PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv),
		Sig: &packet.Signature{
			CreationTime:              currentTime,
			SigType:                   packet.SigTypeSubkeyBinding,
			PubKeyAlgo:                packet.PubKeyAlgoRSA,
			Hash:                      config.Hash(),
			FlagsValid:                true,
			FlagEncryptStorage:        true,
			FlagEncryptCommunications: true,
			IssuerKeyId:               &e.PrimaryKey.KeyId,
		},
	}
	e.Subkeys[0].PublicKey.IsSubkey = true
	e.Subkeys[0].PrivateKey.IsSubkey = true

	return e, nil
}
开发者ID:postfix,项目名称:name_pending,代码行数:62,代码来源:keys.go


示例11: NewEntity

// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
// single identity composed of the given full name, comment and email, any of
// which may be empty but must not contain any of "()<>\x00".
func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email string) (*Entity, os.Error) {
	uid := packet.NewUserId(name, comment, email)
	if uid == nil {
		return nil, error.InvalidArgumentError("user id field contained invalid characters")
	}
	signingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits)
	if err != nil {
		return nil, err
	}
	encryptingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits)
	if err != nil {
		return nil, err
	}

	t := uint32(currentTimeSecs)

	e := &Entity{
		PrimaryKey: packet.NewRSAPublicKey(t, &signingPriv.PublicKey, false /* not a subkey */),
		PrivateKey: packet.NewRSAPrivateKey(t, signingPriv, false /* not a subkey */),
		Identities: make(map[string]*Identity),
	}
	isPrimaryId := true
	e.Identities[uid.Id] = &Identity{
		Name:   uid.Name,
		UserId: uid,
		SelfSignature: &packet.Signature{
			CreationTime: t,
			SigType:      packet.SigTypePositiveCert,
			PubKeyAlgo:   packet.PubKeyAlgoRSA,
			Hash:         crypto.SHA256,
			IsPrimaryId:  &isPrimaryId,
			FlagsValid:   true,
			FlagSign:     true,
			FlagCertify:  true,
			IssuerKeyId:  &e.PrimaryKey.KeyId,
		},
	}

	e.Subkeys = make([]Subkey, 1)
	e.Subkeys[0] = Subkey{
		PublicKey:  packet.NewRSAPublicKey(t, &encryptingPriv.PublicKey, true /* is a subkey */),
		PrivateKey: packet.NewRSAPrivateKey(t, encryptingPriv, true /* is a subkey */),
		Sig: &packet.Signature{
			CreationTime:              t,
			SigType:                   packet.SigTypeSubkeyBinding,
			PubKeyAlgo:                packet.PubKeyAlgoRSA,
			Hash:                      crypto.SHA256,
			FlagsValid:                true,
			FlagEncryptStorage:        true,
			FlagEncryptCommunications: true,
			IssuerKeyId:               &e.PrimaryKey.KeyId,
		},
	}

	return e, nil
}
开发者ID:go-nosql,项目名称:golang,代码行数:59,代码来源:keys.go


示例12: TestKeys

func TestKeys(t *testing.T) {
	var err error
	MasterKey, err = rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}
	SlaveKey, err = rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}
	Keys = NewPubKeys()
	Keys.Put("master", &MasterKey.PublicKey)
	Keys.Put("slave", &SlaveKey.PublicKey)
}
开发者ID:fcavani,项目名称:discover,代码行数:14,代码来源:discover_test.go


示例13: Example

// Example demonstrate discovery in work.
func Example() {
	masterKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println(err)
	}
	slaveKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println(err)
	}
	keys := NewPubKeys()
	keys.Put("slave", &slaveKey.PublicKey)

	server := &Server{}
	server.Name = "master"
	server.PrivateKey = masterKey
	server.PubKeys = keys
	server.Protocol = func(addr *net.UDPAddr, req *Request) (resp *Response, err error) {
		if string(req.Data) != "request" {
			return nil, e.New("protocol error")
		}
		return &Response{
			Data: []byte("msg"),
		}, nil
	}
	err = server.Do()
	if err != nil {
		fmt.Println(err)
	}
	defer server.Close()

	client := &Client{}
	client.ServerName = "master"
	client.ServerKey = &masterKey.PublicKey
	client.Name = "slave"
	client.PrivateKey = slaveKey
	client.Port = server.Port
	client.Request = func(dst *net.UDPAddr) (*Request, error) {
		return &Request{
			Data: []byte("request"),
		}, nil
	}
	resp, err := client.Discover()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(resp.Data))
	//Output:
	//msg
}
开发者ID:fcavani,项目名称:discover,代码行数:50,代码来源:discover_test.go


示例14: NewMockUpaxClient

func NewMockUpaxClient(name, lfs string, members []*xcl.MemberInfo,
	primary uint) (mc *MockUpaxClient, err error) {
	var (
		ckPriv, skPriv *rsa.PrivateKey
		ep             []xt.EndPointI
		node           *xn.Node
		uc             *UpaxClient
	)

	// lfs should be a well-formed POSIX path; if the directory does
	// not exist we should create it.
	err = xf.CheckLFS(lfs, 0750)

	// The ckPriv is an RSA key used to encrypt short messages.
	if err == nil {
		if ckPriv == nil {
			ckPriv, err = rsa.GenerateKey(rand.Reader, 2048)
		}
		if err == nil {
			// The skPriv is an RSA key used to create digital signatures.
			if skPriv == nil {
				skPriv, err = rsa.GenerateKey(rand.Reader, 2048)
			}
		}
	}
	// The mock client uses a system-assigned endpoint
	if err == nil {
		var endPoint *xt.TcpEndPoint
		endPoint, err = xt.NewTcpEndPoint("127.0.0.1:0")
		if err == nil {
			ep = []xt.EndPointI{endPoint}
		}
	}
	// spin up an XLattice node
	if err == nil {
		node, err = xn.New(name, nil, // get a default NodeID
			lfs, ckPriv, skPriv, nil, ep, nil) // nil overlays, peers
	}
	if err == nil {
		uc, err = NewUpaxClient(ckPriv, skPriv, node, members, primary)
		if err == nil {
			mc = &MockUpaxClient{
				UpaxClient: *uc,
			}
		}
	}
	return
}
开发者ID:jddixon,项目名称:upax_go,代码行数:48,代码来源:mock_client_test.go


示例15: GenerateKey

// GenerateKey generates a private/public key pair of the given bits. It panics on error.
func GenerateKey(bits int) (asserts.PrivateKey, *rsa.PrivateKey) {
	priv, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		panic(fmt.Errorf("failed to create private key: %v", err))
	}
	return asserts.RSAPrivateKey(priv), priv
}
开发者ID:niemeyer,项目名称:snapd,代码行数:8,代码来源:assertstest.go


示例16: BenchmarkCheckCert

func BenchmarkCheckCert(b *testing.B) {
	dbMap, err := sa.NewDbMap(dbConnStr)
	if err != nil {
		fmt.Println("Couldn't connect to database")
		return
	}

	checker := newChecker(dbMap)
	testKey, _ := rsa.GenerateKey(rand.Reader, 1024)
	expiry := time.Now().AddDate(0, 0, 1)
	serial := big.NewInt(1337)
	rawCert := x509.Certificate{
		Subject: pkix.Name{
			CommonName: "example.com",
		},
		NotAfter:     expiry,
		DNSNames:     []string{"example-a.com"},
		SerialNumber: serial,
	}
	certDer, _ := x509.CreateCertificate(rand.Reader, &rawCert, &rawCert, &testKey.PublicKey, testKey)
	cert := core.Certificate{
		Status:  core.StatusValid,
		Serial:  core.SerialToString(serial),
		Digest:  core.Fingerprint256(certDer),
		DER:     certDer,
		Issued:  time.Now(),
		Expires: expiry,
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		checker.checkCert(cert)
	}
}
开发者ID:devpaul,项目名称:boulder,代码行数:33,代码来源:main_test.go


示例17: 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")
	}
}
开发者ID:JoeHorn,项目名称:boulder,代码行数:27,代码来源:csr.go


示例18: 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")
	}
}
开发者ID:bbandix,项目名称:cfssl,代码行数:30,代码来源:csr.go


示例19: TestSignAndVerify

func TestSignAndVerify(t *testing.T) {
	header := &Header{
		Algorithm: "RS256",
		Typ:       "JWT",
	}
	payload := &ClaimSet{
		Iss: "http://google.com/",
		Aud: "",
		Exp: 3610,
		Iat: 10,
	}

	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}

	token, err := Encode(header, payload, privateKey)
	if err != nil {
		t.Fatal(err)
	}

	err = Verify(token, &privateKey.PublicKey)
	if err != nil {
		t.Fatal(err)
	}
}
开发者ID:Crosse,项目名称:oauth2,代码行数:27,代码来源:jws_test.go


示例20: generatePrivateKey

func generatePrivateKey() (*packet.PrivateKey, error) {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}
	return packet.NewRSAPrivateKey(time.Now(), priv), nil
}
开发者ID:General-Beck,项目名称:snappy,代码行数:7,代码来源:crypto.go



注:本文中的crypto/rsa.GenerateKey函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang rsa.SignPKCS1v15函数代码示例发布时间:2022-05-24
下一篇:
Golang rsa.EncryptPKCS1v15函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap