本文整理匯總了Golang中github.com/ethereum/go-ethereum/crypto.GenerateKey函數的典型用法代碼示例。如果您正苦於以下問題:Golang GenerateKey函數的具體用法?Golang GenerateKey怎麽用?Golang GenerateKey使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了GenerateKey函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: testEncHandshake
func testEncHandshake(token []byte) error {
type result struct {
side string
s secrets
err error
}
var (
prv0, _ = crypto.GenerateKey()
prv1, _ = crypto.GenerateKey()
rw0, rw1 = net.Pipe()
output = make(chan result)
)
go func() {
r := result{side: "initiator"}
defer func() { output <- r }()
pub1s := discover.PubkeyID(&prv1.PublicKey)
r.s, r.err = initiatorEncHandshake(rw0, prv0, pub1s, token)
if r.err != nil {
return
}
id1 := discover.PubkeyID(&prv1.PublicKey)
if r.s.RemoteID != id1 {
r.err = fmt.Errorf("remote ID mismatch: got %v, want: %v", r.s.RemoteID, id1)
}
}()
go func() {
r := result{side: "receiver"}
defer func() { output <- r }()
r.s, r.err = receiverEncHandshake(rw1, prv1, token)
if r.err != nil {
return
}
id0 := discover.PubkeyID(&prv0.PublicKey)
if r.s.RemoteID != id0 {
r.err = fmt.Errorf("remote ID mismatch: got %v, want: %v", r.s.RemoteID, id0)
}
}()
// wait for results from both sides
r1, r2 := <-output, <-output
if r1.err != nil {
return fmt.Errorf("%s side error: %v", r1.side, r1.err)
}
if r2.err != nil {
return fmt.Errorf("%s side error: %v", r2.side, r2.err)
}
// don't compare remote node IDs
r1.s.RemoteID, r2.s.RemoteID = discover.NodeID{}, discover.NodeID{}
// flip MACs on one of them so they compare equal
r1.s.EgressMAC, r1.s.IngressMAC = r1.s.IngressMAC, r1.s.EgressMAC
if !reflect.DeepEqual(r1.s, r2.s) {
return fmt.Errorf("secrets mismatch:\n t1: %#v\n t2: %#v", r1.s, r2.s)
}
return nil
}
示例2: jwsMultiParams
func jwsMultiParams(t *testing.T) ([]*Header, *ClaimSet, []*ecdsa.PrivateKey, []*ecdsa.PublicKey) {
seckey1, err := crypto.GenerateKey()
checkErr(t, err)
seckey2, err := crypto.GenerateKey()
checkErr(t, err)
seckey3, err := crypto.GenerateKey()
checkErr(t, err)
hdr1 := CreateDefaultHeader(&seckey1.PublicKey)
hdr2 := CreateDefaultHeader(&seckey2.PublicKey)
hdr3 := CreateDefaultHeader(&seckey3.PublicKey)
clm := CreateDefaultClaimsMulti([]*ecdsa.PublicKey{
&seckey1.PublicKey,
&seckey2.PublicKey,
&seckey3.PublicKey,
})
seckeys := []*ecdsa.PrivateKey{seckey1, seckey2, seckey3}
pubkeys := []*ecdsa.PublicKey{
&seckey1.PublicKey,
&seckey2.PublicKey,
&seckey3.PublicKey,
}
return []*Header{hdr1, hdr2, hdr3}, clm, seckeys, pubkeys
}
示例3: NodeKey
// NodeKey retrieves the currently configured private key of the node, checking
// first any manually set key, falling back to the one found in the configured
// data folder. If no key can be found, a new one is generated.
func (c *Config) NodeKey() *ecdsa.PrivateKey {
// Use any specifically configured key
if c.PrivateKey != nil {
return c.PrivateKey
}
// Generate ephemeral key if no datadir is being used
if c.DataDir == "" {
key, err := crypto.GenerateKey()
if err != nil {
glog.Fatalf("Failed to generate ephemeral node key: %v", err)
}
return key
}
// Fall back to persistent key from the data directory
keyfile := filepath.Join(c.DataDir, datadirPrivateKey)
if key, err := crypto.LoadECDSA(keyfile); err == nil {
return key
}
// No persistent key found, generate and store a new one
key, err := crypto.GenerateKey()
if err != nil {
glog.Fatalf("Failed to generate node key: %v", err)
}
if err := crypto.SaveECDSA(keyfile, key); err != nil {
glog.V(logger.Error).Infof("Failed to persist node key: %v", err)
}
return key
}
示例4: TestSetupConn
func TestSetupConn(t *testing.T) {
prv0, _ := crypto.GenerateKey()
prv1, _ := crypto.GenerateKey()
node0 := &discover.Node{
ID: discover.PubkeyID(&prv0.PublicKey),
IP: net.IP{1, 2, 3, 4},
TCP: 33,
}
node1 := &discover.Node{
ID: discover.PubkeyID(&prv1.PublicKey),
IP: net.IP{5, 6, 7, 8},
TCP: 44,
}
hs0 := &protoHandshake{
Version: baseProtocolVersion,
ID: node0.ID,
Caps: []Cap{{"a", 0}, {"b", 2}},
}
hs1 := &protoHandshake{
Version: baseProtocolVersion,
ID: node1.ID,
Caps: []Cap{{"c", 1}, {"d", 3}},
}
fd0, fd1 := net.Pipe()
done := make(chan struct{})
keepalways := func(discover.NodeID) bool { return true }
go func() {
defer close(done)
conn0, err := setupConn(fd0, prv0, hs0, node1, keepalways)
if err != nil {
t.Errorf("outbound side error: %v", err)
return
}
if conn0.ID != node1.ID {
t.Errorf("outbound conn id mismatch: got %v, want %v", conn0.ID, node1.ID)
}
if !reflect.DeepEqual(conn0.Caps, hs1.Caps) {
t.Errorf("outbound caps mismatch: got %v, want %v", conn0.Caps, hs1.Caps)
}
}()
conn1, err := setupConn(fd1, prv1, hs1, nil, keepalways)
if err != nil {
t.Fatalf("inbound side error: %v", err)
}
if conn1.ID != node0.ID {
t.Errorf("inbound conn id mismatch: got %v, want %v", conn1.ID, node0.ID)
}
if !reflect.DeepEqual(conn1.Caps, hs0.Caps) {
t.Errorf("inbound caps mismatch: got %v, want %v", conn1.Caps, hs0.Caps)
}
<-done
}
示例5: main
func main() {
logger.AddLogSystem(logger.NewStdLogSystem(os.Stdout, log.LstdFlags, logger.InfoLevel))
// Generate the peer identity
key, err := crypto.GenerateKey()
if err != nil {
fmt.Printf("Failed to generate peer key: %v.\n", err)
os.Exit(-1)
}
name := common.MakeName("whisper-go", "1.0")
shh := whisper.New()
// Create an Ethereum peer to communicate through
server := p2p.Server{
PrivateKey: key,
MaxPeers: 10,
Name: name,
Protocols: []p2p.Protocol{shh.Protocol()},
ListenAddr: ":30300",
NAT: nat.Any(),
}
fmt.Println("Starting Ethereum peer...")
if err := server.Start(); err != nil {
fmt.Printf("Failed to start Ethereum peer: %v.\n", err)
os.Exit(1)
}
// Send a message to self to check that something works
payload := fmt.Sprintf("Hello world, this is %v. In case you're wondering, the time is %v", name, time.Now())
if err := selfSend(shh, []byte(payload)); err != nil {
fmt.Printf("Failed to self message: %v.\n", err)
os.Exit(-1)
}
}
示例6: TestMessageCleartextSignRecover
// Tests whether a message can be signed, and wrapped in plain-text.
func TestMessageCleartextSignRecover(t *testing.T) {
key, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("failed to create crypto key: %v", err)
}
payload := []byte("hello world")
msg := NewMessage(payload)
if _, err := msg.Wrap(DefaultPoW, Options{
From: key,
}); err != nil {
t.Fatalf("failed to sign message: %v", err)
}
if msg.Flags&signatureFlag != signatureFlag {
t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, signatureFlag)
}
if bytes.Compare(msg.Payload, payload) != 0 {
t.Fatalf("payload mismatch after signing: have 0x%x, want 0x%x", msg.Payload, payload)
}
pubKey := msg.Recover()
if pubKey == nil {
t.Fatalf("failed to recover public key")
}
p1 := elliptic.Marshal(crypto.S256(), key.PublicKey.X, key.PublicKey.Y)
p2 := elliptic.Marshal(crypto.S256(), pubKey.X, pubKey.Y)
if !bytes.Equal(p1, p2) {
t.Fatalf("public key mismatch: have 0x%x, want 0x%x", p2, p1)
}
}
示例7: TestMessageAnonymousEncryptDecrypt
// Tests whether a message can be encrypted and decrypted using an anonymous
// sender (i.e. no signature).
func TestMessageAnonymousEncryptDecrypt(t *testing.T) {
key, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("failed to create recipient crypto key: %v", err)
}
payload := []byte("hello world")
msg := NewMessage(payload)
envelope, err := msg.Wrap(DefaultPoW, Options{
To: &key.PublicKey,
})
if err != nil {
t.Fatalf("failed to encrypt message: %v", err)
}
if msg.Flags&signatureFlag != 0 {
t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, 0)
}
if len(msg.Signature) != 0 {
t.Fatalf("signature found for anonymous message: 0x%x", msg.Signature)
}
out, err := envelope.Open(key)
if err != nil {
t.Fatalf("failed to open encrypted message: %v", err)
}
if !bytes.Equal(out.Payload, payload) {
t.Error("payload mismatch: have 0x%x, want 0x%x", out.Payload, payload)
}
}
示例8: TestEnvelopeIdentifiedOpenUntargeted
func TestEnvelopeIdentifiedOpenUntargeted(t *testing.T) {
key, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("failed to generate test identity: %v", err)
}
payload := []byte("hello envelope")
envelope, err := NewMessage(payload).Wrap(DefaultPoW, Options{})
if err != nil {
t.Fatalf("failed to wrap message: %v", err)
}
opened, err := envelope.Open(key)
switch err {
case nil:
t.Fatalf("envelope opened with bad key: %v", opened)
case ecies.ErrInvalidPublicKey:
// Ok, key mismatch but opened
default:
t.Fatalf("failed to open envelope: %v", err)
}
if opened.To != nil {
t.Fatalf("recipient mismatch: have 0x%x, want nil", opened.To)
}
if bytes.Compare(opened.Payload, payload) != 0 {
t.Fatalf("payload mismatch: have 0x%x, want 0x%x", opened.Payload, payload)
}
}
示例9: newkey
func newkey() *ecdsa.PrivateKey {
key, err := crypto.GenerateKey()
if err != nil {
panic("couldn't generate key: " + err.Error())
}
return key
}
示例10: setupTxPool
func setupTxPool() (*TxPool, *ecdsa.PrivateKey) {
db, _ := ethdb.NewMemDatabase()
statedb := state.New(common.Hash{}, db)
var m event.TypeMux
key, _ := crypto.GenerateKey()
return NewTxPool(&m, func() *state.StateDB { return statedb }, func() *big.Int { return big.NewInt(1000000) }), key
}
示例11: init
func init() {
ringKeys[0] = benchRootKey
ringAddrs[0] = benchRootAddr
for i := 1; i < len(ringKeys); i++ {
ringKeys[i], _ = crypto.GenerateKey()
ringAddrs[i] = crypto.PubkeyToAddress(ringKeys[i].PublicKey)
}
}
示例12: NewIdentity
// NewIdentity generates a new cryptographic identity for the client, and injects
// it into the known identities for message decryption.
func (self *Whisper) NewIdentity() *ecdsa.PrivateKey {
key, err := crypto.GenerateKey()
if err != nil {
panic(err)
}
self.keys[string(crypto.FromECDSAPub(&key.PublicKey))] = key
return key
}
示例13: TestMessageFullCrypto
// Tests whether a message can be properly signed and encrypted.
func TestMessageFullCrypto(t *testing.T) {
fromKey, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("failed to create sender crypto key: %v", err)
}
toKey, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("failed to create recipient crypto key: %v", err)
}
payload := []byte("hello world")
msg := NewMessage(payload)
envelope, err := msg.Wrap(DefaultPoW, Options{
From: fromKey,
To: &toKey.PublicKey,
})
if err != nil {
t.Fatalf("failed to encrypt message: %v", err)
}
if msg.Flags&signatureFlag != signatureFlag {
t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, signatureFlag)
}
if len(msg.Signature) == 0 {
t.Fatalf("no signature found for signed message")
}
out, err := envelope.Open(toKey)
if err != nil {
t.Fatalf("failed to open encrypted message: %v", err)
}
if !bytes.Equal(out.Payload, payload) {
t.Error("payload mismatch: have 0x%x, want 0x%x", out.Payload, payload)
}
pubKey := out.Recover()
if pubKey == nil {
t.Fatalf("failed to recover public key")
}
p1 := elliptic.Marshal(crypto.S256(), fromKey.PublicKey.X, fromKey.PublicKey.Y)
p2 := elliptic.Marshal(crypto.S256(), pubKey.X, pubKey.Y)
if !bytes.Equal(p1, p2) {
t.Fatalf("public key mismatch: have 0x%x, want 0x%x", p2, p1)
}
}
示例14: TestNodeKeyPersistency
// Tests that node keys can be correctly created, persisted, loaded and/or made
// ephemeral.
func TestNodeKeyPersistency(t *testing.T) {
// Create a temporary folder and make sure no key is present
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("failed to create temporary data directory: %v", err)
}
defer os.RemoveAll(dir)
if _, err := os.Stat(filepath.Join(dir, datadirPrivateKey)); err == nil {
t.Fatalf("non-created node key already exists")
}
// Configure a node with a preset key and ensure it's not persisted
key, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("failed to generate one-shot node key: %v", err)
}
if _, err := New(&Config{DataDir: dir, PrivateKey: key}); err != nil {
t.Fatalf("failed to create empty stack: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, datadirPrivateKey)); err == nil {
t.Fatalf("one-shot node key persisted to data directory")
}
// Configure a node with no preset key and ensure it is persisted this time
if _, err := New(&Config{DataDir: dir}); err != nil {
t.Fatalf("failed to create newly keyed stack: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, datadirPrivateKey)); err != nil {
t.Fatalf("node key not persisted to data directory: %v", err)
}
key, err = crypto.LoadECDSA(filepath.Join(dir, datadirPrivateKey))
if err != nil {
t.Fatalf("failed to load freshly persisted node key: %v", err)
}
blob1, err := ioutil.ReadFile(filepath.Join(dir, datadirPrivateKey))
if err != nil {
t.Fatalf("failed to read freshly persisted node key: %v", err)
}
// Configure a new node and ensure the previously persisted key is loaded
if _, err := New(&Config{DataDir: dir}); err != nil {
t.Fatalf("failed to create previously keyed stack: %v", err)
}
blob2, err := ioutil.ReadFile(filepath.Join(dir, datadirPrivateKey))
if err != nil {
t.Fatalf("failed to read previously persisted node key: %v", err)
}
if bytes.Compare(blob1, blob2) != 0 {
t.Fatalf("persisted node key mismatch: have %x, want %x", blob2, blob1)
}
// Configure ephemeral node and ensure no key is dumped locally
if _, err := New(&Config{DataDir: ""}); err != nil {
t.Fatalf("failed to create ephemeral stack: %v", err)
}
if _, err := os.Stat(filepath.Join(".", datadirPrivateKey)); err == nil {
t.Fatalf("ephemeral node key persisted to disk")
}
}
示例15: setupTxPool
func setupTxPool() (*TxPool, *ecdsa.PrivateKey) {
db, _ := ethdb.NewMemDatabase()
statedb, _ := state.New(common.Hash{}, db)
var m event.TypeMux
key, _ := crypto.GenerateKey()
newPool := NewTxPool(testChainConfig(), &m, func() (*state.StateDB, error) { return statedb, nil }, func() *big.Int { return big.NewInt(1000000) })
newPool.resetState()
return newPool, key
}