-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #28 from ipfs/key-derivation
Feat: key derivation for libp2p identities
- Loading branch information
Showing
4 changed files
with
109 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package main | ||
|
||
import ( | ||
"crypto/ed25519" | ||
crand "crypto/rand" | ||
"crypto/sha256" | ||
"errors" | ||
"io" | ||
|
||
libp2p "github.com/libp2p/go-libp2p/core/crypto" | ||
"github.com/mr-tron/base58" | ||
"golang.org/x/crypto/hkdf" | ||
) | ||
|
||
const seedBytes = 32 | ||
|
||
// newSeed returns a b58 encoded random seed. | ||
func newSeed() (string, error) { | ||
bs := make([]byte, seedBytes) | ||
_, err := io.ReadFull(crand.Reader, bs) | ||
if err != nil { | ||
return "", err | ||
} | ||
return base58.Encode(bs), nil | ||
} | ||
|
||
// derive derives libp2p keys from a b58-encoded seed. | ||
func deriveKey(b58secret string, info []byte) (libp2p.PrivKey, error) { | ||
secret, err := base58.Decode(b58secret) | ||
if err != nil { | ||
return nil, err | ||
} | ||
if len(secret) < seedBytes { | ||
return nil, errors.New("derivation seed is too short") | ||
} | ||
|
||
hash := sha256.New | ||
hkdf := hkdf.New(hash, secret, nil, info) | ||
keySeed := make([]byte, ed25519.SeedSize) | ||
if _, err := io.ReadFull(hkdf, keySeed); err != nil { | ||
return nil, err | ||
} | ||
key := ed25519.NewKeyFromSeed(keySeed) | ||
return libp2p.UnmarshalEd25519PrivateKey(key) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters