Skip to content

Commit

Permalink
Streamline exporting from jwk.Key to raw key
Browse files Browse the repository at this point in the history
Remove Raw() from keys, and implement jwk.Export
  • Loading branch information
lestrrat committed Nov 21, 2023
1 parent ebfaa54 commit 7206695
Show file tree
Hide file tree
Showing 19 changed files with 213 additions and 210 deletions.
10 changes: 6 additions & 4 deletions Changes-v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ These are changes that are incompatible with the v2.x.x version.

## Module

* This module now requires Go 1.20.x
* This module now requires Go 1.21

* All `xxx.Get()` methods have been changed from `Get(string) (interface{}, error)` to
`Get(string, interface{}) error`, where the second argument should be a pointer
Expand Down Expand Up @@ -42,7 +42,9 @@ These are changes that are incompatible with the v2.x.x version.
type to instantiate, and aids implementing your own `jwk.KeyParser`. Also see
`jwk.RegisterKeyProbe()`

* Conversion between raw keys and `jwk.Key` can be customized using `jwk.KeyConverter`.
Also see `jwk.RegisterKeyConverter()`
* Conversion between raw keys and `jwk.Key` can be customized using `jwk.KeyImporter` and `jwk.KeyExporter`.
Also see `jwk.RegisterKeyImporter()` and `jwk.RegisterKeyExporter()`

* Added `jwk/ecdsa` to keep track of which curves are available for ECDSA keys.
* Added `jwk/ecdsa` to keep track of which curves are available for ECDSA keys.

* `(jwk.Key).Raw()` has been deprecated. Use `jwk.Export()` instead.
2 changes: 1 addition & 1 deletion examples/jwk_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func ExampleJWK_Usage() {

// jws and jwe operations can be performed using jwk.Key, but you could also
// covert it to their "raw" forms, such as *rsa.PrivateKey or *ecdsa.PrivateKey
if err := key.Raw(&rawkey); err != nil {
if err := jwk.Export(key, &rawkey); err != nil {
log.Printf("failed to create public key: %s", err)
return
}
Expand Down
11 changes: 7 additions & 4 deletions examples/jwx_register_ec_and_key_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ func convertShangMiSm2(key interface{}) (jwk.Key, error) {
}

func convertJWKToShangMiSm2(key jwk.Key, hint interface{}) (interface{}, error) {
ecdsaKey := key.(jwk.ECDSAPrivateKey)
ecdsaKey, ok := key.(jwk.ECDSAPrivateKey)
if !ok {
return nil, fmt.Errorf(`invalid key type %T: %w`, key, jwk.ContinueError())
}
if ecdsaKey.Crv() != SM2 {
return nil, fmt.Errorf(`cannot convert curve of type %s to ShangMi key: %w`, ecdsaKey.Crv(), jwk.ContinueError())
}
Expand Down Expand Up @@ -87,7 +90,7 @@ func ExampleShangMiSm2() {
{
// Create a ShangMi SM2 private key back from the jwk.Key
var clone sm2.PrivateKey
if err := shangmi2JWK.Raw(&clone); err != nil {
if err := jwk.Export(shangmi2JWK, &clone); err != nil {
fmt.Printf("failed to create ShangMi private key from jwk.Key: %s\n", err)
return
}
Expand Down Expand Up @@ -116,7 +119,7 @@ func ExampleShangMiSm2() {

{ // Can do the same thing for interface{}
var clone interface{}
if err := shangmi2JWK.Raw(&clone); err != nil {
if err := jwk.Export(shangmi2JWK, &clone); err != nil {
fmt.Printf("failed to create ShangMi private key from jwk.Key (via interface{}): %s\n", err)
return
}
Expand All @@ -135,7 +138,7 @@ func ExampleShangMiSm2() {
return
}
var clone ecdsa.PrivateKey
if err := eckjwk.Raw(&clone); err != nil {
if err := jwk.Export(eckjwk, &clone); err != nil {
fmt.Printf("failed to create ShangMi public key from jwk.Key: %s\n", err)
return
}
Expand Down
10 changes: 5 additions & 5 deletions internal/jwxtest/jwxtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ func DecryptJweFile(ctx context.Context, file string, alg jwa.KeyEncryptionAlgor
}

var rawkey interface{}
if err := key.Raw(&rawkey); err != nil {
if err := jwk.Export(key, &rawkey); err != nil {
return nil, fmt.Errorf(`failed to obtain raw key from JWK: %w`, err)
}

Expand All @@ -285,19 +285,19 @@ func EncryptJweFile(ctx context.Context, payload []byte, keyalg jwa.KeyEncryptio
switch keyalg {
case jwa.RSA1_5, jwa.RSA_OAEP, jwa.RSA_OAEP_256:
var rawkey rsa.PrivateKey
if err := key.Raw(&rawkey); err != nil {
if err := jwk.Export(key, &rawkey); err != nil {
return "", nil, fmt.Errorf(`failed to obtain raw key: %w`, err)
}
keyif = rawkey.PublicKey
case jwa.ECDH_ES, jwa.ECDH_ES_A128KW, jwa.ECDH_ES_A192KW, jwa.ECDH_ES_A256KW:
var rawkey ecdsa.PrivateKey
if err := key.Raw(&rawkey); err != nil {
if err := jwk.Export(key, &rawkey); err != nil {
return "", nil, fmt.Errorf(`failed to obtain raw key: %w`, err)
}
keyif = rawkey.PublicKey
default:
var rawkey []byte
if err := key.Raw(&rawkey); err != nil {
if err := jwk.Export(key, &rawkey); err != nil {
return "", nil, fmt.Errorf(`failed to obtain raw key: %w`, err)
}
keyif = rawkey
Expand All @@ -323,7 +323,7 @@ func VerifyJwsFile(ctx context.Context, file string, alg jwa.SignatureAlgorithm,
}

var rawkey, pubkey interface{}
if err := key.Raw(&rawkey); err != nil {
if err := jwk.Export(key, &rawkey); err != nil {
return nil, fmt.Errorf(`failed to obtain raw key from JWK: %w`, err)
}
pubkey = rawkey
Expand Down
14 changes: 7 additions & 7 deletions internal/keyconv/keyconv.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
func RSAPrivateKey(dst, src interface{}) error {
if jwkKey, ok := src.(jwk.Key); ok {
var raw rsa.PrivateKey
if err := jwkKey.Raw(&raw); err != nil {
if err := jwk.Export(jwkKey, &raw); err != nil {
return fmt.Errorf(`failed to produce rsa.PrivateKey from %T: %w`, src, err)
}
src = &raw
Expand All @@ -42,7 +42,7 @@ func RSAPrivateKey(dst, src interface{}) error {
func RSAPublicKey(dst, src interface{}) error {
if jwkKey, ok := src.(jwk.Key); ok {
var raw rsa.PublicKey
if err := jwkKey.Raw(&raw); err != nil {
if err := jwk.Export(jwkKey, &raw); err != nil {
return fmt.Errorf(`failed to produce rsa.PublicKey from %T: %w`, src, err)
}
src = &raw
Expand All @@ -66,7 +66,7 @@ func RSAPublicKey(dst, src interface{}) error {
func ECDSAPrivateKey(dst, src interface{}) error {
if jwkKey, ok := src.(jwk.Key); ok {
var raw ecdsa.PrivateKey
if err := jwkKey.Raw(&raw); err != nil {
if err := jwk.Export(jwkKey, &raw); err != nil {
return fmt.Errorf(`failed to produce ecdsa.PrivateKey from %T: %w`, src, err)
}
src = &raw
Expand All @@ -89,7 +89,7 @@ func ECDSAPrivateKey(dst, src interface{}) error {
func ECDSAPublicKey(dst, src interface{}) error {
if jwkKey, ok := src.(jwk.Key); ok {
var raw ecdsa.PublicKey
if err := jwkKey.Raw(&raw); err != nil {
if err := jwk.Export(jwkKey, &raw); err != nil {
return fmt.Errorf(`failed to produce ecdsa.PublicKey from %T: %w`, src, err)
}
src = &raw
Expand All @@ -110,7 +110,7 @@ func ECDSAPublicKey(dst, src interface{}) error {
func ByteSliceKey(dst, src interface{}) error {
if jwkKey, ok := src.(jwk.Key); ok {
var raw []byte
if err := jwkKey.Raw(&raw); err != nil {
if err := jwk.Export(jwkKey, &raw); err != nil {
return fmt.Errorf(`failed to produce []byte from %T: %w`, src, err)
}
src = raw
Expand All @@ -125,7 +125,7 @@ func ByteSliceKey(dst, src interface{}) error {
func Ed25519PrivateKey(dst, src interface{}) error {
if jwkKey, ok := src.(jwk.Key); ok {
var raw ed25519.PrivateKey
if err := jwkKey.Raw(&raw); err != nil {
if err := jwk.Export(jwkKey, &raw); err != nil {
return fmt.Errorf(`failed to produce ed25519.PrivateKey from %T: %w`, src, err)
}
src = &raw
Expand All @@ -146,7 +146,7 @@ func Ed25519PrivateKey(dst, src interface{}) error {
func Ed25519PublicKey(dst, src interface{}) error {
if jwkKey, ok := src.(jwk.Key); ok {
var raw ed25519.PublicKey
if err := jwkKey.Raw(&raw); err != nil {
if err := jwk.Export(jwkKey, &raw); err != nil {
return fmt.Errorf(`failed to produce ed25519.PublicKey from %T: %w`, src, err)
}
src = &raw
Expand Down
4 changes: 2 additions & 2 deletions jwe/internal/keyenc/keyenc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,15 @@ func TestDeriveECDHES(t *testing.T) {
if !assert.NoError(t, err, `jwk.ParseKey should succeed`) {
return
}
if !assert.NoError(t, aliceWebKey.Raw(&aliceKey), `aliceWebKey.Raw should succeed`) {
if !assert.NoError(t, jwk.Export(aliceWebKey, &aliceKey), `jwk.Export(aliceWebKey) should succeed`) {
return
}

bobWebKey, err := jwk.ParseKey([]byte(bobKeySrc))
if !assert.NoError(t, err, `jwk.ParseKey should succeed`) {
return
}
if !assert.NoError(t, bobWebKey.Raw(&bobKey), `bobWebKey.Raw should succeed`) {
if !assert.NoError(t, jwk.Export(bobWebKey, &bobKey), `jwk.Export(bobWebKey) should succeed`) {
return
}

Expand Down
8 changes: 4 additions & 4 deletions jwe/jwe.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (b *recipientBuilder) Build(cek []byte, calg jwa.ContentEncryptionAlgorithm
keyID = jwkKey.KeyID()

var raw interface{}
if err := jwkKey.Raw(&raw); err != nil {
if err := jwk.Export(jwkKey, &raw); err != nil {
return nil, nil, fmt.Errorf(`failed to retrieve raw key out of %T: %w`, b.key, err)
}

Expand Down Expand Up @@ -572,7 +572,7 @@ func (dctx *decryptCtx) try(ctx context.Context, recipient Recipient, keyUsed in
func (dctx *decryptCtx) decryptContent(alg jwa.KeyEncryptionAlgorithm, key interface{}, recipient Recipient) ([]byte, error) {
if jwkKey, ok := key.(jwk.Key); ok {
var raw interface{}
if err := jwkKey.Raw(&raw); err != nil {
if err := jwk.Export(jwkKey, &raw); err != nil {
return nil, fmt.Errorf(`failed to retrieve raw key from %T: %w`, key, err)
}
key = raw
Expand Down Expand Up @@ -608,13 +608,13 @@ func (dctx *decryptCtx) decryptContent(alg jwa.KeyEncryptionAlgorithm, key inter
switch epk := epk.(type) {
case jwk.ECDSAPublicKey:
var pubkey ecdsa.PublicKey
if err := epk.Raw(&pubkey); err != nil {
if err := jwk.Export(epk, &pubkey); err != nil {
return nil, fmt.Errorf(`failed to get public key: %w`, err)
}
dec.PublicKey(&pubkey)
case jwk.OKPPublicKey:
var pubkey interface{}
if err := epk.Raw(&pubkey); err != nil {
if err := jwk.Export(epk, &pubkey); err != nil {
return nil, fmt.Errorf(`failed to get public key: %w`, err)
}
dec.PublicKey(pubkey)
Expand Down
8 changes: 4 additions & 4 deletions jwe/jwe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func init() {
panic(err)
}

if err := privkey.Raw(&rsaPrivKey); err != nil {
if err := jwk.Export(privkey, &rsaPrivKey); err != nil {
panic(err)
}
}
Expand Down Expand Up @@ -168,7 +168,7 @@ func TestParse_RSAES_OAEP_AES_GCM(t *testing.T) {
}

var rawkey rsa.PrivateKey
if !assert.NoError(t, privkey.Raw(&rawkey), `obtaining raw key should succeed`) {
if !assert.NoError(t, jwk.Export(privkey, &rawkey), `obtaining raw key should succeed`) {
return
}

Expand Down Expand Up @@ -501,7 +501,7 @@ func Test_GHIssue207(t *testing.T) {
}

var key ecdsa.PrivateKey
if !assert.NoError(t, webKey.Raw(&key), `jwk.Raw should succeed`) {
if !assert.NoError(t, jwk.Export(webKey, &key), `jwk.Export should succeed`) {
return
}

Expand Down Expand Up @@ -628,7 +628,7 @@ func TestDecodePredefined_Direct(t *testing.T) {
}

var key []byte
if !assert.NoError(t, webKey.Raw(&key), `jwk.Raw should succeed`) {
if !assert.NoError(t, jwk.Export(webKey, &key), `jwk.Export should succeed`) {
return
}

Expand Down
41 changes: 26 additions & 15 deletions jwk/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ import (
var keyImporters = make(map[reflect.Type]KeyImporter)
var keyExporters = make(map[jwa.KeyType][]KeyExporter)

var myKeyImporters sync.RWMutex
var muKeyImporters sync.RWMutex
var muKeyExporters sync.RWMutex

// RegisterKeyImporter registers a KeyImporter for the given raw key. When `jwk.FromRaw()` is called,
// the library will look up the appropriate KeyImporter for the given raw key type (via `reflect`)
// and execute the KeyImporters in succession until either one of them succeeds, or all of them fail.
func RegisterKeyImporter(from interface{}, conv KeyImporter) {
myKeyImporters.Lock()
defer myKeyImporters.Unlock()
muKeyImporters.Lock()
defer muKeyImporters.Unlock()
keyImporters[reflect.TypeOf(from)] = conv
}

Expand Down Expand Up @@ -254,32 +254,43 @@ func bytesToKey(src interface{}) (Key, error) {
return k, nil
}

// All objects call this method to convert themselves to a raw key.
// It's done this way to centralize the logic (mapping) of which keys are converted
// to what raw key.
func raw(key Key, dst interface{}) error {
myKeyImporters.RLock()
defer myKeyImporters.RUnlock()
// Export converts a `jwk.Key` to a Export key. The dst argument must be a pointer to the
// object that the user wants the result to be assigned to.
//
// Normally you would pass a pointer to the zero value of the raw key type
// such as &(*rsa.PrivateKey) or &(*ecdsa.PublicKey), which gets assigned
// the converted key.
//
// If you do not know the exact type of a jwk.Key before attempting
// to obtain the raw key, you can simply pass a pointer to an
// empty interface as the second argument
//
// If you already know the exact type, it is recommended that you
// pass a pointer to the zero value of the actual key type for efficiency.
func Export(key Key, dst interface{}) error {
// dst better be a pointer
rv := reflect.ValueOf(dst)
if rv.Kind() != reflect.Ptr {
return fmt.Errorf(`destination object must be a pointer`)
return fmt.Errorf(`jwk.Export: destination object must be a pointer`)
}
if convs, ok := keyExporters[key.KeyType()]; ok {
for _, conv := range convs {
muKeyExporters.RLock()
exporters, ok := keyExporters[key.KeyType()]
muKeyExporters.RUnlock()
if ok {
for _, conv := range exporters {
v, err := conv.Export(key, dst)
if err != nil {
if IsContinueError(err) {
continue
}
return fmt.Errorf(`failed to convert jwk.Key to raw format: %w`, err)
return fmt.Errorf(`jwk.Export: failed to export jwk.Key to raw format: %w`, err)
}

if err := blackmagic.AssignIfCompatible(dst, v); err != nil {
return fmt.Errorf(`failed to assign key: %w`, err)
return fmt.Errorf(`jwk.Export: failed to assign key: %w`, err)
}
return nil
}
}
return fmt.Errorf(`failed to find converter for key type '%T'`, key)
return fmt.Errorf(`jwk.Export: failed to find exporter for key type '%T'`, key)
}
Loading

0 comments on commit 7206695

Please sign in to comment.