Socket
Socket
Sign inDemoInstall

webcrypto-core

Package Overview
Dependencies
Maintainers
2
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

webcrypto-core - npm Package Compare versions

Comparing version 0.1.26 to 1.0.1

test/aes.ts

229

index.js

@@ -17,3 +17,3 @@ // Copyright (c) 2017, Peculiar Ventures, All rights reserved.

constructor(methodName) {
super(`Unsupported operation: ${methodName ? `: ${methodName}` : ""}`);
super(`Unsupported operation: ${methodName ? `${methodName}` : ""}`);
}

@@ -48,2 +48,3 @@ }

this.checkAlgorithmName(algorithm);
this.checkGenerateKeyParams(algorithm);
if (!(keyUsages && keyUsages.length)) {

@@ -61,2 +62,4 @@ throw new TypeError(`Usages cannot be empty when creating a key.`);

}
checkGenerateKeyParams(algorithm) {
}
async onGenerateKey(algorithm, extractable, keyUsages) {

@@ -84,3 +87,3 @@ throw new UnsupportedOperationError("generateKey");

this.checkAlgorithmParams(algorithm);
this.checkCryptoKey(key, "sign");
this.checkCryptoKey(key, "verify");
}

@@ -90,10 +93,10 @@ async onVerify(algorithm, key, signature, data) {

}
async encrypt(algorithm, key, data) {
async encrypt(algorithm, key, data, options) {
this.checkEncrypt.apply(this, arguments);
return this.onEncrypt.apply(this, arguments);
}
checkEncrypt(algorithm, key, data) {
checkEncrypt(algorithm, key, data, options = {}) {
this.checkAlgorithmName(algorithm);
this.checkAlgorithmParams(algorithm);
this.checkCryptoKey(key, "encrypt");
this.checkCryptoKey(key, options.keyUsage ? "encrypt" : void 0);
}

@@ -103,10 +106,10 @@ async onEncrypt(algorithm, key, data) {

}
async decrypt(algorithm, key, data) {
async decrypt(algorithm, key, data, options) {
this.checkDecrypt.apply(this, arguments);
return this.onDecrypt.apply(this, arguments);
}
checkDecrypt(algorithm, key, data) {
checkDecrypt(algorithm, key, data, options = {}) {
this.checkAlgorithmName(algorithm);
this.checkAlgorithmParams(algorithm);
this.checkCryptoKey(key, "decrypt");
this.checkCryptoKey(key, options.keyUsage ? "decrypt" : void 0);
}

@@ -116,10 +119,10 @@ async onDecrypt(algorithm, key, data) {

}
async deriveBits(algorithm, baseKey, length) {
async deriveBits(algorithm, baseKey, length, options) {
this.checkDeriveBits.apply(this, arguments);
return this.onDeriveBits.apply(this, arguments);
}
checkDeriveBits(algorithm, baseKey, length) {
checkDeriveBits(algorithm, baseKey, length, options = {}) {
this.checkAlgorithmName(algorithm);
this.checkAlgorithmParams(algorithm);
this.checkCryptoKey(baseKey, "deriveBits");
this.checkCryptoKey(baseKey, options.keyUsage ? "deriveBits" : void 0);
if (length % 8 !== 0) {

@@ -132,14 +135,2 @@ throw new OperationError("length: Is not multiple of 8");

}
async deriveKey(algorithm, baseKey, derivedKeyType, extractable, keyUsages) {
this.checkDeriveKey.apply(this, arguments);
return this.onDeriveKey.apply(this, arguments);
}
checkDeriveKey(algorithm, baseKey, derivedKeyType, extractable, keyUsages) {
this.checkAlgorithmName(algorithm);
this.checkAlgorithmParams(algorithm);
this.checkCryptoKey(baseKey, "deriveKey");
}
async onDeriveKey(algorithm, baseKey, derivedKeyType, extractable, keyUsages) {
throw new UnsupportedOperationError("deriveKey");
}
async exportKey(format, key) {

@@ -150,2 +141,7 @@ this.checkExportKey.apply(this, arguments);

checkExportKey(format, key) {
this.checkKeyFormat(format);
this.checkCryptoKey(key);
if (!key.extractable) {
throw new CryptoError("key: Is not extractable");
}
}

@@ -160,2 +156,8 @@ async onExportKey(format, key) {

checkImportKey(format, keyData, algorithm, extractable, keyUsages) {
this.checkKeyFormat(format);
this.checkAlgorithmName(algorithm);
this.checkImportParams(algorithm);
if (Array.isArray(this.usages)) {
this.checkKeyUsages(keyUsages, this.usages);
}
}

@@ -165,20 +167,2 @@ async onImportKey(format, keyData, algorithm, extractable, keyUsages) {

}
async wrapKey(format, key, wrappingKey, wrapAlgorithm) {
this.checkWrapKey.apply(this, arguments);
return this.onWrapKey.apply(this, arguments);
}
checkWrapKey(format, key, wrappingKey, wrapAlgorithm) {
}
async onWrapKey(format, key, wrappingKey, wrapAlgorithm) {
throw new UnsupportedOperationError("wrapKey");
}
async unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages) {
this.checkUnwrapKey.apply(this, arguments);
return this.onUnwrapKey.apply(this, arguments);
}
checkUnwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages) {
}
async onUnwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages) {
throw new UnsupportedOperationError("unwrapKey");
}
checkAlgorithmName(algorithm) {

@@ -191,2 +175,4 @@ if (algorithm.name.toLowerCase() !== this.name.toLowerCase()) {

}
checkDerivedKeyParams(algorithm) {
}
checkKeyUsages(usages, allowed) {

@@ -202,3 +188,3 @@ for (const usage of usages) {

if (keyUsage && key.usages.indexOf(keyUsage) === -1) {
throw new CryptoError(`key.algorithm does not match that of operation`);
throw new CryptoError(`key does not match that of operation`);
}

@@ -219,10 +205,34 @@ }

}
checkImportParams(algorithm) {
}
checkKeyFormat(format) {
switch (format) {
case "raw":
case "pkcs8":
case "spki":
case "jwk":
break;
default:
throw new TypeError("format: Is invalid value. Must be 'jwk', 'raw', 'spki', or 'pkcs8'");
}
}
prepareData(data) {
if (data instanceof ArrayBuffer) {
return data;
}
if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) {
return new Uint8Array(data);
}
if (ArrayBuffer.isView(data)) {
return data.buffer;
}
throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
}
}
class AesProvider extends ProviderCrypto {
checkGenerateKey(algorithm, extractable, keyUsages) {
super.checkGenerateKey.apply(this, arguments);
checkGenerateKeyParams(algorithm) {
this.checkRequiredProperty(algorithm, "length");
if (typeof algorithm.length !== "number") {
throw new TypeError("length: Is not a Number");
throw new TypeError("length: Is not of type Number");
}

@@ -238,2 +248,5 @@ switch (algorithm.length) {

}
checkDerivedKeyParams(algorithm) {
this.checkGenerateKeyParams(algorithm);
}
}

@@ -315,3 +328,6 @@

this.checkRequiredProperty(algorithm, "iv");
if (algorithm.iv.byteLength < 0) {
if (!(algorithm.iv instanceof ArrayBuffer || ArrayBuffer.isView(algorithm.iv))) {
throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
if (algorithm.iv.byteLength < 1) {
throw new OperationError("iv: Must have length more than 0 and less than 2^64 - 1");

@@ -361,11 +377,24 @@ }

}
checkGenerateKeyParams(algorithm) {
this.checkRequiredProperty(algorithm, "length");
if (typeof algorithm.length !== "number") {
throw new TypeError("length: Is not of type Number");
}
if (algorithm.length !== this.keySizeBits) {
throw new OperationError(`algorith.length: Must be ${this.keySizeBits}`);
}
}
checkDerivedKeyParams(algorithm) {
this.checkGenerateKeyParams(algorithm);
}
}
class RsaProvider extends ProviderCrypto {
checkGenerateKey(algorithm, extractable, keyUsages) {
super.checkGenerateKey.apply(this, arguments);
constructor() {
super(...arguments);
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
}
checkGenerateKeyParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
if (RsaProvider.HASH_ALGORITHMS.indexOf(algorithm.hash.name.toUpperCase()) === -1) {
throw new AlgorithmError(`Unsupported hash algorithm`);
}
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "publicExponent");

@@ -389,4 +418,7 @@ if (!(algorithm.publicExponent && algorithm.publicExponent instanceof Uint8Array)) {

}
checkImportParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
}
}
RsaProvider.HASH_ALGORITHMS = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];

@@ -418,2 +450,5 @@ class RsaSsaProvider extends RsaProvider {

}
if (algorithm.saltLength < 1) {
throw new RangeError("saltLength: Must be more than 0");
}
}

@@ -440,4 +475,3 @@ }

class EllipticProvider extends ProviderCrypto {
checkGenerateKey(algorithm, extractable, keyUsages) {
super.checkGenerateKey.apply(this, arguments);
checkGenerateKeyParams(algorithm) {
this.checkRequiredProperty(algorithm, "namedCurve");

@@ -516,3 +550,3 @@ this.checkNamedCurve(algorithm.namedCurve);

this.name = "HMAC";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SAH-384", "SHA-512"];
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["sign", "verify"];

@@ -528,4 +562,4 @@ }

return 384;
case "SHA-521":
return 521;
case "SHA-512":
return 512;
default:

@@ -535,4 +569,4 @@ throw new Error(`Unknown algorithm name '${algName}'`);

}
checkGenerateKey(algorithm, extractable, keyUsages) {
super.checkGenerateKey.apply(this, arguments);
checkGenerateKeyParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);

@@ -543,21 +577,10 @@ if ("length" in algorithm) {

}
if (algorithm.length < 8) {
throw new OperationError("length: Is less than 8 bits");
if (algorithm.length < 1) {
throw new RangeError("length: Number is out of range");
}
}
}
checkAlgorithmParams(algorithm) {
checkImportParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "salt");
if (!(algorithm.salt instanceof ArrayBuffer || ArrayBuffer.isView(algorithm.salt))) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
this.checkRequiredProperty(algorithm, "iterations");
if (typeof algorithm.iterations !== "number") {
throw new TypeError("iterations: Is not a Number");
}
if (algorithm.iterations < 1) {
throw new TypeError("iterations: Is less than 1");
}
}

@@ -570,3 +593,3 @@ }

this.name = "PBKDF2";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SAH-384", "SHA-512"];
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["deriveBits", "deriveKey"];

@@ -589,2 +612,8 @@ }

}
checkImportKey(format, keyData, algorithm, extractable, keyUsages) {
super.checkImportKey(format, keyData, algorithm, extractable, keyUsages);
if (extractable) {
throw new SyntaxError("extractable: Must be False");
}
}
}

@@ -612,4 +641,4 @@

}
has(provider) {
return this.get(provider.name) === provider;
has(name) {
return !!this.get(name);
}

@@ -678,3 +707,3 @@ get length() {

const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.encrypt(preparedAlgorithm, key, preparedData);
const result = await provider.encrypt(preparedAlgorithm, key, preparedData, { keyUsage: true });
return result;

@@ -688,3 +717,3 @@ }

const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.decrypt(preparedAlgorithm, key, preparedData);
const result = await provider.decrypt(preparedAlgorithm, key, preparedData, { keyUsage: true });
return result;

@@ -697,3 +726,3 @@ }

const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.deriveBits(preparedAlgorithm, baseKey, length);
const result = await provider.deriveBits(preparedAlgorithm, baseKey, length, { keyUsage: true });
return result;

@@ -704,9 +733,8 @@ }

const preparedDerivedKeyType = this.prepareAlgorithm(derivedKeyType);
if (!("length" in preparedDerivedKeyType)) {
throw new RequiredPropertyError("derivedKeyType.length");
}
if (typeof preparedDerivedKeyType.length !== "number") {
throw new TypeError("derivedKeyType.length: Is not a number");
}
const derivedBits = await this.deriveBits(algorithm, baseKey, preparedDerivedKeyType.length);
const importProvider = this.getProvider(preparedDerivedKeyType.name);
importProvider.checkDerivedKeyParams(preparedDerivedKeyType);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
provider.checkCryptoKey(baseKey, "deriveKey");
const derivedBits = await provider.deriveBits(preparedAlgorithm, baseKey, derivedKeyType.length, { keyUsage: false });
return this.importKey("raw", derivedBits, derivedKeyType, extractable, keyUsages);

@@ -729,16 +757,34 @@ }

}
else {
if (!keyData.kty) {
throw new TypeError("keyData: Is not JSON");
}
}
return provider.importKey(format, keyData, preparedAlgorithm, extractable, keyUsages);
}
async wrapKey(format, key, wrappingKey, wrapAlgorithm) {
const keyData = await this.exportKey(format, key);
let keyData = await this.exportKey(format, key);
if (format === "jwk") {
const json = JSON.stringify(keyData);
return this.encrypt(wrapAlgorithm, wrappingKey, pvtsutils.Convert.FromUtf8String(json));
keyData = pvtsutils.Convert.FromUtf8String(json);
}
return this.encrypt(wrapAlgorithm, wrappingKey, keyData);
const preparedAlgorithm = this.prepareAlgorithm(wrapAlgorithm);
const preparedData = this.prepareData(keyData);
const provider = this.getProvider(preparedAlgorithm.name);
return provider.encrypt(preparedAlgorithm, wrappingKey, preparedData, { keyUsage: false });
}
async unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages) {
let keyData = await this.decrypt(unwrapAlgorithm, unwrappingKey, wrappedKey);
const preparedAlgorithm = this.prepareAlgorithm(unwrapAlgorithm);
const preparedData = this.prepareData(wrappedKey);
const provider = this.getProvider(preparedAlgorithm.name);
let keyData = await provider.decrypt(preparedAlgorithm, unwrappingKey, preparedData, { keyUsage: false });
if (format === "jwk") {
keyData = JSON.parse(pvtsutils.Convert.ToUtf8String(keyData));
try {
keyData = JSON.parse(pvtsutils.Convert.ToUtf8String(keyData));
}
catch (e) {
const error = new TypeError("wrappedKey: Is not a JSON");
error.internal = e;
throw error;
}
}

@@ -815,3 +861,4 @@ return this.importKey(format, keyData, unwrappedKeyAlgorithm, extractable, keyUsages);

exports.ProviderCrypto = ProviderCrypto;
exports.ProviderStorage = ProviderStorage;
exports.SubtleCrypto = SubtleCrypto;
exports.CryptoKey = CryptoKey;
{
"name": "webcrypto-core",
"version": "0.1.26",
"version": "1.0.1",
"description": "Common layer to be used by crypto libraries based on WebCrypto API for input validation.",
"main": "dist/webcrypto-core.js",
"module": "dist/webcrypto-core.es.js",
"types": "index.d.ts",
"directories": {
"test": "test"
},
"main": "index.js",
"types": "types/index.d.ts",
"scripts": {
"prepare": "npm run build",
"build": "npm run build:dist",
"build:es5": "rollup -c",
"build:map": "rollup -c -m",
"build:es2015": "rollup -c rollup.config.es.js",
"build:dist": "npm run build:es5 && npm run build:es2015",
"build:source": "tsc --declaration --declarationDir types",
"test": "mocha test",
"build": "npm run build:defs && npm run build:js",
"build:defs": "tsc --declaration --outDir types --emitDeclarationOnly",
"build:js": "rollup -c",
"test": "mocha",
"prepub": "npm run build",
"pub": "npm version patch && npm publish && git push",
"precoverage": "npm run build:map",
"coverage": "nyc npm test",

@@ -43,12 +35,15 @@ "precoveragehtml": "npm run coverage",

"dependencies": {
"tslib": "^1.7.1"
"pvtsutils": "^1.0.3",
"tslib": "^1.9.3"
},
"devDependencies": {
"@types/node": "^8.10.14",
"coveralls": "^3.0.1",
"mocha": "^5.1.1",
"nyc": "^11.7.3",
"rollup": "^0.58.2",
"rollup-plugin-typescript": "^0.8.1",
"typescript": "^2.8.3"
"@types/mocha": "^5.2.5",
"@types/node": "^10.12.18",
"coveralls": "^3.0.2",
"mocha": "^5.2.0",
"nyc": "^13.1.0",
"rollup": "^1.1.2",
"rollup-plugin-typescript": "^1.0.0",
"ts-node": "^8.0.1",
"typescript": "^3.2.4"
},

@@ -61,3 +56,19 @@ "author": "PeculiarVentures",

"homepage": "https://github.com/PeculiarVentures/webcrypto-core#readme",
"banner": "// Copyright (c) 2017, Peculiar Ventures, All rights reserved."
"banner": "// Copyright (c) 2017, Peculiar Ventures, All rights reserved.",
"nyc": {
"extension": [
".ts",
".tsx"
],
"include": [
"src/**/*.ts"
],
"exclude": [
"**/*.d.ts"
],
"reporter": [
"text-summary",
"html"
]
}
}
[![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/PeculiarVentures/webcrypto-core/master/LICENSE)
[![Build Status](https://travis-ci.org/PeculiarVentures/webcrypto-core.svg?branch=master)](https://travis-ci.org/PeculiarVentures/webcrypto-core)
[![Coverage Status](https://coveralls.io/repos/github/PeculiarVentures/webcrypto-core/badge.svg?branch=master)](https://coveralls.io/github/PeculiarVentures/webcrypto-core?branch=master)
[![npm version](https://badge.fury.io/js/webcrypto-core.svg)](https://badge.fury.io/js/webcrypto-core)
[![NPM](https://nodei.co/npm-dl/webcrypto-core.png?months=2&height=2)](https://nodei.co/npm/webcrypto-core/)
[![NPM](https://nodei.co/npm/webcrypto-core.png)](https://nodei.co/npm/webcrypto-core/)

@@ -13,54 +14,63 @@ # webcrypto-core

## Dependencies
## Installing
Install all dependencies
```
npm install
npm install webcrypto-core
```
> NOTE: `npm install` command downloads and installs modules to local folder.
> You can install all dependencies globally
## Example
typescript
```
npm install typescript --global
```
Current examples shows how you can implement your own WebCrypt interface
rollup
```
npm install rollup --global
```
```js
const core = require(".");
const crypto = require("crypto");
mocha
```
npm install mocha --global
```
class Sha1Provider extends core.ProviderCrypto {
Single line command for all modules
```
npm install typescript rollup mocha --global
```
constructor() {
super();
## Compilation
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
this.name = "SHA-1";
this.usages = [];
}
Compile the source code with declaration using the next command:
```
tsc --declaration
```
async onDigest(algorithm, data) {
const hash = crypto.createHash("SHA1").update(Buffer.from(data)).digest();
return new Uint8Array(hash).buffer;
}
## Test
```
npm test
```
}
## Size
class SubtleCrypto extends core.SubtleCrypto {
constructor() {
super();
| Files | Size |
|-------------------------|------------|
| webcrypto-core.js | 59Kb |
| webcrypto-core.min.js | 25Kb |
// Add SHA1 provider to SubtleCrypto
this.providers.set(new Sha1Provider());
}
}
class 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);
});
```
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc