Giter VIP home page Giter VIP logo

webcrypto-core's Introduction

License test Coverage Status npm version

NPM

webcrypto-core

We have created a number of WebCrypto polyfills including: node-webcrypto-ossl, node-webcrypto-p11, and webcrypto-liner. webcrypto-core was designed to be a common layer to be used by all of these libraries for input validation.

Unless you intend to create a WebCrypto polyfill this library is probably not useful to you.

Installing

npm install webcrypto-core

Example

Current examples shows how you can implement your own WebCrypt interface

const core = require(".");
const crypto = require("crypto");

class Sha1Provider extends core.ProviderCrypto {

  constructor() {
    super();

    this.name = "SHA-1";
    this.usages = [];
  }

  async onDigest(algorithm, data) {
    const hash = crypto.createHash("SHA1").update(Buffer.from(data)).digest();
    return new Uint8Array(hash).buffer;
  }

}

class SubtleCrypto extends core.SubtleCrypto {
  constructor() {
    super();

    // Add SHA1 provider to SubtleCrypto
    this.providers.set(new Sha1Provider());
  }
}

class Crypto extends core.Crypto {

  constructor() {
    this.subtle = new SubtleCrypto();
  }

  getRandomValues(array) {
    const buffer = Buffer.from(array.buffer);
    crypto.randomFillSync(buffer);
    return array;
  }

}

const webcrypto = new Crypto();
webcrypto.subtle.digest("SHA-1", Buffer.from("TEST MESSAGE"))
  .then((hash) => {
    console.log(Buffer.from(hash).toString("hex")); // dbca505deb07e1612d944a69c0c851f79f3a4a60
  })
  .catch((err) => {
    console.error(err);
  });

webcrypto-core's People

Contributors

boldt avatar dependabot[bot] avatar gnarea avatar jack-works avatar jhuenges avatar ludufre avatar microshine avatar miguel-a-calles-mba avatar rmhrisk avatar shamilovtim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webcrypto-core's Issues

[Bug] 'CryptoKey has wrong key usage. Must be \'decrypt\'' When using unwrapKey() with RSA-OAEP and keyStorage

I am using https://github.com/PeculiarVentures/node-webcrypto-ossl/ in my Node.js project.
I have a bug that seems to trace back to this Pollyfill using in node-webcrypto-ossl , so I'm creating the issue here.

I have been facing an issue where when using unwrapKey() with RSA-OAEP, it fails when using RSA key being imported from keyStorage. When inspecting the keyStorage JSON file stored, it contains the correct usages ("usages":["unwrapKey"]) , but is still failing.

Exact error:

{ Error: CryptoKey has wrong key usage. Must be 'decrypt' at CryptoKeyError.WebCryptoError [as constructor] (/home/primary/BeamUpScotty_Server/Main_Server/node_modules/webcrypto-core/dist/webcrypto-core.js:38:21) at new CryptoKeyError (/home/primary/BeamUpScotty_Server/Main_Server/node_modules/webcrypto-core/dist/webcrypto-core.js:64:47) at Function.BaseCrypto.checkKey (/home/primary/BeamUpScotty_Server/Main_Server/node_modules/webcrypto-core/dist/webcrypto-core.js:140:23) at /home/primary/BeamUpScotty_Server/Main_Server/node_modules/webcrypto-core/dist/webcrypto-core.js:1378:19 at new Promise (<anonymous>) at Function.RsaOAEP.decrypt (/home/primary/BeamUpScotty_Server/Main_Server/node_modules/webcrypto-core/dist/webcrypto-core.js:1376:16) at /home/primary/BeamUpScotty_Server/Main_Server/node_modules/webcrypto-core/dist/webcrypto-core.js:1610:19 at new Promise (<anonymous>) at SubtleCrypto.decrypt (/home/primary/BeamUpScotty_Server/Main_Server/node_modules/webcrypto-core/dist/webcrypto-core.js:1578:16) at SubtleCrypto.decrypt (/home/primary/BeamUpScotty_Server/Main_Server/node_modules/node-webcrypto-ossl/buildjs/subtle.js:168:30) at Promise.resolve.then (/home/primary/BeamUpScotty_Server/Main_Server/node_modules/node-webcrypto-ossl/buildjs/subtle.js:231:33) at process._tickCallback (internal/process/next_tick.js:68:7) code: 3, message: 'CryptoKey has wrong key usage. Must be \'decrypt\'' }

I was able to temporarily remove this issue (and verify it's not an issue with my code), by going into the dist/webcrypto-core.js and modifying line 140 to comment out the throw error.

if (usage) { if (!key.usages.some(function (keyUsage) { return usage.toUpperCase() === keyUsage.toUpperCase(); })) { //throw new CryptoKeyError(CryptoKeyError.WRONG_KEY_USAGE, usage); } }

I should be able to post a sample code to reproduce this issue if necessary late tomorrow (today?), i'm just creating this issue now so I wont forget to later, as it's currently 3:00 AM.

getRandomValues() requires process

When running a test (i.e. using NodeJS) that calls peculiar's crypto.getRandomValues(new Int8Array(12)) everything works fine.

When running the same code in the browser (still using peculiar's crypto and NOT window.crypto), I get

ReferenceError: process is not defined

I would have expected that an API of a WebCrypto implementation to run on the web (without requiring NodeJS modules such as process)?

Can't compile it

Compile the source code using the following command:

npm run build
NOTE: Command creates webcrypto-core.js and webcrypto-core.min.js files in build folder

What if this doesn't happen?

root@8f4d4b4f2670:/webcrypto-core# ls
README.md  build  index.d.ts  index.js	node_modules  npm-debug.log  package.json  rollup.config.js  src  test	tsconfig.json  tslint.json
root@8f4d4b4f2670:/webcrypto-core# rm -rf build
root@8f4d4b4f2670:/webcrypto-core# npm run build
npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
npm info lifecycle [email protected]~prebuild: [email protected]
npm info lifecycle [email protected]~build: [email protected]

> [email protected] build /webcrypto-core
> tsc && rollup -c

npm info lifecycle [email protected]~postbuild: [email protected]
npm info ok
root@8f4d4b4f2670:/webcrypto-core# ls -lah build/
total 44K
drwxr-xr-x 7 root root  148 Dec 22 01:29 .
drwxr-xr-x 7 root root 4.0K Dec 22 01:29 ..
drwxr-xr-x 2 root root   22 Dec 22 01:29 aes
-rw-r--r-- 1 root root  363 Dec 22 01:29 alg.js
-rw-r--r-- 1 root root 6.4K Dec 22 01:29 base.js
-rw-r--r-- 1 root root 1.4K Dec 22 01:29 base64url.js
drwxr-xr-x 2 root root   22 Dec 22 01:29 ec
-rw-r--r-- 1 root root 3.3K Dec 22 01:29 error.js
drwxr-xr-x 2 root root   22 Dec 22 01:29 hmac
-rw-r--r-- 1 root root  402 Dec 22 01:29 index.js
drwxr-xr-x 2 root root   22 Dec 22 01:29 rsa
drwxr-xr-x 2 root root   22 Dec 22 01:29 sha
-rw-r--r-- 1 root root  15K Dec 22 01:29 subtle.js
root@8f4d4b4f2670:/webcrypto-core# ls -lah build/*
-rw-r--r-- 1 root root  363 Dec 22 01:29 build/alg.js
-rw-r--r-- 1 root root 6.4K Dec 22 01:29 build/base.js
-rw-r--r-- 1 root root 1.4K Dec 22 01:29 build/base64url.js
-rw-r--r-- 1 root root 3.3K Dec 22 01:29 build/error.js
-rw-r--r-- 1 root root  402 Dec 22 01:29 build/index.js
-rw-r--r-- 1 root root  15K Dec 22 01:29 build/subtle.js

build/aes:
total 8.0K
drwxr-xr-x 2 root root   22 Dec 22 01:29 .
drwxr-xr-x 7 root root  148 Dec 22 01:29 ..
-rw-r--r-- 1 root root 7.9K Dec 22 01:29 crypto.js

build/ec:
total 8.0K
drwxr-xr-x 2 root root   22 Dec 22 01:29 .
drwxr-xr-x 7 root root  148 Dec 22 01:29 ..
-rw-r--r-- 1 root root 6.9K Dec 22 01:29 crypto.js

build/hmac:
total 4.0K
drwxr-xr-x 2 root root   22 Dec 22 01:29 .
drwxr-xr-x 7 root root  148 Dec 22 01:29 ..
-rw-r--r-- 1 root root 3.5K Dec 22 01:29 crypto.js

build/rsa:
total 12K
drwxr-xr-x 2 root root   22 Dec 22 01:29 .
drwxr-xr-x 7 root root  148 Dec 22 01:29 ..
-rw-r--r-- 1 root root 9.4K Dec 22 01:29 crypto.js

build/sha:
total 4.0K
drwxr-xr-x 2 root root   22 Dec 22 01:29 .
drwxr-xr-x 7 root root  148 Dec 22 01:29 ..
-rw-r--r-- 1 root root 1.6K Dec 22 01:29 crypto.js

npm run minify fails, too:

npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
npm ERR! Linux 4.2.5-xxxx-grs-ipv6-64
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "minify"
npm ERR! node v6.2.0
npm ERR! npm  v3.8.9

npm ERR! missing script: minify
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     /webcrypto-core/npm-debug.log

checkDeriveBits: length is not multiple of 8

Not a huge deal, but providing an HMAC key length is supposed to be optional. The API relies on the hash algorithm provided to determine the length of the key, but the length can be overridden. See expected usage here.

When I don't provide a length when trying to derive an HMAC key from an HKDF key, webcrypto-core throws with OperationError: length: Is not multiple of 8

Installation of 0.1.4 fails

I was just reinstalling my node_modules with a dependency on webcrypto-ossl, which in turn pulls in webcrypto-core. But this fails now with the following output:

npm i

> [email protected] install /Users/dignifiedquire/opensource/ipfs/js-ipfs-lerna/packages/js-libp2p-ipfs/node_modules/webcrypto-core
> npm run build:es5


> [email protected] build:es5 /Users/dignifiedquire/opensource/ipfs/js-ipfs-lerna/packages/js-libp2p-ipfs/node_modules/webcrypto-core
> tsc --module commonjs --target es5


41         return Promise.resolve()
                  ~~~~~~~~~~~~~~~~~
42             .then(() => {
   ~~~~~~~~~~~~~~~~~~~~~~~~~
43                 this.checkAlgorithm(algorithm);
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
44             });
   ~~~~~~~~~~~~~~

src/pbkdf2/crypto.ts(41,16): error TS2322: Type 'Promise<void>' is not assignable to type 'PromiseLike<CryptoKey | CryptoKeyPair>'.
  Types of property 'then' are incompatible.
    Type '{ (onfulfilled?: ((value: void) => void | PromiseLike<void>) | null | undefined, onrejected?: ((r...' is not assignable to type '{ (onfulfilled?: ((value: CryptoKey | CryptoKeyPair) => CryptoKey | CryptoKeyPair | PromiseLike<C...'.
      Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
        Type '((value: CryptoKey | CryptoKeyPair) => CryptoKey | CryptoKeyPair | PromiseLike<CryptoKey | Crypto...' is not assignable to type '((value: void) => void | PromiseLike<void>) | null | undefined'.
          Type '(value: CryptoKey | CryptoKeyPair) => CryptoKey | CryptoKeyPair | PromiseLike<CryptoKey | CryptoK...' is not assignable to type '((value: void) => void | PromiseLike<void>) | null | undefined'.
            Type '(value: CryptoKey | CryptoKeyPair) => CryptoKey | CryptoKeyPair | PromiseLike<CryptoKey | CryptoK...' is not assignable to type '(value: void) => void | PromiseLike<void>'.
              Types of parameters 'value' and 'value' are incompatible.
                Type 'void' is not assignable to type 'CryptoKey | CryptoKeyPair'.


 48         return Promise.resolve()
                   ~~~~~~~~~~~~~~~~~
 49             .then(() => {
    ~~~~~~~~~~~~~~~~~~~~~~~~~
...
 54                 this.checkKeyUsages(keyUsages);
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 55             });
    ~~~~~~~~~~~~~~

src/pbkdf2/crypto.ts(48,16): error TS2322: Type 'Promise<void>' is not assignable to type 'PromiseLike<CryptoKey>'.
  Types of property 'then' are incompatible.
    Type '{ (onfulfilled?: ((value: void) => void | PromiseLike<void>) | null | undefined, onrejected?: ((r...' is not assignable to type '{ (onfulfilled?: ((value: CryptoKey) => CryptoKey | PromiseLike<CryptoKey>) | null | undefined, o...'.
      Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
        Type '((value: CryptoKey) => CryptoKey | PromiseLike<CryptoKey>) | null | undefined' is not assignable to type '((value: void) => void | PromiseLike<void>) | null | undefined'.
          Type '(value: CryptoKey) => CryptoKey | PromiseLike<CryptoKey>' is not assignable to type '((value: void) => void | PromiseLike<void>) | null | undefined'.
            Type '(value: CryptoKey) => CryptoKey | PromiseLike<CryptoKey>' is not assignable to type '(value: void) => void | PromiseLike<void>'.
              Types of parameters 'value' and 'value' are incompatible.
                Type 'void' is not assignable to type 'CryptoKey'.


 59         return Promise.resolve()
                   ~~~~~~~~~~~~~~~~~
 60             .then(() => {
    ~~~~~~~~~~~~~~~~~~~~~~~~~
...
 88                 }
    ~~~~~~~~~~~~~~~~~
 89             });
    ~~~~~~~~~~~~~~

src/pbkdf2/crypto.ts(59,16): error TS2322: Type 'Promise<void>' is not assignable to type 'PromiseLike<CryptoKey>'.


 92         return Promise.resolve()
                   ~~~~~~~~~~~~~~~~~
 93             .then(() => {
    ~~~~~~~~~~~~~~~~~~~~~~~~~
...
 97                     throw new WebCryptoError("Parameter 'length' must be Number and more than 0");
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 98             });
    ~~~~~~~~~~~~~~

src/pbkdf2/crypto.ts(92,16): error TS2322: Type 'Promise<void>' is not assignable to type 'PromiseLike<ArrayBuffer>'.
  Types of property 'then' are incompatible.
    Type '{ (onfulfilled?: ((value: void) => void | PromiseLike<void>) | null | undefined, onrejected?: ((r...' is not assignable to type '{ (onfulfilled?: ((value: ArrayBuffer) => ArrayBuffer | PromiseLike<ArrayBuffer>) | null | undefi...'.
      Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
        Type '((value: ArrayBuffer) => ArrayBuffer | PromiseLike<ArrayBuffer>) | null | undefined' is not assignable to type '((value: void) => void | PromiseLike<void>) | null | undefined'.
          Type '(value: ArrayBuffer) => ArrayBuffer | PromiseLike<ArrayBuffer>' is not assignable to type '((value: void) => void | PromiseLike<void>) | null | undefined'.
            Type '(value: ArrayBuffer) => ArrayBuffer | PromiseLike<ArrayBuffer>' is not assignable to type '(value: void) => void | PromiseLike<void>'.
              Types of parameters 'value' and 'value' are incompatible.
                Type 'void' is not assignable to type 'ArrayBuffer'.

ChainAlert: npm package release (1.7.1) has no matching tag in this repo

Dear webcrypto-core maintainers,
Thank you for your contribution to the open-source community.

This issue was automatically created to inform you a new version (1.7.1) of webcrypto-core was published without a matching tag in this repo.

As part of our efforts to fight software supply chain attacks, we would like to verify this release is known and intended, and not a result of an unauthorized activity.

If you find this behavior legitimate, kindly close and ignore this issue. Read more

badge

`toStringTag` to support feature detection

Hi,

Would you be open to a PR to add Symbol.toStringTag, e.g., as our project needs for CryptoKey?

    get [Symbol.toStringTag]() {
        return 'CryptoKey';
    }

This should behave more in line with the browser API, and allow feature detection via Object.prototype.toString.call(obj).slice(8, -1).

E.g., the following logs "CryptoKey" in Chrome or Firefox:

(async () => {
console.log(Object.prototype.toString.call(await crypto.subtle.generateKey(
  {
    name: "HMAC",
    hash: {name: "SHA-512"}
  },
  true,
  ["sign", "verify"]
)).slice(8, -1));
})();

Our project (typeson-registry) needs this to support auto-cloning of objects that may contain CryptoKey objects.

Allow to pass additional arugments to a subtle function

Hi,
I am using your package to build a subtle API for using hardware security services such as Key Vault.
If one wants to generate a key on such a service, one wants to specify the name of the new key and as such pass an additional optional parameter to generateKey.
The method checkRequiredArguments is very strict on killing this option.

protected checkRequiredArguments(args: IArguments, size: number, methodName: string) {
if (args.length !== size) {
throw new TypeError(Failed to execute '${methodName}' on 'SubtleCrypto': ${size} arguments required, but only ${args.length} present);
}
}

Would it be possible to allow additional arguments (args.length > size) to these functions or do you envision another way to pass additional parameters.
The only other way I saw was to pass additional props in algorithm but this is not a clean solution.

Thanks

deriveBits PBKDF2: algorithm.hash should allow a string value

Context

When using PBKDF2 to derive an array of bytes from a key, the WebCrypto documentation states you can do the following:

crypto.subtle.deriveBits(
  {
    name: 'PBKDF2',
    salt,
    iterations: 10000,
    hash: 'SHA-256'
  }, 
  key, 
  lengthInBits
)

Encountered issue

However, when calling this in node-webcrypto-ossl (which uses this library), I get the following error:

TypeError: Cannot read property 'toLowerCase' of undefined
      at Pbkdf2Provider.checkHashAlgorithm (node_modules/webcrypto-core/build/webcrypto-core.js:260:55)
      at Pbkdf2Provider.checkAlgorithmParams (node_modules/webcrypto-core/build/webcrypto-core.js:649:14)
      at Pbkdf2Provider.checkDeriveBits (node_modules/webcrypto-core/build/webcrypto-core.js:192:14)
      at Pbkdf2Provider.deriveBits (node_modules/webcrypto-core/build/webcrypto-core.js:187:30)
      at SubtleCrypto.deriveBits (node_modules/webcrypto-core/build/webcrypto-core.js:799:39)

Expected outcome

A string value should be allowed for the hash property of the algorithm.

Possible user remediation

For now, changing the call to use an object with a name property bypasses this issue:

crypto.subtle.deriveBits(
  {
    name: 'PBKDF2',
    salt,
    iterations: 10000,
    hash: { name: 'SHA-256' }
  }, 
  key, 
  lengthInBits
)

SubtleCrypto fails to recognise some `CryptoKey`s

The following is failing for me:

protected checkCryptoKey(key: globalThis.CryptoKey): asserts key is CryptoKey {
if (!(key instanceof CryptoKey)) {
throw new TypeError(`Key is not of type 'CryptoKey'`);
}
}

Error: Error during exporting public key: Key is not of type 'CryptoKey'

    at PublicKeyInfo.importKey (/home/gus/repos/relaynet-internet-gateway/node_modules/@relaycorp/relaynet-core/node_modules/pkijs/build/index.js:3935:19)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at Function.issue (/home/gus/repos/relaynet-internet-gateway/node_modules/@relaycorp/relaynet-core/src/lib/crypto_wrappers/x509/Certificate.ts:108:5)
    at PublicGatewayManager.generate (/home/gus/repos/relaynet-internet-gateway/src/node/PublicGatewayManager.ts:40:32)
    at Object.<anonymous> (/home/gus/repos/relaynet-internet-gateway/src/node/PublicGatewayManager.spec.ts:67:28)

But it shouldn't be (according to my debugger):

cryptokey-err


I think the issue is analogous to PeculiarVentures/asn1-schema#71. Here some info on the dependency tree:

$ npm list webcrypto-core
@relaycorp/[email protected] /home/gus/repos/relaynet-internet-gateway
└─┬ @relaycorp/[email protected]
  ├─┬ @peculiar/[email protected]
  │ └── [email protected]  deduped
  └── [email protected] 

$ npm list @peculiar/webcrypto
@relaycorp/[email protected] /home/gus/repos/relaynet-internet-gateway
└─┬ @relaycorp/[email protected]
  └── @peculiar/[email protected]

The CryptoKeyPair is generated inside @relaycorp/relaynet-core, using @peculiar/webcrypto, and the resulting key pair is then passed to the root package (relaynet-internet-gateway). Then the root package tries to use that key pair to issue a self-signed certificate using @relaycorp/relaynet-core (which in turn uses PKI.js), but it fails with the error above.

Note that I tried skipping the key instanceof CryptoKey check above, but hit a new error from @peculiar/webcrypto:

Error: Error during exporting public key: Cannot get CryptoKey from secure storage

    at PublicKeyInfo.importKey (/home/gus/repos/relaynet-internet-gateway/node_modules/@relaycorp/relaynet-core/node_modules/pkijs/build/index.js:3935:19)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at Function.issue (/home/gus/repos/relaynet-internet-gateway/node_modules/@relaycorp/relaynet-core/src/lib/crypto_wrappers/x509/Certificate.ts:108:5)
    at PublicGatewayManager.generate (/home/gus/repos/relaynet-internet-gateway/src/node/PublicGatewayManager.ts:40:32)
    at Object.<anonymous> (/home/gus/repos/relaynet-internet-gateway/src/node/PublicGatewayManager.spec.ts:67:28)

Fix nullability checks

In JS the following holds true:

const foo = { maybe: undefined };
const bar = {};

> "maybe" in foo;
true
> "maybe" in bar;
false

This library uses nullability checks such that (e.g.)!("tagLength" in algorithm) which causes unhandled exceptions when the key exists but is undefined

Incompatible with TypeScript 4.4

When using webcrypto-core with TypeScript 4.4, I get the following errors:

node_modules/webcrypto-core/build/types/aes/cmac.d.ts:6:37 - error TS2304: Cannot find name 'AesCmacParams'.

6     checkAlgorithmParams(algorithm: AesCmacParams): void;
                                      ~~~~~~~~~~~~~

node_modules/webcrypto-core/build/types/aes/cmac.d.ts:7:32 - error TS2304: Cannot find name 'AesCmacParams'.

7     abstract onSign(algorithm: AesCmacParams, key: CryptoKey, data: ArrayBuffer, ...args: any[]): Promise<ArrayBuffer>;
                                 ~~~~~~~~~~~~~

node_modules/webcrypto-core/build/types/aes/cmac.d.ts:8:34 - error TS2304: Cannot find name 'AesCmacParams'.

8     abstract onVerify(algorithm: AesCmacParams, key: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer, ...args: any[]): Promise<boolean>;

In my tsconfig.json, the required libs are added already:

...
    "lib": ["dom", "esnext"],
...

Generates invalid UUIDs

randomUUID() appears to generate UUIDs that don't match the spec. It looks like the spec requires the format:

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

Whereas this library generates:

xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx

It's correct except it's missing the final hyphen.

Is this a bug, or am I missing something?

Align webcrypto-core with Web Cryptography API specification

At the moment seems wecrypto-core not fully aligned with Web Crypto API specification, at least in part of handling AES-CBC parameters.

Initially my problem was that during "crypto.decrypt({ AES-CBC })" I had error:

Algorithm has got wrong type for paramter 'iv'. Must be ArrayBufferView.

After checking Web Crypto API description for AesCbcParams I found that type for the "iv" is "BufferSource". The "BufferSource" type is defined in WebIDL specification:

typedef (ArrayBufferView or ArrayBuffer) BufferSource;

So, in fact the "iv" parameter could be ArrayBufferView or pure ArrayBuffer, does not matter.

I did not check other places in webcrypto-core/webcrypto-liner for such "specification alignment issues" - I do expect you could do this yourself. At the moment I need a fix for at least correct type checking for "iv" parameter.

1.7.1 is broken

Hello,

Since the 1.7.1. commit the library is not more usable.

It's conflict with other typescript types

$ tsc -d -p tsconfig.json
../../node_modules/@types/web/index.d.ts(7,1): error TS6200: Definitions of the following identifiers conflict with those in another file: NodeFilter, XPathNSResolver, SVGMatrix, WebKitCSSMatrix, SVGPoint, SVGRect, location, webkitURL, ImportExportKind, TableKind, ValueType, ExportValue, Exports, ImportValue, Imports, ModuleImports, ElementTagNameMap, name, AlgorithmIdentifier, BigInteger, BinaryData, BlobPart, BodyInit, BufferSource, COSEAlgorithmIdentifier, CSSNumberish, CanvasImageSource, ClipboardItemData, ClipboardItemDataType, ClipboardItems, ConstrainBoolean, ConstrainDOMString, ConstrainDouble, ConstrainULong, DOMHighResTimeStamp, EventListenerOrEventListenerObject, Float32List, FormDataEntryValue, GLbitfield, GLboolean, GLclampf, GLenum, GLfloat, GLint, GLint64, GLintptr, GLsizei, GLsizeiptr, GLuint, GLuint64, HTMLOrSVGImageElement, HTMLOrSVGScriptElement, HashAlgorithmIdentifier, HeadersInit, IDBValidKey, ImageBitmapSource, InsertPosition, Int32List, LineAndPositionSetting, MediaProvider, MessageEventSource, MutationRecordType, NamedCurve, OnBeforeUnloadEventHandler, OnErrorEventHandler, PerformanceEntryList, ReadableStreamController, ReadableStreamDefaultReadResult, ReadableStreamReader, RenderingContext, RequestInfo, TexImageSource, TimerHandler, Transferable, Uint32List, UvmEntries, UvmEntry, VibratePattern, WindowProxy, XMLHttpRequestBodyInit, AlignSetting, AnimationPlayState, AnimationReplaceState, AppendMode, AttestationConveyancePreference, AudioContextLatencyCategory, AudioContextState, AuthenticatorAttachment, AuthenticatorTransport, AutoKeyword, AutomationRate, BinaryType, BiquadFilterType, CanPlayTypeResult, CanvasDirection, CanvasFillRule, CanvasFontKerning, CanvasFontStretch, CanvasFontVariantCaps, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, CanvasTextRendering, ChannelCountMode, ChannelInterpretation, ClientTypes, ColorGamut, ColorSpaceConversion, CompositeOperation, CompositeOperationOrAuto, ConnectionType, CredentialMediationRequirement, DOMParserSupportedType, DirectionSetting, DisplayCaptureSurfaceType, DistanceModelType, DocumentReadyState, EndOfStreamError, EndingType, FillMode, FontFaceLoadStatus, FontFaceSetLoadStatus, FullscreenNavigationUI, GamepadHapticActuatorType, GamepadMappingType, HdrMetadataType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, IterationCompositeOperation, KeyFormat, KeyType, KeyUsage, LineAlignSetting, MediaDecodingType, MediaDeviceKind, MediaEncodingType, MediaKeyMessageType, MediaKeySessionClosedReason, MediaKeySessionType, MediaKeyStatus, MediaKeysRequirement, MediaSessionAction, MediaSessionPlaybackState, MediaStreamTrackState, NavigationType, NotificationDirection, NotificationPermission, OrientationLockType, OrientationType, OscillatorType, OverSampleType, PanningModelType, PaymentComplete, PermissionName, PermissionState, PlaybackDirection, PositionAlignSetting, PredefinedColorSpace, PremultiplyAlpha, PresentationStyle, PublicKeyCredentialType, PushEncryptionKeyName, RTCBundlePolicy, RTCDataChannelState, RTCDegradationPreference, RTCDtlsTransportState, RTCIceCandidateType, RTCIceComponent, RTCIceConnectionState, RTCIceCredentialType, RTCIceGathererState, RTCIceGatheringState, RTCIceProtocol, RTCIceTcpCandidateType, RTCIceTransportPolicy, RTCIceTransportState, RTCPeerConnectionState, RTCPriorityType, RTCRtcpMuxPolicy, RTCRtpTransceiverDirection, RTCSdpType, RTCSignalingState, RTCStatsIceCandidatePairState, RTCStatsType, ReadyState, RecordingState, ReferrerPolicy, RemotePlaybackState, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestRedirect, ResidentKeyRequirement, ResizeObserverBoxOptions, ResizeQuality, ResponseType, ScrollBehavior, ScrollLogicalPosition, ScrollRestoration, ScrollSetting, SecurityPolicyViolationEventDisposition, SelectionMode, ServiceWorkerState, ServiceWorkerUpdateViaCache, ShadowRootMode, SlotAssignmentMode, SpeechSynthesisErrorCode, TextTrackKind, TextTrackMode, TouchType, TransferFunction, UserVerificationRequirement, VideoFacingModeEnum, WebGLPowerPreference, WorkerType, XMLHttpRequestResponseType
../../node_modules/@types/web/index.d.ts(221,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/@types/web/index.d.ts(269,5): error TS2687: All declarations of 'privateKey' must have identical modifiers.
../../node_modules/@types/web/index.d.ts(270,5): error TS2687: All declarations of 'publicKey' must have identical modifiers.
../../node_modules/@types/web/index.d.ts(675,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/@types/web/index.d.ts(1142,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/@types/web/index.d.ts(1697,5): error TS2717: Subsequent property declarations must have the same type.  Property 'transfer' must be of type 'any[]', but here has type 'Transferable[]'.
../../node_modules/@types/web/index.d.ts(2691,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(3235,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(3347,5): error TS2717: Subsequent property declarations must have the same type.  Property 'globalCompositeOperation' must be of type 'string', but here has type 'GlobalCompositeOperation'.
../../node_modules/@types/web/index.d.ts(4013,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(4047,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(4057,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/@types/web/index.d.ts(4123,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(4199,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(5144,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(5902,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(6157,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(6173,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(6479,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(6480,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/@types/web/index.d.ts(6820,5): error TS2717: Subsequent property declarations must have the same type.  Property 'loading' must be of type 'string', but here has type '"eager" | "lazy"'.
../../node_modules/@types/web/index.d.ts(7772,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(9273,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(9622,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(9749,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(10023,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(10039,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(10699,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(10721,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(11411,13): error TS2403: Subsequent variable declarations must have the same type.  Variable 'Request' must be of type '{ new (input: RequestInfo, init?: RequestInit): Request; prototype: Request; }', but here has type '{ new (input: RequestInfo | URL, init?: RequestInit): Request; prototype: Request; }'.
../../node_modules/@types/web/index.d.ts(12514,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(12654,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(12705,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(12916,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(13133,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(13482,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(13504,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(13515,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(13668,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/@types/web/index.d.ts(13735,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(13990,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(14014,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(14086,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/@types/web/index.d.ts(16578,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(25,1): error TS6200: Definitions of the following identifiers conflict with those in another file: NodeFilter, XPathNSResolver, SVGMatrix, WebKitCSSMatrix, SVGPoint, SVGRect, location, webkitURL, ImportExportKind, TableKind, ValueType, ExportValue, Exports, ImportValue, Imports, ModuleImports, ElementTagNameMap, name, AlgorithmIdentifier, BigInteger, BinaryData, BlobPart, BodyInit, BufferSource, COSEAlgorithmIdentifier, CSSNumberish, CanvasImageSource, ClipboardItemData, ClipboardItemDataType, ClipboardItems, ConstrainBoolean, ConstrainDOMString, ConstrainDouble, ConstrainULong, DOMHighResTimeStamp, EventListenerOrEventListenerObject, Float32List, FormDataEntryValue, GLbitfield, GLboolean, GLclampf, GLenum, GLfloat, GLint, GLint64, GLintptr, GLsizei, GLsizeiptr, GLuint, GLuint64, HTMLOrSVGImageElement, HTMLOrSVGScriptElement, HashAlgorithmIdentifier, HeadersInit, IDBValidKey, ImageBitmapSource, InsertPosition, Int32List, LineAndPositionSetting, MediaProvider, MessageEventSource, MutationRecordType, NamedCurve, OnBeforeUnloadEventHandler, OnErrorEventHandler, PerformanceEntryList, ReadableStreamController, ReadableStreamDefaultReadResult, ReadableStreamReader, RenderingContext, RequestInfo, TexImageSource, TimerHandler, Transferable, Uint32List, UvmEntries, UvmEntry, VibratePattern, WindowProxy, XMLHttpRequestBodyInit, AlignSetting, AnimationPlayState, AnimationReplaceState, AppendMode, AttestationConveyancePreference, AudioContextLatencyCategory, AudioContextState, AuthenticatorAttachment, AuthenticatorTransport, AutoKeyword, AutomationRate, BinaryType, BiquadFilterType, CanPlayTypeResult, CanvasDirection, CanvasFillRule, CanvasFontKerning, CanvasFontStretch, CanvasFontVariantCaps, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, CanvasTextRendering, ChannelCountMode, ChannelInterpretation, ClientTypes, ColorGamut, ColorSpaceConversion, CompositeOperation, CompositeOperationOrAuto, ConnectionType, CredentialMediationRequirement, DOMParserSupportedType, DirectionSetting, DisplayCaptureSurfaceType, DistanceModelType, DocumentReadyState, EndOfStreamError, EndingType, FillMode, FontFaceLoadStatus, FontFaceSetLoadStatus, FullscreenNavigationUI, GamepadHapticActuatorType, GamepadMappingType, HdrMetadataType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, IterationCompositeOperation, KeyFormat, KeyType, KeyUsage, LineAlignSetting, MediaDecodingType, MediaDeviceKind, MediaEncodingType, MediaKeyMessageType, MediaKeySessionClosedReason, MediaKeySessionType, MediaKeyStatus, MediaKeysRequirement, MediaSessionAction, MediaSessionPlaybackState, MediaStreamTrackState, NavigationType, NotificationDirection, NotificationPermission, OrientationLockType, OrientationType, OscillatorType, OverSampleType, PanningModelType, PaymentComplete, PermissionName, PermissionState, PlaybackDirection, PositionAlignSetting, PredefinedColorSpace, PremultiplyAlpha, PresentationStyle, PublicKeyCredentialType, PushEncryptionKeyName, RTCBundlePolicy, RTCDataChannelState, RTCDegradationPreference, RTCDtlsTransportState, RTCIceCandidateType, RTCIceComponent, RTCIceConnectionState, RTCIceCredentialType, RTCIceGathererState, RTCIceGatheringState, RTCIceProtocol, RTCIceTcpCandidateType, RTCIceTransportPolicy, RTCIceTransportState, RTCPeerConnectionState, RTCPriorityType, RTCRtcpMuxPolicy, RTCRtpTransceiverDirection, RTCSdpType, RTCSignalingState, RTCStatsIceCandidatePairState, RTCStatsType, ReadyState, RecordingState, ReferrerPolicy, RemotePlaybackState, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestRedirect, ResidentKeyRequirement, ResizeObserverBoxOptions, ResizeQuality, ResponseType, ScrollBehavior, ScrollLogicalPosition, ScrollRestoration, ScrollSetting, SecurityPolicyViolationEventDisposition, SelectionMode, ServiceWorkerState, ServiceWorkerUpdateViaCache, ShadowRootMode, SlotAssignmentMode, SpeechSynthesisErrorCode, TextTrackKind, TextTrackMode, TouchType, TransferFunction, UserVerificationRequirement, VideoFacingModeEnum, WebGLPowerPreference, WorkerType, XMLHttpRequestResponseType
../../node_modules/typescript/lib/lib.dom.d.ts(239,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/typescript/lib/lib.dom.d.ts(287,5): error TS2687: All declarations of 'privateKey' must have identical modifiers.
../../node_modules/typescript/lib/lib.dom.d.ts(288,5): error TS2687: All declarations of 'publicKey' must have identical modifiers.
../../node_modules/typescript/lib/lib.dom.d.ts(681,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/typescript/lib/lib.dom.d.ts(1125,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/typescript/lib/lib.dom.d.ts(2625,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(3158,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(3919,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(3953,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(3963,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/typescript/lib/lib.dom.d.ts(4029,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(4105,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(5023,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(5741,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(5996,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(6012,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(6303,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(6304,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/typescript/lib/lib.dom.d.ts(7594,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(9058,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(9407,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(9534,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(9795,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(9811,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(10469,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(10491,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(12198,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(12338,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(12389,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(12600,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(12817,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(13156,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(13178,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(13189,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(13342,5): error TS2374: Duplicate index signature for type 'string'.
../../node_modules/typescript/lib/lib.dom.d.ts(13408,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(13663,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(13687,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(13759,5): error TS2374: Duplicate index signature for type 'number'.
../../node_modules/typescript/lib/lib.dom.d.ts(16230,5): error TS2374: Duplicate index signature for type 'number'.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

If I lock the version to 1.7.0 it works fine, although ideally I want ot use the latest version available

Error "Parameter 'saltLength' should be a multiple of 8" is incorrect

During some operations with RSA-PSS algorithm I had this error:

Error: Parameter 'saltLength' should be a multiple of 8

So, the "saltLength" parameter is using only as a part of RSASSA-PSS-params which in turn came from RFC4055. In the RFC we have this definition of RSASSA-PSS-params:

RSASSA-PSS-params  ::=  Sequence  {
    hashAlgorithm      [0] HashAlgorithm DEFAULT sha1Identifier,
    maskGenAlgorithm   [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier,
    saltLength         [2] Integer DEFAULT 20,
    trailerField       [3] Integer DEFAULT 1  }

As you can see the "saltLength" parameter has a default value equal to 20 and let me explain why. As you can see the "RSASSA-PSS-params" also has default value for "hashAlgorithm" parameter and the default value is SHA-1. And as a result of SHA-1 algorithm we have value with length equal to 20. That is why we have "saltLength" default value as 20.

Also let me quote some part of WebCrypto API specification for "exportKey" operation for RSA-PSS algorithm:

Set the saltLength field to the length in octets of the digest algorithm identified by the name attribute of the hash attribute of the [[algorithm]] internal slot of key

So, in fact the "saltLength" value must be equal in length to output of hashAlgorithm used inside "RSASSA-PSS-params".

Please remove the check "if (alg.saltLength % 8) ..." because it is completely incorrect.

PR

@dannycoates I just noticed your fork, there’s some good changes in here. If you’d be interested in having those merged into the main project just submit a PR be happy to accept them

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.