Skip to content

Commit

Permalink
Custom elliptic curve example (#1012)
Browse files Browse the repository at this point in the history
* Add an example adding new EC algo and key type

* Add failing example

* Kind of fix, but still need to review spec

* Appease linter

* Add more context for debugging

* fix directive

* See if bumping go version to 1.21 only makes a difference

* fix one more

* Rename RJ/JR to Import/Export

* fix usage

* docs

* oops, add missing file

* Streamline exporting from jwk.Key to raw key

Remove Raw() from keys, and implement jwk.Export

* fix typo

* appease linter

* fix type detection for symmetric keys

* rework OKP tests so that crypto/ecdh keys are tested

* fix handling of x25519 keys

* tweak

* tweak docs

* gofmt
  • Loading branch information
lestrrat committed Jan 11, 2024
1 parent dd7e72c commit 0969d9d
Show file tree
Hide file tree
Showing 24 changed files with 924 additions and 402 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
strategy:
matrix:
go_tags: [ 'stdlib', 'goccy', 'es256k', 'asmbase64', 'alltags']
go: [ '1.21', '1.20' ]
go: [ '1.21' ]
name: "Test [ Go ${{ matrix.go }} / Tags ${{ matrix.go_tags }} ]"
steps:
- name: Checkout repository
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/smoke.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
strategy:
matrix:
go_tags: [ 'stdlib', 'goccy', 'es256k', 'alltags' ]
go: [ '1.21', '1.20' ]
go: [ '1.21' ]
name: "Smoke [ Go ${{ matrix.go }} / Tags ${{ matrix.go_tags }} ]"
steps:
- name: Checkout repository
Expand Down
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.
1 change: 1 addition & 0 deletions examples/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.20

require (
github.com/cloudflare/circl v1.3.7
github.com/emmansun/gmsm v0.21.5
github.com/lestrrat-go/jwx/v3 v3.0.0
)

Expand Down
2 changes: 2 additions & 0 deletions examples/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0=
github.com/emmansun/gmsm v0.21.5 h1:G4HwuiqNQGZmAlZi233iwDPcfWKcoax0/GzS3eR+l7o=
github.com/emmansun/gmsm v0.21.5/go.mod h1:5hRB+YZ3dy/llu3dcKyBHieRe5Z2V6sqvNJOWEsIcqQ=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/lestrrat-go/blackmagic v1.0.2 h1:Cg2gVSc9h7sz9NOByczrbUvLopQmXrfFx//N+AkAr5k=
Expand Down
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
169 changes: 169 additions & 0 deletions examples/jwx_register_ec_and_key_example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package examples_test

import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"math/big"

"github.com/emmansun/gmsm/sm2"
"github.com/lestrrat-go/jwx/v3/jwa"
"github.com/lestrrat-go/jwx/v3/jwk"
ourecdsa "github.com/lestrrat-go/jwx/v3/jwk/ecdsa"
"github.com/lestrrat-go/jwx/v3/jws"
)

// Setup. This is something that you probably should do in your adapter
// library, or in your application's init() function.
//
// I could not readily find what the exact curve notation is for ShangMi SM2
// (either I'm just bad at researching or it's not in an RFC as of this writing)
// so I'm faking it as "SM2".
//
// For demonstration purposes, it could as well be a random string, as long
// as its consistent in your usage.
const SM2 jwa.EllipticCurveAlgorithm = "SM2"

func init() {
// Register the algorithm name so it can be looked up
jwa.RegisterEllipticCurveAlgorithm(SM2)

// Register the actual ECDSA curve. Notice that we need to tell this
// to our jwk library, so that the JWK lookup can be done properly
// when a raw SM2 key is passed to various key operations.
ourecdsa.RegisterCurve(SM2, sm2.P256())

// We only need one converter for the private key, because the public key
// is exactly the same type as *ecdsa.PublicKey
jwk.RegisterKeyImporter(&sm2.PrivateKey{}, jwk.KeyImportFunc(convertShangMiSm2))

jwk.RegisterKeyExporter(jwa.EC, jwk.KeyExportFunc(convertJWKToShangMiSm2))
}

func convertShangMiSm2(key interface{}) (jwk.Key, error) {
shangmi2pk, ok := key.(*sm2.PrivateKey)
if !ok {
return nil, fmt.Errorf("invalid SM2 private key")
}
return jwk.FromRaw(shangmi2pk.PrivateKey)
}

func convertJWKToShangMiSm2(key jwk.Key, hint interface{}) (interface{}, error) {
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())
}

switch hint.(type) {
case *sm2.PrivateKey, *interface{}:
default:
return nil, fmt.Errorf(`can only convert SM2 key to *sm2.PrivateKey (got %T): %w`, hint, jwk.ContinueError())
}

var ret sm2.PrivateKey
ret.PublicKey.Curve = sm2.P256()
ret.D = (&big.Int{}).SetBytes(ecdsaKey.D())
ret.PublicKey.X = (&big.Int{}).SetBytes(ecdsaKey.X())
ret.PublicKey.Y = (&big.Int{}).SetBytes(ecdsaKey.Y())
return &ret, nil
}

// End setup

func ExampleShangMiSm2() {
shangmi2pk, _ := sm2.GenerateKey(rand.Reader)

// Create a jwk.Key from ShangMi SM2 private key
shangmi2JWK, err := jwk.FromRaw(shangmi2pk)
if err != nil {
fmt.Printf("failed to create jwk.Key from raw ShangMi private key: %s\n", err)
return
}

{
// Create a ShangMi SM2 private key back from the jwk.Key
var clone sm2.PrivateKey
if err := jwk.Export(shangmi2JWK, &clone); err != nil {
fmt.Printf("failed to create ShangMi private key from jwk.Key: %s\n", err)
return
}

// Clone should have same Crv, D, X, and Y values
if clone.Curve != shangmi2pk.Curve {
fmt.Println("curve does not match")
return
}

if clone.D.Cmp(shangmi2pk.D) != 0 {
fmt.Println("D does not match")
return
}

if clone.X.Cmp(shangmi2pk.X) != 0 {
fmt.Println("X does not match")
return
}

if clone.Y.Cmp(shangmi2pk.Y) != 0 {
fmt.Println("Y does not match")
return
}
}

{ // Can do the same thing for interface{}
var clone interface{}
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
}
}

{
// Of course, ecdsa.PrivateKeys are also supported separately
ecprivkey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
fmt.Println(err)
return
}
eckjwk, err := jwk.FromRaw(ecprivkey)
if err != nil {
fmt.Printf("failed to create jwk.Key from raw ShangMi public key: %s\n", err)
return
}
var clone ecdsa.PrivateKey
if err := jwk.Export(eckjwk, &clone); err != nil {
fmt.Printf("failed to create ShangMi public key from jwk.Key: %s\n", err)
return
}
}

payload := []byte("Lorem ipsum")
signed, err := jws.Sign(payload, jws.WithKey(jwa.ES256, shangmi2JWK))
if err != nil {
fmt.Printf("Failed to sign using ShangMi key: %s\n", err)
return
}

shangmi2PubJWK, err := jwk.PublicKeyOf(shangmi2JWK)
if err != nil {
fmt.Printf("Failed to create public JWK using ShangMi key: %s\n", err)
return
}

verified, err := jws.Verify(signed, jws.WithKey(jwa.ES256, shangmi2PubJWK))
if err != nil {
fmt.Printf("Failed to verify using ShangMi key: %s\n", err)
return
}

if !bytes.Equal(payload, verified) {
fmt.Println("payload does not match")
return
}
//OUTPUT:
}
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
10 changes: 5 additions & 5 deletions internal/keyconv/keyconv.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ 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 {
return fmt.Errorf(`keyconv: failed to produce rsa.PrivateKey from %T: %w`, src, err)
if err := jwk.Export(jwkKey, &raw); err != nil {
return fmt.Errorf(`failed to produce rsa.PrivateKey from %T: %w`, src, err)
}
src = &raw
}
Expand Down Expand Up @@ -70,7 +70,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(`keyconv: failed to produce ecdsa.PrivateKey from %T: %w`, src, err)
}
src = &raw
Expand Down Expand Up @@ -118,7 +118,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(`keyconv: failed to produce []byte from %T: %w`, src, err)
}
src = raw
Expand All @@ -133,7 +133,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 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 @@ -95,7 +95,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 @@ -620,7 +620,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 @@ -657,13 +657,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
Loading

0 comments on commit 0969d9d

Please sign in to comment.