Skip to content

Commit

Permalink
Implementation import/export JWK implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
olegbespalov committed Feb 22, 2024
1 parent d8ebd3f commit e284c5e
Show file tree
Hide file tree
Showing 11 changed files with 227 additions and 74 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Expand Up @@ -14,7 +14,7 @@
# Dependency directories (remove the comment below to include it)
# vendor/

./k6
k6

# we use the config from the main k6's repository
# https://github.com/grafana/k6/blob/master/.golangci.yml
Expand Down
2 changes: 1 addition & 1 deletion examples/import_export/import-export-jwk-aes-key.js
Expand Up @@ -25,7 +25,7 @@ import { crypto } from "k6/x/webcrypto";
"AES-CBC",
true, ["encrypt", "decrypt"]
);

console.log("imported: " + JSON.stringify(importedKey));

const exportedAgain = await crypto.subtle.exportKey("jwk", importedKey);
Expand Down
5 changes: 3 additions & 2 deletions go.mod
Expand Up @@ -40,9 +40,10 @@ require (
go.opentelemetry.io/otel/sdk v1.19.0 // indirect
go.opentelemetry.io/otel/trace v1.19.0 // indirect
go.opentelemetry.io/proto/otlp v1.0.0 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.3.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20230711160842-782d3b101e98 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230731193218-e0aa005b6bdf // indirect
Expand Down
11 changes: 6 additions & 5 deletions go.sum
Expand Up @@ -130,7 +130,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.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
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=
Expand Down Expand Up @@ -163,17 +164,17 @@ 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.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
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=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
Expand Down
64 changes: 45 additions & 19 deletions webcrypto/aes.go
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"

"github.com/dop251/goja"
)
Expand All @@ -23,6 +24,10 @@ type AESKeyGenParams struct {
Length bitLength `js:"length"`
}

func (akgp AESKeyGenParams) alg() string {
return akgp.Name
}

// newAESKeyGenParams creates a new AESKeyGenParams object, from the
// normalized algorithm, and the algorithm parameters.
//
Expand Down Expand Up @@ -84,7 +89,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),
}
Expand Down Expand Up @@ -114,10 +119,12 @@ type AESKeyAlgorithm struct {
Length int64 `js:"length"`
}

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")
}
Expand All @@ -135,8 +142,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)
}
}
Expand All @@ -148,6 +162,10 @@ type AESImportParams struct {
Algorithm
}

func (aip AESImportParams) alg() string {
return aip.Name
}

func newAESImportParams(normalized Algorithm) *AESImportParams {
return &AESImportParams{
Algorithm: normalized,
Expand All @@ -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,
Expand All @@ -172,21 +188,31 @@ 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
var (
has128Bits = len(keyData) == 16
has192Bits = len(keyData) == 24
has256Bits = len(keyData) == 32
)

if !has128Bits && !has192Bits && !has256Bits {
return nil, NewError(DataError, fmt.Sprintf("invalid key length %v bytes", len(keyData)))
}

key := &CryptoKey{
Algorithm: AESKeyAlgorithm{
Algorithm: aip.Algorithm,
Expand Down
6 changes: 1 addition & 5 deletions webcrypto/errors.go
@@ -1,9 +1,5 @@
package webcrypto

import (
"fmt"
)

// ErrorName is a type alias for the name of a WebCryptoError.
//
// Note that it is a type alias, and not a binding, so that it is
Expand Down Expand Up @@ -53,7 +49,7 @@ type Error struct {

// Error implements the `error` interface, so WebCryptoError are normal Go errors.
func (e *Error) Error() string {
return fmt.Sprintf(e.Name)
return e.Name + ": " + e.Message
}

// NewError returns a new WebCryptoError with the given name and message.
Expand Down
62 changes: 53 additions & 9 deletions webcrypto/hmac.go
Expand Up @@ -30,6 +30,14 @@ type HMACKeyGenParams struct {
Length null.Int `js:"length"`
}

func (hkgp HMACKeyGenParams) hash() string {
return hkgp.Hash.Name
}

func (hkgp HMACKeyGenParams) alg() string {
return hkgp.Name
}

// newHMACKeyGenParams creates a new HMACKeyGenParams object, from the normalized
// algorithm, and the params parameters passed by the user.
//
Expand Down Expand Up @@ -132,7 +140,7 @@ func (hkgp *HMACKeyGenParams) GenerateKey(
key := &CryptoKey{Type: SecretCryptoKeyType, handle: randomKey}

// 6.
algorithm := HMACKeyAlgorithm{}
algorithm := &HMACKeyAlgorithm{}

// 7.
algorithm.Name = HMAC
Expand Down Expand Up @@ -169,10 +177,26 @@ type HMACKeyAlgorithm struct {
Length int64 `js:"length"`
}

func exportHMACKey(ck *CryptoKey, format KeyFormat) ([]byte, error) {
type hashAlgorithm interface {
hash() string
}

type namedAlgorithm interface {
alg() string
}

func (hka HMACKeyAlgorithm) hash() string {
return hka.Hash.Name
}

func (hka HMACKeyAlgorithm) alg() string {
return hka.Name
}

func exportHMACKey(ck *CryptoKey, format KeyFormat) (interface{}, error) {
// 1.
if ck.handle == nil {
return nil, NewError(OperationError, "key data is not accesible")
return nil, NewError(OperationError, "key data is not accessible")
}

// 2.
Expand All @@ -185,6 +209,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)
Expand Down Expand Up @@ -219,6 +250,14 @@ type HMACImportParams struct {
Length null.Int `js:"length"`
}

func (hip HMACImportParams) hash() string {
return hip.Hash.Name
}

func (hip HMACImportParams) alg() string {
return hip.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) {
Expand Down Expand Up @@ -277,14 +316,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.
Expand Down
64 changes: 64 additions & 0 deletions webcrypto/jwk.go
@@ -0,0 +1,64 @@
package webcrypto

import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
)

// JWK represents a JSON Web Key (JWK) key.
type JWK map[string]interface{}

// Set sets a key-value pair in the JWK.
func (jwk *JWK) 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) {
var key JWK
err := json.Unmarshal(jsonKeyData, &key)
if err != nil {
return nil, fmt.Errorf("failed to parse JWK key: %w", err)
}

k, ok := key["k"]
if !ok || k == "" {
return nil, errors.New("invalid JWK key")
}

kv, ok := k.(string)
if !ok {
return nil, errors.New("invalid JWK key")
}

return base64.RawStdEncoding.DecodeString(kv)
}

// ExportSymmetricJWK exports a symmetric key as a map of JWK key parameters.
func ExportSymmetricJWK(key *CryptoKey) (*JWK, error) {
// currently, handle is key in the form of a byte slice
rawKey, ok := key.handle.([]byte)
if !ok {
return nil, errors.New("key's handle isn't a byte slice")
}

exported := &JWK{
"kty": "oct",
"key_ops": key.Usages,
"ext": key.Extractable,
"k": base64.RawStdEncoding.EncodeToString(rawKey),
}

switch alg := key.Algorithm.(type) {
case hashAlgorithm:
exported.Set("alg", fmt.Sprintf("HS"+alg.hash()[4:]))
case namedAlgorithm:
exported.Set("alg", fmt.Sprintf("A%d%s", (8*len(rawKey)), alg.alg()[4:]))
default:
return nil, errors.New("unsupported algorithm")
}

return exported, nil
}

0 comments on commit e284c5e

Please sign in to comment.