did: simplify public API, add missing required algorithm

This commit is contained in:
Michael Muré
2024-10-14 15:16:38 +02:00
parent 59da2d1a2c
commit f8b5fa3a32
4 changed files with 104 additions and 156 deletions

View File

@@ -1,6 +1,7 @@
package did
import (
"crypto/rand"
"errors"
crypto "github.com/libp2p/go-libp2p/core/crypto"
@@ -9,6 +10,42 @@ import (
"github.com/multiformats/go-varint"
)
// GenerateEd25519 generates an Ed25519 private key and the matching DID.
// This is the RECOMMENDED algorithm.
func GenerateEd25519() (crypto.PrivKey, DID, error) {
priv, pub, err := crypto.GenerateEd25519Key(rand.Reader)
if err != nil {
return nil, Undef, nil
}
did, err := FromPubKey(pub)
return priv, did, err
}
// GenerateRSA generates a RSA private key and the matching DID.
func GenerateSecp256k1() (crypto.PrivKey, DID, error) {
// NIST Special Publication 800-57 Part 1 Revision 5
// Section 5.6.1.1 (Table 2)
// Paraphrased: 2048-bit RSA keys are secure until 2030 and 3072-bit keys are recommended for longer-term security.
const keyLength = 3072
priv, pub, err := crypto.GenerateRSAKeyPair(keyLength, rand.Reader)
if err != nil {
return nil, Undef, nil
}
did, err := FromPubKey(pub)
return priv, did, err
}
// GenerateEd25519 generates a Secp256k1 private key and the matching DID.
func GenerateRSA() (crypto.PrivKey, DID, error) {
priv, pub, err := crypto.GenerateSecp256k1Key(rand.Reader)
if err != nil {
return nil, Undef, nil
}
did, err := FromPubKey(pub)
return priv, did, err
}
func FromPrivKey(privKey crypto.PrivKey) (DID, error) {
return FromPubKey(privKey.GetPublic())
}
@@ -21,20 +58,17 @@ func FromPubKey(pubKey crypto.PubKey) (DID, error) {
pb.KeyType_ECDSA: multicodec.Es256,
}[pubKey.Type()]
if !ok {
return Undef, errors.New("Blah")
return Undef, errors.New("unsupported key type")
}
buf := varint.ToUvarint(uint64(code))
pubBytes, err := pubKey.Raw()
if err != nil {
return Undef, err
}
return DID{
str: string(append(buf, pubBytes...)),
code: uint64(code),
key: true,
code: code,
bytes: string(append(varint.ToUvarint(uint64(code)), pubBytes...)),
}, nil
}