webcrypto

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 25, 2024 License: AGPL-3.0 Imports: 36 Imported by: 4

Documentation

Overview

Package webcrypto exports the webcrypto API.

Index

Constants

View Source
const (
	// RSASsaPkcs1v15 represents the RSA-SHA1 algorithm.
	RSASsaPkcs1v15 = "RSASSA-PKCS1-v1_5"

	// RSAPss represents the RSA-PSS algorithm.
	RSAPss = "RSA-PSS"

	// RSAOaep represents the RSA-OAEP algorithm.
	RSAOaep = "RSA-OAEP"

	// HMAC represents the HMAC algorithm.
	HMAC = "HMAC"

	// AESCtr represents the AES-CTR algorithm.
	AESCtr = "AES-CTR"

	// AESCbc represents the AES-CBC algorithm.
	AESCbc = "AES-CBC"

	// AESGcm represents the AES-GCM algorithm.
	AESGcm = "AES-GCM"

	// AESKw represents the AES-KW algorithm.
	AESKw = "AES-KW"

	// ECDSA represents the ECDSA algorithm.
	ECDSA = "ECDSA"

	// ECDH represents the ECDH algorithm.
	ECDH = "ECDH"
)
View Source
const (
	// SHA1 represents the SHA-1 algorithm.
	SHA1 HashAlgorithmIdentifier = "SHA-1"

	// SHA256 represents the SHA-256 algorithm.
	SHA256 = "SHA-256"

	// SHA384 represents the SHA-384 algorithm.
	SHA384 = "SHA-384"

	// SHA512 represents the SHA-512 algorithm.
	SHA512 = "SHA-512"
)
View Source
const (
	// DataError represents the DataError error.
	DataError = "DataError"

	// ImplementationError represents the ImplementationError error.
	// It is thrown when the error is likely a bug in our implementation.
	ImplementationError = "ImplementationError"

	// InvalidAccessError represents the InvalidAccessError error.
	InvalidAccessError = "InvalidAccessError"

	// NotSupportedError represents the NotSupportedError error.
	NotSupportedError ErrorName = "NotSupportedError"

	// OperationError represents the OperationError error.
	OperationError = "OperationError"

	// SyntaxError represents the SyntaxError error.
	SyntaxError = "SyntaxError"

	// TypeMismatchError represents the TypeMismatchError error.
	TypeMismatchError = "TypeMismatchError"

	// TypeError represents the TypeError error.
	TypeError = "TypeError"

	// QuotaExceededError is the error thrown if the byteLength of a typedArray
	// exceeds 65,536.
	QuotaExceededError = "QuotaExceededError"
)
View Source
const (
	// ArrayBufferConstructor is the name of the ArrayBufferConstructor constructor
	ArrayBufferConstructor JSType = "ArrayBuffer"

	// DataViewConstructor is the name of the DataView constructor
	DataViewConstructor = "DataView"

	// Int8ArrayConstructor is the name of the Int8ArrayConstructor constructor
	Int8ArrayConstructor = "Int8Array"

	// Uint8ArrayConstructor is the name of the Uint8ArrayConstructor constructor
	Uint8ArrayConstructor = "Uint8Array"

	// Uint8ClampedArrayConstructor is the name of the Uint8ClampedArrayConstructor constructor
	Uint8ClampedArrayConstructor = "Uint8ClampedArray"

	// Int16ArrayConstructor is the name of the Int16ArrayConstructor constructor
	Int16ArrayConstructor = "Int16Array"

	// Uint16ArrayConstructor is the name of the Uint16ArrayConstructor constructor
	Uint16ArrayConstructor = "Uint16Array"

	// Int32ArrayConstructor is the name of the Int32ArrayConstructor constructor
	Int32ArrayConstructor = "Int32Array"

	// Uint32ArrayConstructor is the name of the Uint32ArrayConstructor constructor
	Uint32ArrayConstructor = "Uint32Array"

	// Float32ArrayConstructor is the name of the Float32ArrayConstructor constructor
	Float32ArrayConstructor = "Float32Array"

	// Float64ArrayConstructor is the name of the Float64ArrayConstructor constructor
	Float64ArrayConstructor = "Float64Array"

	// BigInt64ArrayConstructor is the name of the BigInt64ArrayConstructor constructor
	BigInt64ArrayConstructor = "BigInt64Array"

	// BigUint64ArrayConstructor is the name of the BigUint64ArrayConstructor constructor
	BigUint64ArrayConstructor = "BigUint64Array"
)
View Source
const (
	// JWKECKeyType represents the elliptic curve key type.
	JWKECKeyType = "EC"

	// JWKOctKeyType represents the symmetric key type.
	JWKOctKeyType = "oct"
)

Variables

View Source
var (
	// ErrInvalidBlockSize is returned when the given block size is invalid.
	ErrInvalidBlockSize = errors.New("invalid block size")

	// ErrInvalidPkcs7Data is returned when the given data is invalid.
	ErrInvalidPkcs7Data = errors.New("invalid PKCS7 data")
)

Functions

func CompileFile

func CompileFile(base, name string) (*goja.Program, error)

CompileFile compiles a javascript file as a goja.Program.

func IsEllipticCurve

func IsEllipticCurve(name string) bool

IsEllipticCurve returns true if the given string is a valid EllipticCurveKind, false otherwise.

func IsInstanceOf

func IsInstanceOf(rt *goja.Runtime, v goja.Value, instanceOf ...JSType) bool

IsInstanceOf returns true if the given value is an instance of the given constructor This uses the technique described in https://github.com/dop251/goja/issues/379#issuecomment-1164441879

func IsTypedArray

func IsTypedArray(rt *goja.Runtime, v goja.Value) bool

IsTypedArray returns true if the given value is an instance of a Typed Array

func ToBytes

func ToBytes(data interface{}) ([]byte, error)

ToBytes tries to return a byte slice from compatible types.

Types

type AESCBCParams

type AESCBCParams struct {
	Algorithm

	// Name should be set to AES-CBC.
	Name string `js:"name"`

	// Iv holds (an ArrayBuffer, a TypedArray, or a DataView) the initialization vector.
	// Must be 16 bytes, unpredictable, and preferably cryptographically random.
	// However, it need not be secret (for example, it may be transmitted unencrypted along with the ciphertext).
	Iv []byte `js:"iv"`
}

AESCBCParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.Encrypt`, `SubtleCrypto.Decrypt`, `SubtleCrypto.WrapKey`, or `SubtleCrypto.UnwrapKey`, when using the AES-CBC algorithm.

As defined in the specification.

func (*AESCBCParams) Decrypt

func (acp *AESCBCParams) Decrypt(ciphertext []byte, key CryptoKey) ([]byte, error)

Decrypt decrypts the given ciphertext using the AES-CBC algorithm, and returns the plaintext. Implements the WebCryptoAPI's `decrypt` method's specification for the AES-CBC algorithm.

func (*AESCBCParams) Encrypt

func (acp *AESCBCParams) Encrypt(plaintext []byte, key CryptoKey) ([]byte, error)

Encrypt encrypts the given plaintext using the AES-CBC algorithm, and returns the ciphertext. Implements the WebCryptoAPI `encrypt` method's specification for the AES-CBC algorithm.

type AESCTRParams

type AESCTRParams struct {
	Algorithm

	// Counter holds (an ArrayBuffer, a TypedArray, or a DataView) the initial value of the counter block.
	// This must be 16 bytes long (the AES block size). The rightmost length bits of this block are used
	// for the counter, and the rest is used for the nonce.
	//
	// For example, if length is set to 64, then the first half of counter is
	// the nonce and the second half is used for the counter.
	Counter []byte `js:"counter"`

	// Length holds (a Number) the number of bits in the counter block that are used for the actual counter.
	// The counter must be big enough that it doesn't wrap: if the message is n blocks and the counter is m bits long, then
	// the following must be true: n <= 2^m.
	//
	// The NIST SP800-38A standard, which defines CTR, suggests that the counter should occupy half of the counter
	// block (see Appendix B.2), so for AES it would be 64.
	Length int `js:"length"`
}

AESCTRParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.Encrypt`, `SubtleCrypto.Decrypt`, `SubtleCrypto.WrapKey`, or `SubtleCrypto.UnwrapKey`, when using the AES-CTR algorithm.

As defined in the specification.

func (*AESCTRParams) Decrypt

func (acp *AESCTRParams) Decrypt(ciphertext []byte, key CryptoKey) ([]byte, error)

Decrypt decrypts the given ciphertext using the AES-CTR algorithm, and returns the plaintext. Implements the WebCryptoAPI's `decrypt` method's specification for the AES-CTR algorithm.

func (*AESCTRParams) Encrypt

func (acp *AESCTRParams) Encrypt(plaintext []byte, key CryptoKey) ([]byte, error)

Encrypt encrypts the given plaintext using the AES-CTR algorithm, and returns the ciphertext. Implements the WebCryptoAPI's `encrypt` method's specification for the AES-CTR algorithm.

type AESGCMParams

type AESGCMParams struct {
	Algorithm

	// Iv holds (an ArrayBuffer, a TypedArray, or a DataView) with the initialization vector.
	// This must be unique for every encryption operation carried out with a given key.
	//
	// Put another way: never reuse an IV with the same key.
	// The AES-GCM specification recommends that the IV should be 96 bits long, and
	// typically contains bits from a random number generator.
	//
	// Section 8.2 of the specification outlines methods for constructing IVs.
	// Note that the IV does not have to be secret, just unique: so it is OK, for example, to
	// transmit it in the clear alongside the encrypted message.
	Iv []byte `js:"iv"`

	// AdditionalData (an ArrayBuffer, a TypedArray, or a DataView) contains additional data that will
	// not be encrypted but will be authenticated along with the encrypted data.
	//
	// If additionalData is given here then the same data must be given in the corresponding call
	// to decrypt(): if the data given to the decrypt() call does not match the original data, the
	// decryption will throw an exception.
	// This gives you a way to authenticate associated data without having to encrypt it.
	//
	// The bit length of additionalData must be smaller than 2^64 - 1.
	//
	// The additionalData property is optional and may be omitted without compromising the
	// security of the encryption operation.
	AdditionalData []byte `js:"additionalData"`

	// TagLength (a Number) determines the size in bits of the authentication tag generated in
	// the encryption operation and used for authentication in the corresponding decryption.
	//
	// According to the Web Crypto specification this must have one of the
	// following values: 32, 64, 96, 104, 112, 120, or 128.
	// The AES-GCM specification recommends that it should be 96, 104, 112, 120 or 128, although
	// 32 or 64 bits may be acceptable
	// in some applications: Appendix C of the specification provides additional guidance here.
	//
	// tagLength is optional and defaults to 128 if it is not specified.
	TagLength bitLength `js:"tagLength"`
}

AESGCMParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.Encrypt`, `SubtleCrypto.Decrypt`, `SubtleCrypto.WrapKey`, or `SubtleCrypto.UnwrapKey`, when using the AES-GCM algorithm. As defined in the specification.

func (*AESGCMParams) Decrypt

func (agp *AESGCMParams) Decrypt(ciphertext []byte, key CryptoKey) ([]byte, error)

Decrypt decrypts the given ciphertext using the AES-GCM algorithm, and returns the plaintext. Implements the WebCryptoAPI's `decrypt` method's specification for the AES-GCM algorithm.

func (*AESGCMParams) Encrypt

func (agp *AESGCMParams) Encrypt(plaintext []byte, key CryptoKey) ([]byte, error)

Encrypt encrypts the given plaintext using the AES-GCM algorithm, and returns the ciphertext. Implements the WebCryptoAPI's `encrypt` method's specification for the AES-GCM algorithm.

type AESImportParams

type AESImportParams struct {
	Algorithm
}

AESImportParams is an internal placeholder struct for AES import parameters. Although not described by the specification, we define it to be able to implement our internal KeyImporter interface.

func (*AESImportParams) ImportKey

func (aip *AESImportParams) ImportKey(
	format KeyFormat,
	keyData []byte,
	keyUsages []CryptoKeyUsage,
) (*CryptoKey, error)

ImportKey imports an AES key from its raw representation. It implements the KeyImporter interface.

type AESKeyAlgorithm

type AESKeyAlgorithm struct {
	Algorithm

	Length int64 `js:"length"`
}

AESKeyAlgorithm is the algorithm for AES keys as defined in the specification.

type AESKeyGenParams

type AESKeyGenParams struct {
	Algorithm

	// The length, in bits, of the key.
	Length bitLength `js:"length"`
}

AESKeyGenParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.generateKey`, when generating an AES key: that is, when the algorithm is identified as any of AES-CBC, AES-CTR, AES-GCM, or AES-KW.

func (*AESKeyGenParams) GenerateKey

func (akgp *AESKeyGenParams) GenerateKey(
	extractable bool,
	keyUsages []CryptoKeyUsage,
) (CryptoKeyGenerationResult, error)

GenerateKey generates a new AES key, according to the algorithm described in the specification.

type AESKwParams

type AESKwParams struct {
	// Name should be set to AlgorithmKindAesKw.
	Name AlgorithmIdentifier
}

AESKwParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.Encrypt`, `SubtleCrypto.Decrypt`, `SubtleCrypto.WrapKey`, or `SubtleCrypto.UnwrapKey`, when using the AES-KW algorithm.

type Algorithm

type Algorithm struct {
	Name AlgorithmIdentifier `js:"name"`
}

Algorithm represents

type AlgorithmIdentifier

type AlgorithmIdentifier = string

AlgorithmIdentifier represents the name of an algorithm. As defined by the specification

Note that it is defined as an alias of string, instead of a dedicated type, to ensure it is handled as a string by goja.

type Crypto

type Crypto struct {
	Subtle    *SubtleCrypto `js:"subtle"`
	CryptoKey *CryptoKey    `js:"CryptoKey"`
	// contains filtered or unexported fields
}

Crypto represents the Crypto interface of the Web Crypto API.

func (*Crypto) GetRandomValues

func (c *Crypto) GetRandomValues(typedArray goja.Value) goja.Value

GetRandomValues lets you get cryptographically strong random values. As defined by the Web Crypto API's Crypto.getRandomValues() method [specifications].

Do not generate keys using the getRandomValues method. Use the generateKey method instead.

The array given as the parameter is filled with random numbers (random in its cryptographic sense, not in its statistical sense).

To guarantee enough performance, this implementation is not using a truly random number generator, but is using a pseudo-random number generator seeded with a value with enough entropy. We are using the golang crypto/rand package, which uses the operating system's random number generator.

func (*Crypto) RandomUUID

func (c *Crypto) RandomUUID() string

RandomUUID returns a RFC4122 compliant v4 UUID string.

It implements the Web Crypto API's Crypto.randomUUID() method, as specified in Web Crypto API's specification Level 10, section 10.1.2. The UUID is generated using a cryptographically secure random number generator.

type CryptoKey

type CryptoKey struct {
	// Type holds the type of the key.
	Type CryptoKeyType `js:"type"`

	// Extractable indicates whether or not the key may be extracted
	// using `SubtleCrypto.ExportKey` or `SubtleCrypto.WrapKey`.
	//
	// If the value is `true`, the key may be extracted.
	// If the value is `false`, the key may not be extracted, and
	// `SubtleCrypto.exportKey` and `SubtleCrypto.wrapKey` will fail.
	Extractable bool `js:"extractable"`

	// By the time we access the Algorithm field of CryptoKey, we
	// generally already know what type of algorithm it is, and are
	// really looking to access the specific attributes of that algorithm.
	// Thus, the generic parameter type helps us manipulate the
	// `CryptoKey` type without having to cast the `Algorithm` field.
	Algorithm any `js:"algorithm"`

	// Usages holds the key usages for which this key can be used.
	Usages []CryptoKeyUsage `js:"usages"`
	// contains filtered or unexported fields
}

CryptoKey represents a cryptographic key obtained from one of the SubtleCrypto methods `SubtleCrypto.generateKey`, `SubtleCrypto.DeriveKey`, `SubtleCrypto.ImportKey`, or `SubtleCrypto.UnwrapKey`.

func (*CryptoKey) ContainsUsage

func (ck *CryptoKey) ContainsUsage(usage CryptoKeyUsage) bool

ContainsUsage returns true if the key contains the specified usage.

func (*CryptoKey) IsKeyPair added in v0.3.0

func (ck *CryptoKey) IsKeyPair() bool

IsKeyPair .

func (*CryptoKey) ResolveCryptoKey added in v0.3.0

func (ck *CryptoKey) ResolveCryptoKey() (*CryptoKey, error)

ResolveCryptoKey returns the underlying CryptoKey.

func (*CryptoKey) ResolveCryptoKeyPair added in v0.3.0

func (ck *CryptoKey) ResolveCryptoKeyPair() (*CryptoKeyPair, error)

ResolveCryptoKeyPair returns an error since the underlying type is not a CryptoKeyPair.

func (*CryptoKey) Validate added in v0.3.0

func (ck *CryptoKey) Validate() error

Validate checks if the key is valid.

type CryptoKeyGenerationResult added in v0.3.0

type CryptoKeyGenerationResult interface {
	// IsKeyPair returns true if the result is a key pair, false otherwise.
	IsKeyPair() bool

	// ResolveCryptoKeyPair returns the underlying CryptoKeyPair, if the result is a key pair, error otherwise.
	ResolveCryptoKeyPair() (*CryptoKeyPair, error)

	// ResolveCryptoKey returns the underlying CryptoKey, if the result is a key, error otherwise.
	ResolveCryptoKey() (*CryptoKey, error)
}

CryptoKeyGenerationResult represents the result of a key generation operation.

type CryptoKeyPair

type CryptoKeyPair struct {
	// PrivateKey holds the private key. For encryption and decryption algorithms,
	// this key is used to decrypt. For signing and verification algorithms it is used to sign.
	PrivateKey *CryptoKey `js:"privateKey"`

	// PublicKey holds the public key. For encryption and decryption algorithms,
	// this key is used to encrypt. For signing and verification algorithms it is used to verify.
	PublicKey *CryptoKey `js:"publicKey"`
}

CryptoKeyPair represents a key pair for an asymmetric cryptography algorithm, also known as a public-key algorithm.

The Private, and Public generic type parameters define the underlying type holding the private, and public key, respectively.

func (*CryptoKeyPair) IsKeyPair added in v0.3.0

func (ckp *CryptoKeyPair) IsKeyPair() bool

IsKeyPair .

func (*CryptoKeyPair) ResolveCryptoKey added in v0.3.0

func (ckp *CryptoKeyPair) ResolveCryptoKey() (*CryptoKey, error)

ResolveCryptoKey returns an error since the underlying type is not a CryptoKey.

func (*CryptoKeyPair) ResolveCryptoKeyPair added in v0.3.0

func (ckp *CryptoKeyPair) ResolveCryptoKeyPair() (*CryptoKeyPair, error)

ResolveCryptoKeyPair returns the underlying CryptoKeyPair.

type CryptoKeyType

type CryptoKeyType = string

CryptoKeyType represents the type of a key.

Note that it is defined as an alias of string, instead of a dedicated type, to ensure it is handled as a string by goja.

const (
	// UnknownCryptoKeyType that we set when we don't know the type of the key.
	UnknownCryptoKeyType CryptoKeyType = "unknown"

	// SecretCryptoKeyType carries the information that a key is a secret key
	// to use with a symmetric algorithm.
	SecretCryptoKeyType CryptoKeyType = "secret"

	// PrivateCryptoKeyType carries the information that a key is the private half
	// of an asymmetric key pair.
	PrivateCryptoKeyType CryptoKeyType = "private"

	// PublicCryptoKeyType carries the information that a key is the public half
	// of an asymmetric key pair.
	PublicCryptoKeyType CryptoKeyType = "public"
)

type CryptoKeyUsage

type CryptoKeyUsage = string

CryptoKeyUsage represents the usage of a key.

Note that it is defined as an alias of string, instead of a dedicated type, to ensure it is handled as a string by goja.

const (
	// EncryptCryptoKeyUsage indicates that the key may be used to encrypt messages.
	EncryptCryptoKeyUsage CryptoKeyUsage = "encrypt"

	// DecryptCryptoKeyUsage indicates that the key may be used to decrypt messages.
	DecryptCryptoKeyUsage CryptoKeyUsage = "decrypt"

	// SignCryptoKeyUsage indicates that the key may be used to sign messages.
	SignCryptoKeyUsage CryptoKeyUsage = "sign"

	// VerifyCryptoKeyUsage indicates that the key may be used to verify signatures.
	VerifyCryptoKeyUsage CryptoKeyUsage = "verify"

	// DeriveKeyCryptoKeyUsage indicates that the key may be used to derive a new key.
	DeriveKeyCryptoKeyUsage CryptoKeyUsage = "deriveKey"

	// DeriveBitsCryptoKeyUsage indicates that the key may be used to derive bits.
	DeriveBitsCryptoKeyUsage CryptoKeyUsage = "deriveBits"

	// WrapKeyCryptoKeyUsage indicates that the key may be used to wrap another key.
	WrapKeyCryptoKeyUsage CryptoKeyUsage = "wrapKey"

	// UnwrapKeyCryptoKeyUsage indicates that the key may be used to unwrap another key.
	UnwrapKeyCryptoKeyUsage CryptoKeyUsage = "unwrapKey"
)

func UsageIntersection

func UsageIntersection(a, b []CryptoKeyUsage) []CryptoKeyUsage

UsageIntersection returns the intersection of two slices of CryptoKeyUsage.

It implements the algorithm described in the specification to determine the intersection of two slices of CryptoKeyUsage.

type Decrypter

type Decrypter interface {
	Decrypt(ciphertext []byte, key CryptoKey) ([]byte, error)
}

Decrypter is an interface for decrypting data.

type ECDSAParams

type ECDSAParams struct {
	// Name should be set to AlgorithmKindEcdsa.
	Name AlgorithmIdentifier

	// Hash identifies the name of the digest algorithm to use.
	// You can use any of the following:
	//   * [Sha256]
	//   * [Sha384]
	//   * [Sha512]
	Hash Algorithm
}

The ECDSAParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.Sign` or `SubtleCrypto.Verify“ when using the ECDSA algorithm.

func (*ECDSAParams) Sign added in v0.3.0

func (edsa *ECDSAParams) Sign(key CryptoKey, data []byte) ([]byte, error)

Sign .

func (*ECDSAParams) Verify added in v0.3.0

func (edsa *ECDSAParams) Verify(key CryptoKey, signature []byte, data []byte) (bool, error)

Verify .

type ECKeyGenParams

type ECKeyGenParams struct {
	Algorithm

	// NamedCurve holds (a String) the name of the curve to use.
	// You can use any of the following: CurveKindP256, CurveKindP384, or CurveKindP521.
	NamedCurve EllipticCurveKind
}

ECKeyGenParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.GenerateKey`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as either of AlgorithmKindEcdsa or AlgorithmKindEcdh.

func (*ECKeyGenParams) GenerateKey added in v0.3.0

func (ecgp *ECKeyGenParams) GenerateKey(
	extractable bool,
	keyUsages []CryptoKeyUsage,
) (CryptoKeyGenerationResult, error)

GenerateKey generates a new ECDH/ECDSA key pair, according to the algorithm described in the specification.

type EcKeyAlgorithm added in v0.3.0

type EcKeyAlgorithm struct {
	KeyAlgorithm

	// NamedCurve holds (a String) the name of the elliptic curve to use.
	NamedCurve EllipticCurveKind `js:"namedCurve"`
}

EcKeyAlgorithm is the algorithm for elliptic curve keys as defined in the specification.

type EcKeyImportParams

type EcKeyImportParams struct {
	Algorithm

	// NamedCurve holds (a String) the name of the elliptic curve to use.
	NamedCurve EllipticCurveKind `js:"namedCurve"`
}

EcKeyImportParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.ImportKey` or `SubtleCrypto.UnwrapKey`, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as either of ECDSA or ECDH.

func (*EcKeyImportParams) ImportKey added in v0.3.0

func (e *EcKeyImportParams) ImportKey(
	format KeyFormat,
	keyData []byte,
	_ []CryptoKeyUsage,
) (*CryptoKey, error)

ImportKey imports a key according to the algorithm described in the specification. https://www.w3.org/TR/WebCryptoAPI/#ecdh-operations

type EllipticCurveKind

type EllipticCurveKind string

EllipticCurveKind represents the kind of elliptic curve that is being used.

const (
	// EllipticCurveKindP256 represents the P-256 curve.
	EllipticCurveKindP256 EllipticCurveKind = "P-256"

	// EllipticCurveKindP384 represents the P-384 curve.
	EllipticCurveKindP384 EllipticCurveKind = "P-384"

	// EllipticCurveKindP521 represents the P-521 curve.
	EllipticCurveKindP521 EllipticCurveKind = "P-521"
)

func (EllipticCurveKind) String added in v0.3.0

func (k EllipticCurveKind) String() string

type EncryptDecrypter

type EncryptDecrypter interface {
	Encrypter
	Decrypter
}

EncryptDecrypter is an interface for encrypting and decrypting data.

type Encrypter

type Encrypter interface {
	Encrypt(plaintext []byte, key CryptoKey) ([]byte, error)
}

Encrypter is an interface for encrypting data.

type Error

type Error struct {
	// Name contains one of the strings associated with an error name.
	Name string `js:"name"`

	// Message represents message or description associated with the given error name.
	Message string `js:"message"`
}

Error represents a custom error emitted by the Web Crypto API.

func NewError

func NewError(name, message string) *Error

NewError returns a new WebCryptoError with the given name and message.

func (*Error) Error

func (e *Error) Error() string

Error implements the `error` interface, so WebCryptoError are normal Go errors.

type ErrorName

type ErrorName = string

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 not interpreted as an object by goja.

type From

type From[Input, Output any] interface {
	// From produces an output of type Output from the
	// content of the given input.
	From(Input) (Output, error)
}

From is an interface representing the ability to produce an instance from a given generic input. It is an attempt to create a contract around construction of objects from others.

type HKDFParams

type HKDFParams struct {
	// Name should be set to AlgorithmKindHkdf.
	Name AlgorithmIdentifier

	// Hash should be set to the name of the digest algorithm to use.
	// You can use any of the following:
	//   * [Sha256]
	//   * [Sha384]
	//   * [Sha512]
	Hash AlgorithmIdentifier

	// Salt to use. The HKDF specification states that adding
	// salt "adds significantly to the strength of HKDF".
	// Ideally, the salt is a random or pseudo-random value with
	// the same length as the output of the digest function.
	// Unlike the input key material passed into `SubtleCrypto.DeriveKey`,
	// salt does not need to be kept secret.
	Salt []byte

	// Info holds application-specific contextual information.
	// This is used to bind the derived key to an application or
	// context, and enables you to derive different keys for different
	// contexts while using the same input key material.
	//
	// It's important that this should be independent of the input key material itself.
	// This property is required but may be an empty buffer.
	Info []byte
}

HKDFParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.DeriveKey`, when using the HKDF algorithm.

type HMACImportParams

type HMACImportParams struct {
	Algorithm

	// Hash represents the name of the digest function to use. You can
	// use any of the following: [Sha256], [Sha384],
	// or [Sha512].
	Hash Algorithm `js:"hash"`

	// Length holds (a Number) the length of the key, in bits.
	// If this is omitted, the length of the key is equal to the block size
	// of the hash function you have chosen.
	// Unless you have a good reason to use a different length, omit
	// use the default.
	Length null.Int `js:"length"`
}

HMACImportParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.GenerateKey`, when generating an HMAC key.

func (*HMACImportParams) ImportKey

func (hip *HMACImportParams) ImportKey(
	format KeyFormat,
	keyData []byte,
	keyUsages []CryptoKeyUsage,
) (*CryptoKey, error)

ImportKey imports a key from raw key data. It implements the KeyImporter interface.

type HMACKeyAlgorithm

type HMACKeyAlgorithm struct {
	KeyAlgorithm

	// Hash represents the inner hash function to use.
	Hash KeyAlgorithm `js:"hash"`

	// Length represents he length (in bits) of the key.
	Length int64 `js:"length"`
}

HMACKeyAlgorithm represents the algorithm of an HMAC key.

func (*HMACKeyAlgorithm) HashFn

func (hka *HMACKeyAlgorithm) HashFn() (func() hash.Hash, error)

HashFn returns the hash function to use for the HMAC key.

type HMACKeyGenParams

type HMACKeyGenParams struct {
	Algorithm

	// Hash represents the name of the digest function to use. You can
	// use any of the following: [Sha256], [Sha384],
	// or [Sha512].
	Hash Algorithm `js:"hash"`

	// Length holds (a Number) the length of the key, in bits.
	// If this is omitted, the length of the key is equal to the block size
	// of the hash function you have chosen.
	// Unless you have a good reason to use a different length, omit
	// use the default.
	Length null.Int `js:"length"`
}

HMACKeyGenParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.GenerateKey`, when generating an HMAC key.

func (*HMACKeyGenParams) GenerateKey

func (hkgp *HMACKeyGenParams) GenerateKey(
	extractable bool,
	keyUsages []CryptoKeyUsage,
) (CryptoKeyGenerationResult, error)

GenerateKey generates a new HMAC key.

type HMACSignatureParams

type HMACSignatureParams struct {
	// Name should be set to AlgorithmKindHmac.
	Name AlgorithmIdentifier
}

HMACSignatureParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.Sign`, when using the HMAC algorithm.

type HashAlgorithmIdentifier

type HashAlgorithmIdentifier = AlgorithmIdentifier

HashAlgorithmIdentifier represents the name of a hash algorithm.

Note that it is defined as an alias of string, instead of a dedicated type, to ensure it is handled as a string under the hood by goja.

type JSType

type JSType string

JSType is a string representing a JavaScript type

type JsonWebKey added in v0.2.0

type JsonWebKey map[string]interface{} //nolint:stylecheck,revive // we name this type JsonWebKey to match the spec

JsonWebKey represents a JSON Web Key (JsonWebKey) key.

func (*JsonWebKey) Set added in v0.2.0

func (jwk *JsonWebKey) Set(key string, value interface{})

Set sets a key-value pair in the JWK.

type KeyAlgorithm

type KeyAlgorithm struct {
	Algorithm
}

KeyAlgorithm represents the algorithm used to generate a cryptographic key.

type KeyFormat

type KeyFormat = string

KeyFormat represents the format of a CryptoKey.

Note that it is defined as an alias of string, instead of a dedicated type, to ensure it is handled as a string by goja.

const (
	// RawKeyFormat indicates that the key is in raw format.
	RawKeyFormat KeyFormat = "raw"

	// Pkcs8KeyFormat indicates that the key is in PKCS#8 format.
	Pkcs8KeyFormat KeyFormat = "pkcs8"

	// SpkiKeyFormat indicates that the key is in SubjectPublicKeyInfo format.
	SpkiKeyFormat KeyFormat = "spki"

	// JwkKeyFormat indicates that the key is in JSON Web Key format.
	JwkKeyFormat KeyFormat = "jwk"
)

type KeyGenerator

type KeyGenerator interface {
	GenerateKey(extractable bool, keyUsages []CryptoKeyUsage) (CryptoKeyGenerationResult, error)
}

KeyGenerator is the interface implemented by the algorithms used to generate cryptographic keys.

type KeyImporter

type KeyImporter interface {
	ImportKey(format KeyFormat, keyData []byte, keyUsages []CryptoKeyUsage) (*CryptoKey, error)
}

KeyImporter is the interface implemented by the parameters used to import cryptographic keys.

type KeyLength

type KeyLength = uint16

KeyLength holds the length of the key, in bits.

Note that it is defined as an alias of uint16, instead of a dedicated type, to ensure it is handled as a number by goja.

const (
	// KeyLength128 represents a 128 bits key length.
	KeyLength128 KeyLength = 128

	// KeyLength192 represents a 192 bits key length.
	KeyLength192 KeyLength = 192

	// KeyLength256 represents a 256 bits key length.
	KeyLength256 KeyLength = 256

	// KeyLength384 represents a 384 bits key length.
	KeyLength384 KeyLength = 384

	// KeyLength512 represents a 512 bits key length.
	KeyLength512 KeyLength = 512
)

type ModuleInstance

type ModuleInstance struct {
	// contains filtered or unexported fields
}

ModuleInstance represents an instance of the JS module.

func (*ModuleInstance) Exports

func (mi *ModuleInstance) Exports() modules.Exports

Exports implements the modules.Instance interface and returns the exports of the JS module.

type OperationIdentifier

type OperationIdentifier = string

OperationIdentifier represents the name of an operation.

Note that it is defined as an alias of string, instead of a dedicated type, to ensure it is handled as a string by goja.

const (
	// OperationIdentifierSign represents the sign operation.
	OperationIdentifierSign OperationIdentifier = "sign"

	// OperationIdentifierVerify represents the verify operation.
	OperationIdentifierVerify OperationIdentifier = "verify"

	// OperationIdentifierEncrypt represents the encrypt operation.
	OperationIdentifierEncrypt OperationIdentifier = "encrypt"

	// OperationIdentifierDecrypt represents the decrypt operation.
	OperationIdentifierDecrypt OperationIdentifier = "decrypt"

	// OperationIdentifierDeriveBits represents the deriveBits operation.
	OperationIdentifierDeriveBits OperationIdentifier = "deriveBits"

	// OperationIdentifierDeriveKey represents the deriveKey operation.
	OperationIdentifierDeriveKey OperationIdentifier = "deriveKey"

	// OperationIdentifierWrapKey represents the wrapKey operation.
	OperationIdentifierWrapKey OperationIdentifier = "wrapKey"

	// OperationIdentifierUnwrapKey represents the unwrapKey operation.
	OperationIdentifierUnwrapKey OperationIdentifier = "unwrapKey"

	// OperationIdentifierImportKey represents the importKey operation.
	OperationIdentifierImportKey OperationIdentifier = "importKey"

	// OperationIdentifierExportKey represents the exportKey operation.
	OperationIdentifierExportKey OperationIdentifier = "exportKey"

	// OperationIdentifierGenerateKey represents the generateKey operation.
	OperationIdentifierGenerateKey OperationIdentifier = "generateKey"

	// OperationIdentifierDigest represents the digest operation.
	OperationIdentifierDigest OperationIdentifier = "digest"
)

type PBKDF2Params

type PBKDF2Params struct {
	// Name should be set to AlgorithmKindPbkdf2.
	Name AlgorithmIdentifier

	// FIXME: should also include SHA-1, unfortunately
	// Hash identifies the name of the digest algorithm to use.
	// You can use any of the following:
	//   * [Sha256]
	//   * [Sha384]
	//   * [Sha512]
	Hash AlgorithmIdentifier

	// Salt should hold a random or pseudo-random value of at
	// least 16 bytes. Unlike the input key material passed into
	// `SubtleCrypto.DeriveKey`, salt does not need to be kept secret.
	Salt []byte

	// Iterations the number of times the hash function will be executed
	// in `SubtleCrypto.DeriveKey`. This determines how computationally
	// expensive (that is, slow) the `SubtleCrypto.DeriveKey` operation will be.
	//
	// In this context, slow is good, since it makes it more expensive for an
	// attacker to run a dictionary attack against the keys.
	// The general guidance here is to use as many iterations as possible,
	// subject to keeping an acceptable level of performance for your application.
	Iterations int
}

PBKDF2Params represents the object that should be passed as the algorithm parameter into `SubtleCrypto.DeriveKey`, when using the PBKDF2 algorithm.

type RSAHashedImportParams

type RSAHashedImportParams struct {
	// Name should be set to AlgorithmKindRsassPkcs1v15,
	// AlgorithmKindRsaPss, or AlgorithmKindRsaOaep depending
	// on the algorithm you want to use.
	Name string

	// Hash represents the name of the digest function to use.
	// Note that although you can technically pass SHA-1 here, this is strongly
	// discouraged as it is considered vulnerable.
	Hash AlgorithmIdentifier
}

RSAHashedImportParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.ImportKey` or `SubtleCrypto.UnwrapKey`, when importing any RSA-based key pair: that is, when the algorithm is identified as any of RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP.

type RSAHashedKeyGenParams

type RSAHashedKeyGenParams struct {
	// Name should be set to AlgorithmKindRsassPkcs1v15,
	// AlgorithmKindRsaPss, or AlgorithmKindRsaOaep.
	Name AlgorithmIdentifier

	// ModulusLength holds (a Number) the length of the RSA modulus, in bits.
	// This should be at least 2048. Some organizations are now recommending
	// that it should be 4096.
	ModulusLength int

	// PublicExponent holds (a Uint8Array) the public exponent to use.
	// Unless you have a good reason to use something else, use 65537 here.
	PublicExponent []byte

	// Hash represents the name of the digest function to use. You can
	// use any of the following: DigestKindSha256, DigestKindSha384,
	// or DigestKindSha512.
	Hash string
}

RSAHashedKeyGenParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.GenerateKey`, when generating an RSA key pair.

type RSAOaepParams

type RSAOaepParams struct {
	// Name should be set to "RSA-OAEP"
	Name string

	// Label holds (an ArrayBuffer, a TypedArray, or a DataView) an array of bytes that does not
	// itself need to be encrypted but which should be bound to the ciphertext.
	// A digest of the label is part of the input to the encryption operation.
	//
	// Unless your application calls for a label, you can just omit this argument
	// and it will not affect the security of the encryption operation.
	Label []byte
}

RSAOaepParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.Encrypt`, `SubtleCrypto.Decrypt`, `SubtleCrypto.WrapKey`, or `SubtleCrypto.UnwrapKey`, when using the RSA_OAEP algorithm.

type RSAPssParams

type RSAPssParams struct {
	// Name should be set to AlgorithmKindRsaPss.
	Name AlgorithmIdentifier

	// SaltLength holds (a Number) the length of the random salt to use, in bytes.
	// RFC 3447 says that "typical salt lengths" are either 0 or the length of the output
	// of the digest algorithm selected when this key was generated. For instance,
	// when using the SHA256 digest algorithm, the salt length could be 32.
	SaltLength int
}

RSAPssParams represents the object that should be passed as the algorithm parameter into `SubtleCrypto.Sign` or `SubtleCrypto.Verify`, when using the RSA-PSS algorithm.

type RSASsaPkcs1v15Params

type RSASsaPkcs1v15Params struct {
	// Name should be set to AlgorithmKindRsassaPkcs1v15.
	Name AlgorithmIdentifier
}

RSASsaPkcs1v15Params represents the object that should be passed as the algorithm

type RootModule

type RootModule struct{}

RootModule is the global module instance that will create Client instances for each VU.

func New

func New() *RootModule

New returns a pointer to a new RootModule instance

func (*RootModule) NewModuleInstance

func (*RootModule) NewModuleInstance(vu modules.VU) modules.Instance

NewModuleInstance implements the modules.Module interface and returns a new instance for each VU.

type SignerVerifier added in v0.3.0

type SignerVerifier interface {
	Sign(key CryptoKey, dataToSign []byte) ([]byte, error)
	Verify(key CryptoKey, signature, dataToVerify []byte) (bool, error)
}

SignerVerifier .

type SubtleCrypto

type SubtleCrypto struct {
	// contains filtered or unexported fields
}

SubtleCrypto represents the SubtleCrypto interface of the Web Crypto API.

func (*SubtleCrypto) Decrypt

func (sc *SubtleCrypto) Decrypt(
	algorithm, key, data goja.Value,
) *goja.Promise

Decrypt decrypts some encrypted data.

It takes as arguments a key to decrypt with, some optional extra parameters, and the data to decrypt (also known as "ciphertext").

It returns a Promise which will be fulfilled with the decrypted data (also known as "plaintext").

Note that if the provided `algorithm` is RSA-OAEP, the `key` parameter should hold the `PrivateKey` property of the `CryptoKeyPair`.

The `algorithm` parameter should be one of:

  • an `SubtleCrypto.RSAOaepParams` object
  • an `SubtleCrypto.AESCtrParams` object
  • an `SubtleCrypto.AESCbcParams` object
  • an `SubtleCrypto.AESGcmParams` object

The `key` parameter should be a `CryptoKey` to be used for decryption.

The `data` parameter should contain the data to be decrypted.

func (*SubtleCrypto) DeriveBits

func (sc *SubtleCrypto) DeriveBits(
	algorithm goja.Value,
	baseKey goja.Value,
	length int,
) *goja.Promise

DeriveBits derives an array of bits from a base key.

It takes as its arguments the base key, the derivation algorithm to use, and the length of the bit string to derive. It returns a Promise which will be fulfilled with an ArrayBuffer containing the derived bits.

This method is very similar to `SubtleCrypto.DeriveKey`, except that `SubtleCrypto.DeriveKey` returns a `CryptoKey` object rather than an ArrayBuffer. Essentially `SubtleCrypto.DeriveKey` is composed of `SubtleCrypto.DeriveBits` followed by `SubtleCrypto.ImportKey`.

This function supports the same derivation algorithms as deriveKey(): ECDH, HKDF, and PBKDF2

Note that if the `algorithm` parameter is ECDH, the `baseKey` parameter should be the ECDH private key. Otherwise it should be the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a `CryptoKey` using `SubtleCrypto.ImportKey`.

The `algorithm` parameter should be one of:

  • an `SubtleCrypto.ECDHKeyDeriveParams` object
  • an `SubtleCrypto.HKDFParams` object
  • an `SubtleCrypto.PBKDF2Params` object

The `baseKey` parameter should be a `CryptoKey` object representing the input to the derivation algorithm. If `algorithm` is ECDH, then this will be the ECDH private key. Otherwise it will be the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a `CryptoKey` using `SubtleCrypto.ImportKey`.

The `length` parameter is the number of bits to derive. The number should be a multiple of 8.

func (*SubtleCrypto) DeriveKey

func (sc *SubtleCrypto) DeriveKey(
	algorithm goja.Value,
	baseKey goja.Value,
	derivedKeyAlgorithm goja.Value,
	extractable bool,
	keyUsages []CryptoKeyUsage,
) *goja.Promise

DeriveKey can be used to derive a secret key from a master key.

It takes as arguments some initial key material, the derivation algorithm to use, and the desired properties for the key to derive. It returns a Promise which will be fulfilled with a CryptoKey object representing the new key.

Note that if the `algorithm` parameter is ECDH, the `baseKey` parameter should be a private key. Otherwise, it should be the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a CryptoKey using `SubtleCrypto.ImportKey`.

The `algorithm` parameter should be one of:

  • an `SubtleCrypto.ECDHKeyDeriveParams` object
  • an `SubtleCrypto.HKDFParams` object
  • an `SubtleCrypto.Pbkdf2Params` object

The `baseKey` parameter should be a CryptoKey object representing the input to the derivation algorithm. If `algorithm` is ECDH, then this will be the ECDH private key. Otherwise it will be the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a `SubtleCrypto.CryptoKey` using `SubtleCrypto.ImportKey`.

The `derivedKeyAlgorithm` parameter should be one of:

  • an `SubtleCrypto.HMACKeyGenParams` object
  • For AES-CTR, AES-CBC, AES-GCM, AES-KW: pass an `SubtleCrypto.AESKeyGenParams`

The `extractable` parameter indicates whether it will be possible to export the key using `SubtleCrypto.ExportKey` or `SubtleCrypto.WrapKey`.

The `keyUsages` parameter is an array of strings indicating what the key can be used for.

func (*SubtleCrypto) Digest

func (sc *SubtleCrypto) Digest(algorithm goja.Value, data goja.Value) *goja.Promise

Digest generates a digest of the given data.

A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value.

It takes as its arguments an identifier for the digest algorithm to use and the data to digest. It returns a Promise which will be fulfilled with the digest.

Supported digest algorithms:

  • SHA-1 (not to be used in cryptographic applications)
  • SHA-256
  • SHA-384
  • SHA-512

The `data` parameter should contain the data to be digested.

func (*SubtleCrypto) Encrypt

func (sc *SubtleCrypto) Encrypt(
	algorithm, key, data goja.Value,
) *goja.Promise

Encrypt encrypts data.

It takes as its arguments a key to encrypt with, some algorithm-specific parameters, and the data to encrypt (also known as "plaintext").

It returns a Promise which will be fulfilled with the encrypted data (also known as "ciphertext").

The `algorithm` parameter should be one of:

  • an `SubtleCrypto.RSAOaepParams` object
  • an `SubtleCrypto.AESCtrParams` object
  • an `SubtleCrypto.AESCbcParams` object
  • an`SubtleCrypto.AESGcmParams` object

The `key` parameter should be a `CryptoKey` to be used for encryption.

The `data` parameter should contain the data to be encryption.

func (*SubtleCrypto) ExportKey

func (sc *SubtleCrypto) ExportKey(
	format KeyFormat,
	key goja.Value,
) *goja.Promise

ExportKey exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format.

To export a key, the key must have CryptoKey.extractable set to true.

Keys are not exported in an encrypted format: to encrypt keys when exporting them use the SubtleCrypto.wrapKey() API instead.

It returns A Promise:

  • If format was jwk, then the promise fulfills with a JSON object containing the key.
  • Otherwise the promise fulfills with an ArrayBuffer containing the key.

The `format` parameter identifies the format of the key data. The `key` parameter is the key to export, as a CryptoKey object.

func (*SubtleCrypto) GenerateKey

func (sc *SubtleCrypto) GenerateKey(algorithm goja.Value, extractable bool, keyUsages []CryptoKeyUsage) *goja.Promise

GenerateKey generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).

The generated key will match the algorithm, usages, and extractability given as parameters.

It returns a Promise that fulfills with a `SubtleCrypto.CryptoKey` (for symmetric algorithms) or a `SubtleCrypto.CryptoKeyPair` (for public-key algorithms).

The `algorithm` parameter should be one of:

  • for RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP: pass an `SubtleCrypto.RSAHashedKeyGenParams` object
  • for ECDSA or ECDH: pass an `SubtleCrypto.ECKeyGenParams` object
  • an `SubtleCrypto.HMACKeyGenParams` object
  • for AES-CTR, AES-CBC, AES-GCM, AES-KW: pass an `SubtleCrypto.AESKeyGenParams`

The `extractable` parameter indicates whether it will be possible to export the key using `SubtleCrypto.ExportKey` or `SubtleCrypto.WrapKey`.

The `keyUsages` parameter is an array of strings indicating what the key can be used for.

func (*SubtleCrypto) ImportKey

func (sc *SubtleCrypto) ImportKey(
	format KeyFormat,
	keyData goja.Value,
	algorithm goja.Value,
	extractable bool,
	keyUsages []CryptoKeyUsage,
) *goja.Promise

ImportKey imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API.

It returns a Promise that fulfills with the imported key as a CryptoKey object.

The `format` parameter identifies the format of the key data.

The `keyData` parameter is the key data, in the format specified by the `format` parameter.

The `algorithm` parameter should be one of:

  • for RSASSA-PKCS1-v1_5, RSA-PSS or RSA-OAEP: pass an `SubtleCrypto.RSAHashedImportParams` object
  • for ECDSA or ECDH: pass an `SubtleCrypto.EcKeyImportParams` object
  • an `SubtleCrypto.HMACImportParams` object
  • for AES-CTR, AES-CBC, AES-GCM or AES-KW pass the string identifying the algorithm or an object of the form `{ name: ALGORITHM }`, where `ALGORITHM` is the name of the algorithm.
  • for PBKDF2: pass the string "PBKDF2"
  • for HKDF: pass the string "HKDF"

func (*SubtleCrypto) Sign

func (sc *SubtleCrypto) Sign(algorithm, key, data goja.Value) *goja.Promise

Sign generates a digital signature.

It takes as its arguments a key to sign with, some algorithm-specific parameters, and the data to sign. It returns a Promise which will be fulfilled with the signature.

Note that if the `algorithm` parameter identifies a public-key cryptosystem, the `key` parameter should be a private key.

You can use the corresponding `SubtleCrypto.Verify` method to verify the signature.

The `algorithm` parameter should be one of:

  • the string "RSASSA-PKCS1-v1_5" or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`
  • an `SubtleCrypto.RSAPssParams` object
  • an `SubtleCrypto.EcdsaParams` object
  • the string "HMAC" or an object of the form `{ "name": "HMAC" }`

The `key` parameter should be a `CryptoKey` to be used for signing. Note that if `algorithm` identifies a public-key cryptosystem, this is the private key.

The `data` parameter should contain the data to be signed.

func (*SubtleCrypto) UnwrapKey

func (sc *SubtleCrypto) UnwrapKey(
	format KeyFormat,
	wrappedKey []byte,
	unwrappingKey goja.Value,
	unwrapAlgo goja.Value,
	unwrappedKeyAlgo goja.Value,
	extractable bool,
	keyUsages []CryptoKeyUsage,
) *goja.Promise

UnwrapKey "unwraps" a key.

This means that it takes as its input a key that has been exported and then encrypted (also called "wrapped"). It decrypts the key and then imports it, returning a `CryptoKey` object that can be used in the Web Crypto API.

As with `SubtleCrypto.ImportKey`, you specify the key's import format and other attributes of the key to import details such as whether it is extractable, and which operations it can be used for.

But because `SubtleCrypto.UnwrapKey` also decrypts the key to be imported, you also need to pass in the key that must be used to decrypt it. This is sometimes called the "unwrapping key".

The inverse of `SubtleCrypto.UnwrapKey` is `SubtleCrypto.WrapKey`: while `SubtleCrypto.UnwrapKey` is composed of decrypt + import, `Subtle.WrapKey` is composed of encrypt + export.

It returns a Promise that fulfills with the unwrapped key as a CryptoKey object.

The `format` parameter identifies the format of the key data.

The `wrappedKey` parameter is the key to unwrap.

The `unwrappingKey` parameter is the key to use to decrypt the wrapped key. The key **must** have

the `unwrapKey` usage flag set.

The `unwrapAlgorithm` parameter identifies the algorithm to use to decrypt the wrapped key, and should be one of:

  • an `SubtleCrypto.RSAOaepParams` object
  • an `SubtleCrypto.AesCtrParams` object
  • an `SubtleCrypto.AesCbcParams` object
  • an `SubtleCrypto.AesGcmParams` object
  • for the AES-KW algorithm, pass the string "AES-KW", or an object of the form `{ name: "AES-KW" }`

The `unwrappedKeyAlgorithm` parameter identifies the algorithm to use to import the unwrapped key, and should be one of:

  • for RSASSA-PKCS1-v1_5, RSA-PSS or RSA-OAEP: pass an `SubtleCrypto.RSAHashedImportParams` object
  • for ECDSA or ECDH: pass an `SubtleCrypto.EcKeyImportParams` object
  • for HMAC: pass an `SubtleCrypto.HMACImportParams` object
  • for AES-CTR, AES-CBC, AES-GCM or AES-KW pass the string identifying the algorithm or an object of the form `{ name: ALGORITHM }`, where `ALGORITHM` is the name of the algorithm.

The `extractable` parameter identifies whether the key is extractable.

The `keyUsages` parameter identifies the operations that the key can be used for.

func (*SubtleCrypto) Verify

func (sc *SubtleCrypto) Verify(algorithm, key, signature, data goja.Value) *goja.Promise

Verify verifies a digital signature.

It takes as its arguments a key to verify the signature with, some algorithm-specific parameters, the signature, and the original signed data.

It returns a Promise which will be fulfilled with a boolean value indicating whether the signature is valid.

Note that the `key` parameter should hold the secret key for a symmetric algorithm and the public key for a public-key system.

The `algorithm` parameter should be one of:

  • the string "RSASSA-PKCS1-v1_5" or an object of the form `{ "name": "RSASSA-PKCS1-v1_5" }`
  • an `SubtleCrypto.RSAPssParams` object
  • an `SubtleCrypto.EcdsaParams` object
  • the string "HMAC" or an object of the form `{ "name": "HMAC" }`

The `key` parameter should be a `CryptoKey` to be used for verification. Note that it is the secret key for a symmetric algorithm and the public key for a public-key system.

The `signature` parameter should contain the signature to be verified.

The `data` parameter should contain the original signed data.

func (*SubtleCrypto) WrapKey

func (sc *SubtleCrypto) WrapKey(
	format KeyFormat,
	key goja.Value,
	wrappingKey goja.Value,
	wrapAlgorithm goja.Value,
) *goja.Promise

WrapKey "wraps" a key.

This means that it exports the key in an external, portable format, then encrypts the exported key. Wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network.

As with `SubtleCrypto.ExportKey`, you specify an export format for the key. To export a key, it must have `CryptoKey.Extractable` set to true.

But because `SubtleCrypto.WrapKey“ also encrypts the key to be imported, you also need to pass in the key that must be used to encrypt it. This is sometimes called the "wrapping key".

The inverse of `SubtleCrypto.WrapKey` is `SubtleCrypto.UnwrapKey`: while `SubtleCrypto.WrapKey“ is composed of export + encrypt, unwrapKey is composed of import + decrypt.

It returns a Promise that fulfills with an ArrayBuffer containing the encrypted exported key.

The `format` parameter identifies the format of the key data. The `key` parameter is the key to export, as a CryptoKey object. The `wrappingKey` parameter is the key to use to encrypt the exported key. The key **must** have the `wrapKey` usage flag set. The `wrapAlgorithm` parameter identifies the algorithm to use to encrypt the exported key, and should be one of:

  • an `SubtleCrypto.RSAOaepParams` object
  • an `SubtleCrypto.AesCtrParams` object
  • an `SubtleCrypto.AesCbcParams` object
  • an `SubtleCrypto.AesGcmParams` object
  • for the AES-KW algorithm, pass the string "AES-KW", or an object of the form `{ name: "AES-KW" }`

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL