From a5172143fe2f80d1ce0c4f8ae6dac80a74be6baf Mon Sep 17 00:00:00 2001 From: Oleg Bespalov Date: Tue, 20 Feb 2024 16:35:51 +0100 Subject: [PATCH] Implementation import/export JWK implementation --- go.mod | 12 ++- go.sum | 27 ++++++- webcrypto/aes.go | 64 ++++++++++----- webcrypto/algorithm.go | 6 ++ webcrypto/hash.go | 6 ++ webcrypto/hmac.go | 42 ++++++++-- webcrypto/jwk.go | 91 ++++++++++++++++++++++ webcrypto/subtle_crypto.go | 50 +++++++++--- webcrypto/test_setup.go | 7 ++ webcrypto/tests/import_export/symmetric.js | 28 +++---- 10 files changed, 271 insertions(+), 62 deletions(-) create mode 100644 webcrypto/jwk.go diff --git a/go.mod b/go.mod index 7c82ba8..3a6db6d 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.19 require ( github.com/dop251/goja v0.0.0-20231027120936-b396bb4c349d github.com/google/uuid v1.3.1 + github.com/lestrrat-go/jwx/v2 v2.0.20 github.com/stretchr/testify v1.8.4 go.k6.io/k6 v0.49.0 gopkg.in/guregu/null.v3 v3.3.0 @@ -13,15 +14,22 @@ require ( require ( github.com/cenkalti/backoff/v4 v4.2.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/dlclark/regexp2 v1.9.0 // indirect github.com/fatih/color v1.16.0 // indirect github.com/go-logr/logr v1.3.0 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-sourcemap/sourcemap v2.1.4-0.20211119122758-180fcef48034+incompatible // indirect + github.com/goccy/go-json v0.10.2 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/pprof v0.0.0-20230728192033-2ba5b33183c6 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0 // indirect github.com/josharian/intern v1.0.0 // indirect + github.com/lestrrat-go/blackmagic v1.0.2 // indirect + github.com/lestrrat-go/httpcc v1.0.1 // indirect + github.com/lestrrat-go/httprc v1.0.4 // indirect + github.com/lestrrat-go/iter v1.0.2 // indirect + github.com/lestrrat-go/option v1.0.1 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect @@ -29,6 +37,7 @@ require ( github.com/onsi/ginkgo v1.16.5 // indirect github.com/onsi/gomega v1.20.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/segmentio/asm v1.2.0 // indirect github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/spf13/afero v1.1.2 // indirect @@ -40,8 +49,9 @@ require ( go.opentelemetry.io/otel/sdk v1.21.0 // indirect go.opentelemetry.io/otel/trace v1.21.0 // indirect go.opentelemetry.io/proto/otlp v1.0.0 // indirect + golang.org/x/crypto v0.19.0 // indirect golang.org/x/net v0.19.0 // indirect - golang.org/x/sys v0.15.0 // indirect + golang.org/x/sys v0.17.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/time v0.5.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20231002182017-d307bd883b97 // indirect diff --git a/go.sum b/go.sum index 0d3cf98..46afeff 100644 --- a/go.sum +++ b/go.sum @@ -8,6 +8,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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/dlclark/regexp2 v1.4.1-0.20201116162257-a2a8dda75c91/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dlclark/regexp2 v1.9.0 h1:pTK/l/3qYIKaRXuHnEnIf7Y5NxfRPfpb7dis6/gdlVI= @@ -31,6 +33,8 @@ github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5Nq github.com/go-sourcemap/sourcemap v2.1.4-0.20211119122758-180fcef48034+incompatible h1:bopx7t9jyUNX1ebhr0G4gtQWmUOgwQRI0QsYhdYLgkU= github.com/go-sourcemap/sourcemap v2.1.4-0.20211119122758-180fcef48034+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +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/golang/glog v1.1.2 h1:DVjP2PbBOzHyzA+dn3WhHIq4NdVu3Q+pvivFICf/7fo= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= @@ -68,6 +72,18 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lestrrat-go/blackmagic v1.0.2 h1:Cg2gVSc9h7sz9NOByczrbUvLopQmXrfFx//N+AkAr5k= +github.com/lestrrat-go/blackmagic v1.0.2/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU= +github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= +github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= +github.com/lestrrat-go/httprc v1.0.4 h1:bAZymwoZQb+Oq8MEbyipag7iSq6YIga8Wj6GOiJGdI8= +github.com/lestrrat-go/httprc v1.0.4/go.mod h1:mwwz3JMTPBjHUkkDv/IGJ39aALInZLrhBp0X7KGUZlo= +github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI= +github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4= +github.com/lestrrat-go/jwx/v2 v2.0.20 h1:sAgXuWS/t8ykxS9Bi2Qtn5Qhpakw1wrcjxChudjolCc= +github.com/lestrrat-go/jwx/v2 v2.0.20/go.mod h1:UlCSmKqw+agm5BsOBfEAbTvKsEApaGNqHAEUTv5PJC4= +github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= +github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= @@ -94,6 +110,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys= +github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e h1:zWKUYT07mGmVBH+9UgnHXd/ekCK99C8EbDSAt5qsjXE= github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e/go.mod h1:Yow6lPLSAXx2ifx470yD/nUe22Dv5vBvxK/UK9UUTVs= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= @@ -102,7 +120,9 @@ github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -130,7 +150,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= +golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -163,8 +184,8 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= diff --git a/webcrypto/aes.go b/webcrypto/aes.go index 4ea50ae..c023694 100644 --- a/webcrypto/aes.go +++ b/webcrypto/aes.go @@ -6,6 +6,7 @@ import ( "crypto/cipher" "crypto/rand" "errors" + "fmt" "github.com/dop251/goja" ) @@ -23,6 +24,12 @@ type AESKeyGenParams struct { Length bitLength `js:"length"` } +var _ hasAlg = (*AESKeyGenParams)(nil) + +func (akgp AESKeyGenParams) alg() string { + return akgp.Name +} + // newAESKeyGenParams creates a new AESKeyGenParams object, from the // normalized algorithm, and the algorithm parameters. // @@ -84,7 +91,7 @@ func (akgp *AESKeyGenParams) GenerateKey( // 5. 6. 7. 8. 9. key := CryptoKey{} key.Type = SecretCryptoKeyType - key.Algorithm = AESKeyAlgorithm{ + key.Algorithm = &AESKeyAlgorithm{ Algorithm: akgp.Algorithm, Length: int64(akgp.Length), } @@ -114,10 +121,14 @@ type AESKeyAlgorithm struct { Length int64 `js:"length"` } +var _ hasAlg = (*AESKeyAlgorithm)(nil) + +func (aka AESKeyAlgorithm) alg() string { + return aka.Name +} + // exportAESKey exports an AES key to its raw representation. -// -// TODO @oleiade: support JWK format. -func exportAESKey(key *CryptoKey, format KeyFormat) ([]byte, error) { +func exportAESKey(key *CryptoKey, format KeyFormat) (interface{}, error) { if !key.Extractable { return nil, NewError(InvalidAccessError, "the key is not extractable") } @@ -135,8 +146,15 @@ func exportAESKey(key *CryptoKey, format KeyFormat) ([]byte, error) { } return handle, nil + case JwkKeyFormat: + m, err := exportSymmetricJWK(key) + if err != nil { + return nil, NewError(ImplementationError, err.Error()) + } + + return m, nil + default: - // FIXME: note that we do not support JWK format, yet. return nil, NewError(NotSupportedError, unsupportedKeyFormatErrorMsg+" "+format) } } @@ -156,8 +174,6 @@ func newAESImportParams(normalized Algorithm) *AESImportParams { // ImportKey imports an AES key from its raw representation. // It implements the KeyImporter interface. -// -// TODO @oleiade: support JWK format #37 func (aip *AESImportParams) ImportKey( format KeyFormat, keyData []byte, @@ -172,21 +188,25 @@ func (aip *AESImportParams) ImportKey( } } - switch format { - case RawKeyFormat: - var ( - has128Bits = len(keyData) == 16 - has192Bits = len(keyData) == 24 - has256Bits = len(keyData) == 32 - ) - - if !has128Bits && !has192Bits && !has256Bits { - return nil, NewError(DataError, "invalid key length") - } - default: + // only raw and jwk formats are supported for HMAC + if format != RawKeyFormat && format != JwkKeyFormat { return nil, NewError(NotSupportedError, unsupportedKeyFormatErrorMsg+" "+format) } + // if the key is in JWK format, we need to extract the symmetric key from it + if format == JwkKeyFormat { + var err error + keyData, err = extractSymmetricJWK(keyData) + if err != nil { + return nil, NewError(DataError, err.Error()) + } + } + + // check the key length + if !isAESBitsLengthValid(len(keyData)) { + return nil, NewError(DataError, fmt.Sprintf("invalid key length %v bytes", len(keyData))) + } + key := &CryptoKey{ Algorithm: AESKeyAlgorithm{ Algorithm: aip.Algorithm, @@ -199,6 +219,12 @@ func (aip *AESImportParams) ImportKey( return key, nil } +// isAESBitsLengthValid returns true if the given length is a valid AES key length. +// As per the [specification]. +func isAESBitsLengthValid(length int) bool { + return length == 16 || length == 24 || length == 32 +} + // Ensure that AESImportParams implements the KeyImporter interface. var _ KeyImporter = &AESImportParams{} diff --git a/webcrypto/algorithm.go b/webcrypto/algorithm.go index 1ce0e3a..9fbc67e 100644 --- a/webcrypto/algorithm.go +++ b/webcrypto/algorithm.go @@ -187,3 +187,9 @@ func isAesAlgorithm(algorithmName string) bool { func isHashAlgorithm(algorithmName string) bool { return algorithmName == SHA1 || algorithmName == SHA256 || algorithmName == SHA384 || algorithmName == SHA512 } + +// hasAlg an internal interface that helps us to identify +// if a given object has an algorithm method. +type hasAlg interface { + alg() string +} diff --git a/webcrypto/hash.go b/webcrypto/hash.go index cedd4f1..87e7634 100644 --- a/webcrypto/hash.go +++ b/webcrypto/hash.go @@ -23,3 +23,9 @@ func getHashFn(name string) (func() hash.Hash, bool) { return nil, false } } + +// hasHash an internal interface that helps us to identify +// if a given object has a hash method. +type hasHash interface { + hash() string +} diff --git a/webcrypto/hmac.go b/webcrypto/hmac.go index 1150a2a..37d5703 100644 --- a/webcrypto/hmac.go +++ b/webcrypto/hmac.go @@ -30,6 +30,10 @@ type HMACKeyGenParams struct { Length null.Int `js:"length"` } +func (hkgp HMACKeyGenParams) hash() string { + return hkgp.Hash.Name +} + // newHMACKeyGenParams creates a new HMACKeyGenParams object, from the normalized // algorithm, and the params parameters passed by the user. // @@ -132,7 +136,7 @@ func (hkgp *HMACKeyGenParams) GenerateKey( key := &CryptoKey{Type: SecretCryptoKeyType, handle: randomKey} // 6. - algorithm := HMACKeyAlgorithm{} + algorithm := &HMACKeyAlgorithm{} // 7. algorithm.Name = HMAC @@ -169,7 +173,11 @@ type HMACKeyAlgorithm struct { Length int64 `js:"length"` } -func exportHMACKey(ck *CryptoKey, format KeyFormat) ([]byte, error) { +func (hka HMACKeyAlgorithm) hash() string { + return hka.Hash.Name +} + +func exportHMACKey(ck *CryptoKey, format KeyFormat) (interface{}, error) { // 1. if ck.handle == nil { return nil, NewError(OperationError, "key data is not accessible") @@ -185,6 +193,13 @@ func exportHMACKey(ck *CryptoKey, format KeyFormat) ([]byte, error) { switch format { case RawKeyFormat: return bits, nil + case JwkKeyFormat: + m, err := exportSymmetricJWK(ck) + if err != nil { + return nil, NewError(ImplementationError, err.Error()) + } + + return m, nil default: // FIXME: note that we do not support JWK format, yet #37. return nil, NewError(NotSupportedError, "unsupported key format "+format) @@ -219,6 +234,12 @@ type HMACImportParams struct { Length null.Int `js:"length"` } +var _ hasHash = (*HMACImportParams)(nil) + +func (hip HMACImportParams) hash() string { + return hip.Hash.Name +} + // newHMACImportParams creates a new HMACImportParams object from the given // algorithm and params objects. func newHMACImportParams(rt *goja.Runtime, normalized Algorithm, params goja.Value) (*HMACImportParams, error) { @@ -277,14 +298,19 @@ func (hip *HMACImportParams) ImportKey( } // 3. - var hash KeyAlgorithm + if format != RawKeyFormat && format != JwkKeyFormat { + return nil, NewError(NotSupportedError, "unsupported key format "+format) + } + + hash := KeyAlgorithm{Algorithm{Name: hip.Hash.Name}} // 4. - switch format { - case RawKeyFormat: - hash = KeyAlgorithm{Algorithm{Name: hip.Hash.Name}} - default: - return nil, NewError(NotSupportedError, "unsupported key format "+format) + if format == JwkKeyFormat { + var err error + keyData, err = extractSymmetricJWK(keyData) + if err != nil { + return nil, NewError(DataError, err.Error()) + } } // 5. 6. diff --git a/webcrypto/jwk.go b/webcrypto/jwk.go new file mode 100644 index 0000000..4252fc0 --- /dev/null +++ b/webcrypto/jwk.go @@ -0,0 +1,91 @@ +package webcrypto + +import ( + "encoding/json" + "errors" + "fmt" + + "github.com/lestrrat-go/jwx/v2/jwk" +) + +// JsonWebKey represents a JSON Web Key (JsonWebKey) key. +type JsonWebKey map[string]interface{} //nolint:stylecheck,revive // we name this type JsonWebKey to match the spec + +// Set sets a key-value pair in the JWK. +func (jwk *JsonWebKey) Set(key string, value interface{}) { + (*jwk)[key] = value +} + +// extractSymmetricJWK extracts the symmetric key from a given JWK key (JSON data). +func extractSymmetricJWK(jsonKeyData []byte) ([]byte, error) { + key, err := jwk.ParseKey(jsonKeyData) + if err != nil { + return nil, fmt.Errorf("failed to parse input as JWK key: %w", err) + } + + // check if the key is a symmetric key + sk, ok := key.(jwk.SymmetricKey) + if !ok { + return nil, errors.New("input isn't a valid JWK symmetric key") + } + + return sk.Octets(), nil +} + +// exportSymmetricJWK exports a symmetric key as a map of JWK key parameters. +func exportSymmetricJWK(key *CryptoKey) (*JsonWebKey, error) { + rawKey, ok := key.handle.([]byte) + if !ok { + return nil, errors.New("key's handle isn't a byte slice") + } + + sk, err := jwk.FromRaw(rawKey) + if err != nil { + return nil, fmt.Errorf("failed to create JWK key: %w", err) + } + + // we do marshal and unmarshal to get the map of JWK key parameters + // where all standard parameters are present, a proper marshaling is done + m, err := json.Marshal(sk) + if err != nil { + return nil, fmt.Errorf("failed to marshal JWK key: %w", err) + } + + // wrap result into the object that is expected to be returned + exported := &JsonWebKey{} + err = json.Unmarshal(m, exported) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal JWK key: %w", err) + } + + exported.Set("ext", key.Extractable) + exported.Set("key_ops", key.Usages) + + algV, err := extractAlg(key.Algorithm, len(rawKey)) + if err != nil { + return nil, fmt.Errorf("failed to extract algorithm: %w", err) + } + exported.Set("alg", algV) + + return exported, nil +} + +func extractAlg(inAlg any, keyLen int) (string, error) { + switch alg := inAlg.(type) { + case hasHash: + v := alg.hash() + if len(v) < 4 { + return "", errors.New("length of hash algorithm is less than 4: " + v) + } + return "HS" + v[4:], nil + case hasAlg: + v := alg.alg() + if len(v) < 4 { + return "", errors.New("length of named algorithm is less than 4: " + v) + } + + return fmt.Sprintf("A%d%s", (8 * keyLen), v[4:]), nil + default: + return "", fmt.Errorf("unsupported algorithm: %v", inAlg) + } +} diff --git a/webcrypto/subtle_crypto.go b/webcrypto/subtle_crypto.go index 4d5f443..e951216 100644 --- a/webcrypto/subtle_crypto.go +++ b/webcrypto/subtle_crypto.go @@ -2,6 +2,7 @@ package webcrypto import ( "crypto/hmac" + "encoding/json" "errors" "fmt" @@ -621,8 +622,6 @@ func (sc *SubtleCrypto) DeriveBits(algorithm goja.Value, baseKey goja.Value, len // `ALGORITHM` is the name of the algorithm. // - for PBKDF2: pass the string "PBKDF2" // - for HKDF: pass the string "HKDF" -// -// TODO @oleiade: implement support for JWK format func (sc *SubtleCrypto) ImportKey( format KeyFormat, keyData goja.Value, @@ -633,14 +632,30 @@ func (sc *SubtleCrypto) ImportKey( rt := sc.vu.Runtime() promise, resolve, reject := promises.New(sc.vu) + var keyBytes []byte + // 2. - ab, err := exportArrayBuffer(rt, keyData) - if err != nil { - reject(err) + switch format { + case RawKeyFormat: + ab, err := exportArrayBuffer(rt, keyData) + if err != nil { + reject(err) + return promise + } + + keyBytes = make([]byte, len(ab)) + copy(keyBytes, ab) + case JwkKeyFormat: + var err error + keyBytes, err = json.Marshal(keyData.Export()) + if err != nil { + reject(NewError(ImplementationError, "wrong keyData format for JWK format: "+err.Error())) + return promise + } + default: + reject(NewError(ImplementationError, "unsupported format "+format)) return promise } - keyBytes := make([]byte, len(ab)) - copy(keyBytes, ab) // 3. normalized, err := normalizeAlgorithm(rt, algorithm, OperationIdentifierImportKey) @@ -700,8 +715,6 @@ func (sc *SubtleCrypto) ImportKey( // // The `format` parameter identifies the format of the key data. // The `key` parameter is the key to export, as a CryptoKey object. -// -// TODO @oleiade: implement support for JWK format func (sc *SubtleCrypto) ExportKey(format KeyFormat, key goja.Value) *goja.Promise { rt := sc.vu.Runtime() promise, resolve, reject := promises.New(sc.vu) @@ -719,7 +732,9 @@ func (sc *SubtleCrypto) ExportKey(format KeyFormat, key goja.Value) *goja.Promis return promise } - keyAlgorithmName := key.ToObject(rt).Get("algorithm").ToObject(rt).Get("name").String() + inputAlgorithm := key.ToObject(rt).Get("algorithm").ToObject(rt) + + keyAlgorithmName := inputAlgorithm.Get("name").String() if algorithm.Name != keyAlgorithmName { reject(NewError(InvalidAccessError, "algorithm name does not match key algorithm name")) return promise @@ -738,7 +753,7 @@ func (sc *SubtleCrypto) ExportKey(format KeyFormat, key goja.Value) *goja.Promis return } - var result []byte + var result interface{} var err error switch keyAlgorithmName { @@ -759,7 +774,18 @@ func (sc *SubtleCrypto) ExportKey(format KeyFormat, key goja.Value) *goja.Promis return } - resolve(rt.NewArrayBuffer(result)) + if format != RawKeyFormat { + resolve(result) + return + } + + b, ok := result.([]byte) + if !ok { + reject(NewError(ImplementationError, "for "+format+" []byte expected as result")) + return + } + + resolve(rt.NewArrayBuffer(b)) }() return promise diff --git a/webcrypto/test_setup.go b/webcrypto/test_setup.go index abcec9a..cd2b000 100644 --- a/webcrypto/test_setup.go +++ b/webcrypto/test_setup.go @@ -11,6 +11,7 @@ import ( "github.com/dop251/goja" "github.com/stretchr/testify/require" + k6encoding "go.k6.io/k6/js/modules/k6/encoding" "go.k6.io/k6/js/modulestest" ) @@ -58,6 +59,12 @@ func newConfiguredRuntime(t testing.TB) *modulestest.Runtime { err = runtime.VU.Runtime().Set("crypto", m.Exports().Named["crypto"]) require.NoError(t, err) + // we define the btoa function in the goja runtime + // so that the Web Platform tests can use it. + encodingModule := k6encoding.New().NewModuleInstance(runtime.VU) + err = runtime.VU.Runtime().Set("btoa", encodingModule.Exports().Named["b64encode"]) + require.NoError(t, err) + _, err = runtime.VU.Runtime().RunString(initGlobals) require.NoError(t, err) diff --git a/webcrypto/tests/import_export/symmetric.js b/webcrypto/tests/import_export/symmetric.js index 9b4ca3c..f20dd74 100644 --- a/webcrypto/tests/import_export/symmetric.js +++ b/webcrypto/tests/import_export/symmetric.js @@ -11,7 +11,6 @@ // Test importKey and exportKey for non-PKC algorithms. Only "happy paths" are // currently tested - those where the operation should succeed. - var subtle = crypto.subtle; // keying material for algorithms that can use any bit string. @@ -25,25 +24,15 @@ var rawKeyData = [ // combinations of algorithms, usages, parameters, and formats to test var testVectors = [ - {name: "AES-CTR", legalUsages: ["encrypt", "decrypt"], extractable: [true, false], formats: ["raw"]}, - {name: "AES-CBC", legalUsages: ["encrypt", "decrypt"], extractable: [true, false], formats: ["raw"]}, - {name: "AES-GCM", legalUsages: ["encrypt", "decrypt"], extractable: [true, false], formats: ["raw"]}, - {name: "HMAC", hash: "SHA-1", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw"]}, - {name: "HMAC", hash: "SHA-256", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw"]}, - {name: "HMAC", hash: "SHA-384", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw"]}, - {name: "HMAC", hash: "SHA-512", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw"]}, - - // FIXME: uncomment when other symmetric algorithms, and jwk formats, are supported - // Plus, replace the above entries with their commented-out versions. - // {name: "AES-CTR", legalUsages: ["encrypt", "decrypt"], extractable: [true, false], formats: ["raw", "jwk"]}, - // {name: "AES-CBC", legalUsages: ["encrypt", "decrypt"], extractable: [true, false], formats: ["raw", "jwk"]}, - // {name: "AES-GCM", legalUsages: ["encrypt", "decrypt"], extractable: [true, false], formats: ["raw", "jwk"]}, + {name: "AES-CTR", legalUsages: ["encrypt", "decrypt"], extractable: [true, false], formats: ["raw", "jwk"]}, + {name: "AES-CBC", legalUsages: ["encrypt", "decrypt"], extractable: [true, false], formats: ["raw", "jwk"]}, + {name: "AES-GCM", legalUsages: ["encrypt", "decrypt"], extractable: [true, false], formats: ["raw", "jwk"]}, // {name: "AES-KW", legalUsages: ["wrapKey", "unwrapKey"], extractable: [true, false], formats: ["raw", "jwk"]}, - // {name: "HMAC", hash: "SHA-1", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw", "jwk"]}, - // {name: "HMAC", hash: "SHA-256", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw", "jwk"]}, - // {name: "HMAC", hash: "SHA-384", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw", "jwk"]}, - // {name: "HMAC", hash: "SHA-512", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw", "jwk"]}, + {name: "HMAC", hash: "SHA-1", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw", "jwk"]}, + {name: "HMAC", hash: "SHA-256", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw", "jwk"]}, + {name: "HMAC", hash: "SHA-384", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw", "jwk"]}, + {name: "HMAC", hash: "SHA-512", legalUsages: ["sign", "verify"], extractable: [false], formats: ["raw", "jwk"]}, // {name: "HKDF", legalUsages: ["deriveBits", "deriveKey"], extractable: [false], formats: ["raw"]}, // {name: "PBKDF2", legalUsages: ["deriveBits", "deriveKey"], extractable: [false], formats: ["raw"]} ]; @@ -168,6 +157,7 @@ function byteArrayToUnpaddedBase64(byteArray){ for (var i=0; i