TBD54566975 / web5-go

Apache License 2.0
10 stars 6 forks source link

Public Key Bytes -> JWK #13

Closed mistermoe closed 7 months ago

mistermoe commented 7 months ago

Summary

Implements Methods to convert public key bytes -> JWKs based on a specified algorithm ID. In support of https://github.com/TBD54566975/web5-go/pull/3#discussion_r1474913355. Includes minimal test coverage. full coverage to come when we consume test vectors here

Usage

package main

import (
    "encoding/hex"
    "fmt"
    "log"

    "github.com/tbd545669675/web5-go/crypto/dsa"
)

func main() {
    // Example vector taken from: https://github.com/TBD54566975/web5-js/blob/dids-new-crypto/packages/crypto/tests/fixtures/test-vectors/secp256k1/bytes-to-public-key.json
    publicKeyHex := "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
    pubKeyBytes, err := hex.DecodeString(publicKeyHex)
    if err != nil {
        log.Fatalf("Failed to decode public key hex: %v", err)
    }

    jwk, _ := dsa.BytesToPublicKey(dsa.AlgorithmIDSECP256K1, pubKeyBytes)
    fmt.Printf("JWK: %v\n", jwk)
}
KendallWeihe commented 7 months ago

What is the programmatic use case for converting an array of bytes into a public key?

frankhinek commented 7 months ago

What is the programmatic use case for converting an array of bytes into a public key?

Any case where key material needs to be converted into a format that isn't JWK. A specific example would be converting from a public key in JWK format to z-base-32 or Base64URL encoding for DID DHT or multibase encoding for DID Key.

The specifics of converting between byte array and JWK representations has some nuance that varies by the key type (e.g., Ed25519, secp256k1, etc.) so its useful to have specific implementations of publicKeyToBytes() and bytesToPublicKey() for each asymmetric key type (and the ...privateKey...() complements).

mistermoe commented 7 months ago

@KendallWeihe i linked the concrete usecase in the PR description: https://github.com/TBD54566975/web5-go/pull/3#discussion_r1474913355