本文整理汇总了Golang中crypto/rsa.GenerateKey函数的典型用法代码示例。如果您正苦于以下问题:Golang GenerateKey函数的具体用法?Golang GenerateKey怎么用?Golang GenerateKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GenerateKey函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
}
}
}
}
示例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`)
}
示例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
}
示例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)
}
示例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)
}
}
}
}
}
示例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
}
示例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)
}
示例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")
}
}
示例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)
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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
}