1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-21 15:04:11 -05:00

perf: use ops for node:crypto ciphers (#17819)

Towards #17809
This commit is contained in:
Divy Srivastava 2023-02-20 22:22:28 +05:30 committed by GitHub
parent a16c11c5d1
commit ea7ca00c89
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
55 changed files with 239 additions and 7880 deletions

2
Cargo.lock generated
View file

@ -1195,8 +1195,10 @@ dependencies = [
"md4",
"once_cell",
"path-clean",
"rand",
"regex",
"ripemd",
"rsa",
"serde",
"sha-1 0.10.0",
"sha2",

View file

@ -120,6 +120,9 @@ url = { version = "2.3.1", features = ["serde", "expose_internals"] }
uuid = { version = "=1.1.2", features = ["v4"] }
zstd = "=0.11.2"
# crypto
rsa = { version = "0.7.0", default-features = false, features = ["std", "pem"] }
# webgpu
raw-window-handle = "0.5.0"
wgpu-core = "0.15"

View file

@ -0,0 +1,50 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import crypto from "node:crypto";
import { Buffer } from "node:buffer";
import {
assertEquals,
assertThrows,
} from "../../../test_util/std/testing/asserts.ts";
const rsaPrivateKey = Deno.readTextFileSync(
new URL("./testdata/rsa_private.pem", import.meta.url),
);
const rsaPublicKey = Deno.readTextFileSync(
new URL("./testdata/rsa_public.pem", import.meta.url),
);
const input = new TextEncoder().encode("hello world");
Deno.test({
name: "rsa public encrypt and private decrypt",
fn() {
const encrypted = crypto.publicEncrypt(Buffer.from(rsaPublicKey), input);
const decrypted = crypto.privateDecrypt(
Buffer.from(rsaPrivateKey),
Buffer.from(encrypted),
);
assertEquals(decrypted, input);
},
});
Deno.test({
name: "rsa private encrypt and private decrypt",
fn() {
const encrypted = crypto.privateEncrypt(rsaPrivateKey, input);
const decrypted = crypto.privateDecrypt(
rsaPrivateKey,
Buffer.from(encrypted),
);
assertEquals(decrypted, input);
},
});
Deno.test({
name: "rsa public decrypt fail",
fn() {
const encrypted = crypto.publicEncrypt(rsaPublicKey, input);
assertThrows(() =>
crypto.publicDecrypt(rsaPublicKey, Buffer.from(encrypted))
);
},
});

View file

@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC33FiIiiexwLe/
P8DZx5HsqFlmUO7/lvJ7necJVNwqdZ3ax5jpQB0p6uxfqeOvzcN3k5V7UFb/Am+n
kSNZMAZhsWzCU2Z4Pjh50QYz3f0Hour7/yIGStOLyYY3hgLK2K8TbhgjQPhdkw9+
QtKlpvbL8fLgONAoGrVOFnRQGcr70iFffsm79mgZhKVMgYiHPJqJgGHvCtkGg9zM
gS7p63+Q3ZWedtFS2RhMX3uCBy/mH6EOlRCNBbRmA4xxNzyf5GQaki3T+Iz9tOMj
dPP+CwV2LqEdylmBuik8vrfTb3qIHLKKBAI8lXN26wWtA3kN4L7NP+cbKlCRlqct
vhmylLH1AgMBAAECggEBAJLZ6ti7yDKgY+LcT/NiBDqKyEUBlbMNZIW5vAPnBKbh
JIDO9WIv9Fs7qSpLbnFHnr0OYtGIfMPXtUiYkyw0QJSc+upHZMvbno4llpes0eHc
jWVTBWETON4oywvj/Kz53vRc9eiKhxVuVWyagNcQgYSprjzLA+9UTcWeB67Guyrf
8YJUE2LC23RiMA5nGYoSHfVRl0c75gj7A0X9nwpAI+xw3kcaVHRIhA6WowA3Pj1o
pK2t692+NLVRylpvMMSS4rziDexomFykCFukYWYB/kZOOSSETSsTWoMXXl1KqsoZ
8IW06NR4rXtIgQ3sTfbYKGZNF5nWFgZ+hJVx0We1Qg0CgYEA8UovlB4nrBm7xH+u
7XXBMbqxADQm5vaEZxw9eluc+tP7cIAI4sglMIvL/FMpbd2pEeP/BkR76NTDzzDu
PAZvUGRavgEjy0O9j2NAs/WPK4tZF+vFdunhnSh4EHAF4Ij9kbsUi90NOpbGfVqP
dOaHqzgHKoR23Cuusk9wFQ2XTV8CgYEAwxHdEYT9xrpfrHPqSBQPpO0dWGKJEkrW
Ob+76rSfuL8wGR4OBNmQdhLuU9zTIh22pog+XPnLPAecC+4yu/wtJ2SPCKiKDbJB
re0CKPyRfGqzvA3njXwMxXazU4kGs+2Fg+xu/iKbaIjxXrclBLhkxhBtySrwAFhx
xOk6fFcPLSsCgYEAqS/Mdr5CMRGGMH0bKhPUWEtAixUGZhJaunX5wY71Xoc/Gh4c
nO+b7BNJ/+5L8WZog0vr6PgiLhrqBaCYm2wjpyoG2o2wDHm+NAlzN/wp3G2EFhrS
xdOux+S1c0kpRcyoiAO2n29rNDa+jOzwBBcU8ACEPdLOCQl0IEFFJO33tl8CgYBY
DOIqnEsovsucvh3MNzHwkg8i7CdPGHSmUIN0J9/ItpPxYn2VdtccVOM6+3xZ8+uU
M/9iXGZ+TDkFsZk4/VUsaNmfYOQf1oyLA2ZsNcU90bQbeHNCi/H/19qOJFXgNaCE
sd5P3DMl9lptFGIjRVBHjvbfTQBUR5fi+BusMGfrTQKBgQCTtzMEJP2sef883AJr
XuGVPLzwLi9eTBvPzc5r5pfkvh7mDDmWFxHZm5kctvavqgy32uUPsQgMi1Kz67bU
s5dY9MCVrN2elhTLD8LOiAz8836o3AxFefm5cUWGaU/aZWDYR0QtNqFdyHyRaodo
JJfnfK+oK1Eq7+PvpXfVN9BkYw==
-----END PRIVATE KEY-----

View file

@ -0,0 +1,9 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt9xYiIonscC3vz/A2ceR
7KhZZlDu/5bye53nCVTcKnWd2seY6UAdKersX6njr83Dd5OVe1BW/wJvp5EjWTAG
YbFswlNmeD44edEGM939B6Lq+/8iBkrTi8mGN4YCytivE24YI0D4XZMPfkLSpab2
y/Hy4DjQKBq1ThZ0UBnK+9IhX37Ju/ZoGYSlTIGIhzyaiYBh7wrZBoPczIEu6et/
kN2VnnbRUtkYTF97ggcv5h+hDpUQjQW0ZgOMcTc8n+RkGpIt0/iM/bTjI3Tz/gsF
di6hHcpZgbopPL630296iByyigQCPJVzdusFrQN5DeC+zT/nGypQkZanLb4ZspSx
9QIDAQAB
-----END PUBLIC KEY-----

View file

@ -33,7 +33,7 @@ p256 = { version = "0.11.1", features = ["ecdh"] }
p384 = "0.11.1"
rand.workspace = true
ring = { workspace = true, features = ["std"] }
rsa = { version = "0.7.0", default-features = false, features = ["std"] }
rsa.workspace = true
sec1 = "0.3.0"
serde.workspace = true
serde_bytes.workspace = true

View file

@ -20,8 +20,10 @@ md-5 = "0.10.5"
md4 = "0.10.2"
once_cell.workspace = true
path-clean = "=0.1.0"
rand.workspace = true
regex.workspace = true
ripemd = "0.1.3"
rsa.workspace = true
serde = "1.0.149"
sha-1 = "0.10.0"
sha2 = "0.10.6"

View file

@ -4,9 +4,17 @@ use deno_core::error::AnyError;
use deno_core::op;
use deno_core::OpState;
use deno_core::ResourceId;
use deno_core::StringOrBuffer;
use deno_core::ZeroCopyBuf;
use std::rc::Rc;
use rsa::padding::PaddingScheme;
use rsa::pkcs8::DecodePrivateKey;
use rsa::pkcs8::DecodePublicKey;
use rsa::PublicKey;
use rsa::RsaPrivateKey;
use rsa::RsaPublicKey;
mod digest;
#[op]
@ -47,3 +55,74 @@ pub fn op_node_hash_clone(
let context = state.resource_table.get::<digest::Context>(rid)?;
Ok(state.resource_table.add(context.as_ref().clone()))
}
#[op]
pub fn op_node_private_encrypt(
key: StringOrBuffer,
msg: StringOrBuffer,
padding: u32,
) -> Result<ZeroCopyBuf, AnyError> {
let key = RsaPrivateKey::from_pkcs8_pem((&key).try_into()?)?;
let mut rng = rand::thread_rng();
match padding {
1 => Ok(
key
.encrypt(&mut rng, PaddingScheme::new_pkcs1v15_encrypt(), &msg)?
.into(),
),
4 => Ok(
key
.encrypt(&mut rng, PaddingScheme::new_oaep::<sha1::Sha1>(), &msg)?
.into(),
),
_ => Err(type_error("Unknown padding")),
}
}
#[op]
pub fn op_node_private_decrypt(
key: StringOrBuffer,
msg: StringOrBuffer,
padding: u32,
) -> Result<ZeroCopyBuf, AnyError> {
let key = RsaPrivateKey::from_pkcs8_pem((&key).try_into()?)?;
match padding {
1 => Ok(
key
.decrypt(PaddingScheme::new_pkcs1v15_encrypt(), &msg)?
.into(),
),
4 => Ok(
key
.decrypt(PaddingScheme::new_oaep::<sha1::Sha1>(), &msg)?
.into(),
),
_ => Err(type_error("Unknown padding")),
}
}
#[op]
pub fn op_node_public_encrypt(
key: StringOrBuffer,
msg: StringOrBuffer,
padding: u32,
) -> Result<ZeroCopyBuf, AnyError> {
let key = RsaPublicKey::from_public_key_pem((&key).try_into()?)?;
let mut rng = rand::thread_rng();
match padding {
1 => Ok(
key
.encrypt(&mut rng, PaddingScheme::new_pkcs1v15_encrypt(), &msg)?
.into(),
),
4 => Ok(
key
.encrypt(&mut rng, PaddingScheme::new_oaep::<sha1::Sha1>(), &msg)?
.into(),
),
_ => Err(type_error("Unknown padding")),
}
}

View file

@ -98,47 +98,6 @@ pub fn init_polyfill() -> Extension {
let esm_files = include_js_files!(
dir "polyfills",
"_core.ts",
"_crypto/crypto_browserify/asn1.js/base/buffer.js",
"_crypto/crypto_browserify/asn1.js/base/node.js",
"_crypto/crypto_browserify/asn1.js/base/reporter.js",
"_crypto/crypto_browserify/asn1.js/constants/der.js",
"_crypto/crypto_browserify/asn1.js/decoders/der.js",
"_crypto/crypto_browserify/asn1.js/decoders/pem.js",
"_crypto/crypto_browserify/asn1.js/encoders/der.js",
"_crypto/crypto_browserify/asn1.js/encoders/pem.js",
"_crypto/crypto_browserify/asn1.js/mod.js",
"_crypto/crypto_browserify/bn.js/bn.js",
"_crypto/crypto_browserify/browserify_aes/aes.js",
"_crypto/crypto_browserify/browserify_aes/auth_cipher.js",
"_crypto/crypto_browserify/browserify_aes/decrypter.js",
"_crypto/crypto_browserify/browserify_aes/encrypter.js",
"_crypto/crypto_browserify/browserify_aes/ghash.js",
"_crypto/crypto_browserify/browserify_aes/incr32.js",
"_crypto/crypto_browserify/browserify_aes/mod.js",
"_crypto/crypto_browserify/browserify_aes/modes/cbc.js",
"_crypto/crypto_browserify/browserify_aes/modes/cfb.js",
"_crypto/crypto_browserify/browserify_aes/modes/cfb1.js",
"_crypto/crypto_browserify/browserify_aes/modes/cfb8.js",
"_crypto/crypto_browserify/browserify_aes/modes/ctr.js",
"_crypto/crypto_browserify/browserify_aes/modes/ecb.js",
"_crypto/crypto_browserify/browserify_aes/modes/mod.js",
"_crypto/crypto_browserify/browserify_aes/modes/ofb.js",
"_crypto/crypto_browserify/browserify_aes/stream_cipher.js",
"_crypto/crypto_browserify/browserify_aes/xor.ts",
"_crypto/crypto_browserify/browserify_rsa.js",
"_crypto/crypto_browserify/cipher_base.js",
"_crypto/crypto_browserify/evp_bytes_to_key.ts",
"_crypto/crypto_browserify/parse_asn1/asn1.js",
"_crypto/crypto_browserify/parse_asn1/certificate.js",
"_crypto/crypto_browserify/parse_asn1/fix_proc.js",
"_crypto/crypto_browserify/parse_asn1/mod.js",
"_crypto/crypto_browserify/public_encrypt/mgf.js",
"_crypto/crypto_browserify/public_encrypt/mod.js",
"_crypto/crypto_browserify/public_encrypt/private_decrypt.js",
"_crypto/crypto_browserify/public_encrypt/public_encrypt.js",
"_crypto/crypto_browserify/public_encrypt/with_public.js",
"_crypto/crypto_browserify/public_encrypt/xor.js",
"_crypto/crypto_browserify/randombytes.ts",
"_events.mjs",
"_fs/_fs_access.ts",
"_fs/_fs_appendFile.ts",
@ -411,6 +370,9 @@ pub fn init_polyfill() -> Extension {
crypto::op_node_hash_update::decl(),
crypto::op_node_hash_digest::decl(),
crypto::op_node_hash_clone::decl(),
crypto::op_node_private_encrypt::decl(),
crypto::op_node_private_decrypt::decl(),
crypto::op_node_public_encrypt::decl(),
winerror::op_node_sys_to_uv_error::decl(),
v8::op_v8_cached_data_version_tag::decl(),
v8::op_v8_get_heap_statistics::decl(),

View file

@ -1,2 +0,0 @@
This directory contains the libraries ported from
[crypto-browserify](https://github.com/crypto-browserify) organization.

View file

@ -1,167 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Fedor Indutny. All rights reserved. MIT license.
import { Reporter } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/base/reporter.js";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
export function DecoderBuffer(base, options) {
Reporter.call(this, options);
if (!Buffer.isBuffer(base)) {
this.error("Input not Buffer");
return;
}
this.base = base;
this.offset = 0;
this.length = base.length;
}
// inherits(DecoderBuffer, Reporter);
DecoderBuffer.prototype = Object.create(Reporter.prototype, {
constructor: {
value: DecoderBuffer,
enumerable: false,
writable: true,
configurable: true,
},
});
DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) {
if (data instanceof DecoderBuffer) {
return true;
}
// Or accept compatible API
const isCompatible = typeof data === "object" &&
Buffer.isBuffer(data.base) &&
data.constructor.name === "DecoderBuffer" &&
typeof data.offset === "number" &&
typeof data.length === "number" &&
typeof data.save === "function" &&
typeof data.restore === "function" &&
typeof data.isEmpty === "function" &&
typeof data.readUInt8 === "function" &&
typeof data.skip === "function" &&
typeof data.raw === "function";
return isCompatible;
};
DecoderBuffer.prototype.save = function save() {
return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
};
DecoderBuffer.prototype.restore = function restore(save) {
// Return skipped data
const res = new DecoderBuffer(this.base);
res.offset = save.offset;
res.length = this.offset;
this.offset = save.offset;
Reporter.prototype.restore.call(this, save.reporter);
return res;
};
DecoderBuffer.prototype.isEmpty = function isEmpty() {
return this.offset === this.length;
};
DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
if (this.offset + 1 <= this.length) {
return this.base.readUInt8(this.offset++, true);
} else {
return this.error(fail || "DecoderBuffer overrun");
}
};
DecoderBuffer.prototype.skip = function skip(bytes, fail) {
if (!(this.offset + bytes <= this.length)) {
return this.error(fail || "DecoderBuffer overrun");
}
const res = new DecoderBuffer(this.base);
// Share reporter state
res._reporterState = this._reporterState;
res.offset = this.offset;
res.length = this.offset + bytes;
this.offset += bytes;
return res;
};
DecoderBuffer.prototype.raw = function raw(save) {
return this.base.slice(save ? save.offset : this.offset, this.length);
};
export function EncoderBuffer(value, reporter) {
if (Array.isArray(value)) {
this.length = 0;
this.value = value.map(function (item) {
if (!EncoderBuffer.isEncoderBuffer(item)) {
item = new EncoderBuffer(item, reporter);
}
this.length += item.length;
return item;
}, this);
} else if (typeof value === "number") {
if (!(0 <= value && value <= 0xff)) {
return reporter.error("non-byte EncoderBuffer value");
}
this.value = value;
this.length = 1;
} else if (typeof value === "string") {
this.value = value;
this.length = Buffer.byteLength(value);
} else if (Buffer.isBuffer(value)) {
this.value = value;
this.length = value.length;
} else {
return reporter.error("Unsupported type: " + typeof value);
}
}
EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) {
if (data instanceof EncoderBuffer) {
return true;
}
// Or accept compatible API
const isCompatible = typeof data === "object" &&
data.constructor.name === "EncoderBuffer" &&
typeof data.length === "number" &&
typeof data.join === "function";
return isCompatible;
};
EncoderBuffer.prototype.join = function join(out, offset) {
if (!out) {
out = Buffer.alloc(this.length);
}
if (!offset) {
offset = 0;
}
if (this.length === 0) {
return out;
}
if (Array.isArray(this.value)) {
this.value.forEach(function (item) {
item.join(out, offset);
offset += item.length;
});
} else {
if (typeof this.value === "number") {
out[offset] = this.value;
} else if (typeof this.value === "string") {
out.write(this.value, offset);
} else if (Buffer.isBuffer(this.value)) {
this.value.copy(out, offset);
}
offset += this.length;
}
return out;
};

View file

@ -1,734 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Fedor Indutny. All rights reserved. MIT license.
import { Reporter } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/base/reporter.js";
import {
DecoderBuffer,
EncoderBuffer,
} from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/base/buffer.js";
import { assert } from "internal:deno_node/polyfills/_util/asserts.ts";
// Supported tags
const tags = [
"seq",
"seqof",
"set",
"setof",
"objid",
"bool",
"gentime",
"utctime",
"null_",
"enum",
"int",
"objDesc",
"bitstr",
"bmpstr",
"charstr",
"genstr",
"graphstr",
"ia5str",
"iso646str",
"numstr",
"octstr",
"printstr",
"t61str",
"unistr",
"utf8str",
"videostr",
];
// Public methods list
const methods = [
"key",
"obj",
"use",
"optional",
"explicit",
"implicit",
"def",
"choice",
"any",
"contains",
].concat(tags);
// Overrided methods list
const overrided = [
"_peekTag",
"_decodeTag",
"_use",
"_decodeStr",
"_decodeObjid",
"_decodeTime",
"_decodeNull",
"_decodeInt",
"_decodeBool",
"_decodeList",
"_encodeComposite",
"_encodeStr",
"_encodeObjid",
"_encodeTime",
"_encodeNull",
"_encodeInt",
"_encodeBool",
];
export function Node(enc, parent, name) {
const state = {};
this._baseState = state;
state.name = name;
state.enc = enc;
state.parent = parent || null;
state.children = null;
// State
state.tag = null;
state.args = null;
state.reverseArgs = null;
state.choice = null;
state.optional = false;
state.any = false;
state.obj = false;
state.use = null;
state.useDecoder = null;
state.key = null;
state["default"] = null;
state.explicit = null;
state.implicit = null;
state.contains = null;
// Should create new instance on each method
if (!state.parent) {
state.children = [];
this._wrap();
}
}
const stateProps = [
"enc",
"parent",
"children",
"tag",
"args",
"reverseArgs",
"choice",
"optional",
"any",
"obj",
"use",
"alteredUse",
"key",
"default",
"explicit",
"implicit",
"contains",
];
Node.prototype.clone = function clone() {
const state = this._baseState;
const cstate = {};
stateProps.forEach(function (prop) {
cstate[prop] = state[prop];
});
const res = new this.constructor(cstate.parent);
res._baseState = cstate;
return res;
};
Node.prototype._wrap = function wrap() {
const state = this._baseState;
methods.forEach(function (method) {
this[method] = function _wrappedMethod() {
const clone = new this.constructor(this);
state.children.push(clone);
return clone[method].apply(clone, arguments);
};
}, this);
};
Node.prototype._init = function init(body) {
const state = this._baseState;
assert(state.parent === null);
body.call(this);
// Filter children
state.children = state.children.filter(function (child) {
return child._baseState.parent === this;
}, this);
assert(state.children.length === 1, "Root node can have only one child");
};
Node.prototype._useArgs = function useArgs(args) {
const state = this._baseState;
// Filter children and args
const children = args.filter(function (arg) {
return arg instanceof this.constructor;
}, this);
args = args.filter(function (arg) {
return !(arg instanceof this.constructor);
}, this);
if (children.length !== 0) {
assert(state.children === null);
state.children = children;
// Replace parent to maintain backward link
children.forEach(function (child) {
child._baseState.parent = this;
}, this);
}
if (args.length !== 0) {
assert(state.args === null);
state.args = args;
state.reverseArgs = args.map(function (arg) {
if (typeof arg !== "object" || arg.constructor !== Object) {
return arg;
}
const res = {};
Object.keys(arg).forEach(function (key) {
if (key == (key | 0)) {
key |= 0;
}
const value = arg[key];
res[value] = key;
});
return res;
});
}
};
//
// Overrided methods
//
overrided.forEach(function (method) {
Node.prototype[method] = function _overrided() {
const state = this._baseState;
throw new Error(method + " not implemented for encoding: " + state.enc);
};
});
//
// Public methods
//
tags.forEach(function (tag) {
Node.prototype[tag] = function _tagMethod() {
const state = this._baseState;
const args = Array.prototype.slice.call(arguments);
assert(state.tag === null);
state.tag = tag;
this._useArgs(args);
return this;
};
});
Node.prototype.use = function use(item) {
assert(item);
const state = this._baseState;
assert(state.use === null);
state.use = item;
return this;
};
Node.prototype.optional = function optional() {
const state = this._baseState;
state.optional = true;
return this;
};
Node.prototype.def = function def(val) {
const state = this._baseState;
assert(state["default"] === null);
state["default"] = val;
state.optional = true;
return this;
};
Node.prototype.explicit = function explicit(num) {
const state = this._baseState;
assert(state.explicit === null && state.implicit === null);
state.explicit = num;
return this;
};
Node.prototype.implicit = function implicit(num) {
const state = this._baseState;
assert(state.explicit === null && state.implicit === null);
state.implicit = num;
return this;
};
Node.prototype.obj = function obj() {
const state = this._baseState;
const args = Array.prototype.slice.call(arguments);
state.obj = true;
if (args.length !== 0) {
this._useArgs(args);
}
return this;
};
Node.prototype.key = function key(newKey) {
const state = this._baseState;
assert(state.key === null);
state.key = newKey;
return this;
};
Node.prototype.any = function any() {
const state = this._baseState;
state.any = true;
return this;
};
Node.prototype.choice = function choice(obj) {
const state = this._baseState;
assert(state.choice === null);
state.choice = obj;
this._useArgs(
Object.keys(obj).map(function (key) {
return obj[key];
}),
);
return this;
};
Node.prototype.contains = function contains(item) {
const state = this._baseState;
assert(state.use === null);
state.contains = item;
return this;
};
//
// Decoding
//
Node.prototype._decode = function decode(input, options) {
const state = this._baseState;
// Decode root node
if (state.parent === null) {
return input.wrapResult(state.children[0]._decode(input, options));
}
let result = state["default"];
let present = true;
let prevKey = null;
if (state.key !== null) {
prevKey = input.enterKey(state.key);
}
// Check if tag is there
if (state.optional) {
let tag = null;
if (state.explicit !== null) {
tag = state.explicit;
} else if (state.implicit !== null) {
tag = state.implicit;
} else if (state.tag !== null) {
tag = state.tag;
}
if (tag === null && !state.any) {
// Trial and Error
const save = input.save();
try {
if (state.choice === null) {
this._decodeGeneric(state.tag, input, options);
} else {
this._decodeChoice(input, options);
}
present = true;
} catch (_e) {
present = false;
}
input.restore(save);
} else {
present = this._peekTag(input, tag, state.any);
if (input.isError(present)) {
return present;
}
}
}
// Push object on stack
let prevObj;
if (state.obj && present) {
prevObj = input.enterObject();
}
if (present) {
// Unwrap explicit values
if (state.explicit !== null) {
const explicit = this._decodeTag(input, state.explicit);
if (input.isError(explicit)) {
return explicit;
}
input = explicit;
}
const start = input.offset;
// Unwrap implicit and normal values
if (state.use === null && state.choice === null) {
let save;
if (state.any) {
save = input.save();
}
const body = this._decodeTag(
input,
state.implicit !== null ? state.implicit : state.tag,
state.any,
);
if (input.isError(body)) {
return body;
}
if (state.any) {
result = input.raw(save);
} else {
input = body;
}
}
if (options && options.track && state.tag !== null) {
options.track(input.path(), start, input.length, "tagged");
}
if (options && options.track && state.tag !== null) {
options.track(input.path(), input.offset, input.length, "content");
}
// Select proper method for tag
if (state.any) {
// no-op
} else if (state.choice === null) {
result = this._decodeGeneric(state.tag, input, options);
} else {
result = this._decodeChoice(input, options);
}
if (input.isError(result)) {
return result;
}
// Decode children
if (!state.any && state.choice === null && state.children !== null) {
state.children.forEach(function decodeChildren(child) {
// NOTE: We are ignoring errors here, to let parser continue with other
// parts of encoded data
child._decode(input, options);
});
}
// Decode contained/encoded by schema, only in bit or octet strings
if (state.contains && (state.tag === "octstr" || state.tag === "bitstr")) {
const data = new DecoderBuffer(result);
result = this._getUse(state.contains, input._reporterState.obj)
._decode(data, options);
}
}
// Pop object
if (state.obj && present) {
result = input.leaveObject(prevObj);
}
// Set key
if (state.key !== null && (result !== null || present === true)) {
input.leaveKey(prevKey, state.key, result);
} else if (prevKey !== null) {
input.exitKey(prevKey);
}
return result;
};
Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
const state = this._baseState;
if (tag === "seq" || tag === "set") {
return null;
}
if (tag === "seqof" || tag === "setof") {
return this._decodeList(input, tag, state.args[0], options);
} else if (/str$/.test(tag)) {
return this._decodeStr(input, tag, options);
} else if (tag === "objid" && state.args) {
return this._decodeObjid(input, state.args[0], state.args[1], options);
} else if (tag === "objid") {
return this._decodeObjid(input, null, null, options);
} else if (tag === "gentime" || tag === "utctime") {
return this._decodeTime(input, tag, options);
} else if (tag === "null_") {
return this._decodeNull(input, options);
} else if (tag === "bool") {
return this._decodeBool(input, options);
} else if (tag === "objDesc") {
return this._decodeStr(input, tag, options);
} else if (tag === "int" || tag === "enum") {
return this._decodeInt(input, state.args && state.args[0], options);
}
if (state.use !== null) {
return this._getUse(state.use, input._reporterState.obj)
._decode(input, options);
} else {
return input.error("unknown tag: " + tag);
}
};
Node.prototype._getUse = function _getUse(entity, obj) {
const state = this._baseState;
// Create altered use decoder if implicit is set
state.useDecoder = this._use(entity, obj);
assert(state.useDecoder._baseState.parent === null);
state.useDecoder = state.useDecoder._baseState.children[0];
if (state.implicit !== state.useDecoder._baseState.implicit) {
state.useDecoder = state.useDecoder.clone();
state.useDecoder._baseState.implicit = state.implicit;
}
return state.useDecoder;
};
Node.prototype._decodeChoice = function decodeChoice(input, options) {
const state = this._baseState;
let result = null;
let match = false;
Object.keys(state.choice).some(function (key) {
const save = input.save();
const node = state.choice[key];
try {
const value = node._decode(input, options);
if (input.isError(value)) {
return false;
}
result = { type: key, value: value };
match = true;
} catch (_e) {
input.restore(save);
return false;
}
return true;
}, this);
if (!match) {
return input.error("Choice not matched");
}
return result;
};
//
// Encoding
//
Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
return new EncoderBuffer(data, this.reporter);
};
Node.prototype._encode = function encode(data, reporter, parent) {
const state = this._baseState;
if (state["default"] !== null && state["default"] === data) {
return;
}
const result = this._encodeValue(data, reporter, parent);
if (result === undefined) {
return;
}
if (this._skipDefault(result, reporter, parent)) {
return;
}
return result;
};
Node.prototype._encodeValue = function encode(data, reporter, parent) {
const state = this._baseState;
// Decode root node
if (state.parent === null) {
return state.children[0]._encode(data, reporter || new Reporter());
}
let result = null;
// Set reporter to share it with a child class
this.reporter = reporter;
// Check if data is there
if (state.optional && data === undefined) {
if (state["default"] !== null) {
data = state["default"];
} else {
return;
}
}
// Encode children first
let content = null;
let primitive = false;
if (state.any) {
// Anything that was given is translated to buffer
result = this._createEncoderBuffer(data);
} else if (state.choice) {
result = this._encodeChoice(data, reporter);
} else if (state.contains) {
content = this._getUse(state.contains, parent)._encode(data, reporter);
primitive = true;
} else if (state.children) {
content = state.children.map(function (child) {
if (child._baseState.tag === "null_") {
return child._encode(null, reporter, data);
}
if (child._baseState.key === null) {
return reporter.error("Child should have a key");
}
const prevKey = reporter.enterKey(child._baseState.key);
if (typeof data !== "object") {
return reporter.error("Child expected, but input is not object");
}
const res = child._encode(data[child._baseState.key], reporter, data);
reporter.leaveKey(prevKey);
return res;
}, this).filter(function (child) {
return child;
});
content = this._createEncoderBuffer(content);
} else {
if (state.tag === "seqof" || state.tag === "setof") {
// TODO(indutny): this should be thrown on DSL level
if (!(state.args && state.args.length === 1)) {
return reporter.error("Too many args for : " + state.tag);
}
if (!Array.isArray(data)) {
return reporter.error("seqof/setof, but data is not Array");
}
const child = this.clone();
child._baseState.implicit = null;
content = this._createEncoderBuffer(data.map(function (item) {
const state = this._baseState;
return this._getUse(state.args[0], data)._encode(item, reporter);
}, child));
} else if (state.use !== null) {
result = this._getUse(state.use, parent)._encode(data, reporter);
} else {
content = this._encodePrimitive(state.tag, data);
primitive = true;
}
}
// Encode data itself
if (!state.any && state.choice === null) {
const tag = state.implicit !== null ? state.implicit : state.tag;
const cls = state.implicit === null ? "universal" : "context";
if (tag === null) {
if (state.use === null) {
reporter.error("Tag could be omitted only for .use()");
}
} else {
if (state.use === null) {
result = this._encodeComposite(tag, primitive, cls, content);
}
}
}
// Wrap in explicit
if (state.explicit !== null) {
result = this._encodeComposite(state.explicit, false, "context", result);
}
return result;
};
Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
const state = this._baseState;
const node = state.choice[data.type];
if (!node) {
assert(
false,
data.type + " not found in " +
JSON.stringify(Object.keys(state.choice)),
);
}
return node._encode(data.value, reporter);
};
Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
const state = this._baseState;
if (/str$/.test(tag)) {
return this._encodeStr(data, tag);
} else if (tag === "objid" && state.args) {
return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
} else if (tag === "objid") {
return this._encodeObjid(data, null, null);
} else if (tag === "gentime" || tag === "utctime") {
return this._encodeTime(data, tag);
} else if (tag === "null_") {
return this._encodeNull();
} else if (tag === "int" || tag === "enum") {
return this._encodeInt(data, state.args && state.reverseArgs[0]);
} else if (tag === "bool") {
return this._encodeBool(data);
} else if (tag === "objDesc") {
return this._encodeStr(data, tag);
} else {
throw new Error("Unsupported tag: " + tag);
}
};
Node.prototype._isNumstr = function isNumstr(str) {
return /^[0-9 ]*$/.test(str);
};
Node.prototype._isPrintstr = function isPrintstr(str) {
return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str);
};

View file

@ -1,138 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Fedor Indutny. All rights reserved. MIT license.
export function Reporter(options) {
this._reporterState = {
obj: null,
path: [],
options: options || {},
errors: [],
};
}
Reporter.prototype.isError = function isError(obj) {
return obj instanceof ReporterError;
};
Reporter.prototype.save = function save() {
const state = this._reporterState;
return { obj: state.obj, pathLen: state.path.length };
};
Reporter.prototype.restore = function restore(data) {
const state = this._reporterState;
state.obj = data.obj;
state.path = state.path.slice(0, data.pathLen);
};
Reporter.prototype.enterKey = function enterKey(key) {
return this._reporterState.path.push(key);
};
Reporter.prototype.exitKey = function exitKey(index) {
const state = this._reporterState;
state.path = state.path.slice(0, index - 1);
};
Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
const state = this._reporterState;
this.exitKey(index);
if (state.obj !== null) {
state.obj[key] = value;
}
};
Reporter.prototype.path = function path() {
return this._reporterState.path.join("/");
};
Reporter.prototype.enterObject = function enterObject() {
const state = this._reporterState;
const prev = state.obj;
state.obj = {};
return prev;
};
Reporter.prototype.leaveObject = function leaveObject(prev) {
const state = this._reporterState;
const now = state.obj;
state.obj = prev;
return now;
};
Reporter.prototype.error = function error(msg) {
let err;
const state = this._reporterState;
const inherited = msg instanceof ReporterError;
if (inherited) {
err = msg;
} else {
err = new ReporterError(
state.path.map(function (elem) {
return "[" + JSON.stringify(elem) + "]";
}).join(""),
msg.message || msg,
msg.stack,
);
}
if (!state.options.partial) {
throw err;
}
if (!inherited) {
state.errors.push(err);
}
return err;
};
Reporter.prototype.wrapResult = function wrapResult(result) {
const state = this._reporterState;
if (!state.options.partial) {
return result;
}
return {
result: this.isError(result) ? null : result,
errors: state.errors,
};
};
function ReporterError(path, msg) {
this.path = path;
this.rethrow(msg);
}
// inherits(ReporterError, Error);
ReporterError.prototype = Object.create(Error.prototype, {
constructor: {
value: ReporterError,
enumerable: false,
writable: true,
configurable: true,
},
});
ReporterError.prototype.rethrow = function rethrow(msg) {
this.message = msg + " at: " + (this.path || "(shallow)");
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ReporterError);
}
if (!this.stack) {
try {
// IE only adds stack when thrown
throw new Error(this.message);
} catch (e) {
this.stack = e.stack;
}
}
return this;
};

View file

@ -1,60 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Fedor Indutny. All rights reserved. MIT license.
// Helper
function reverse(map) {
const res = {};
Object.keys(map).forEach(function (key) {
// Convert key to integer if it is stringified
if ((key | 0) == key) {
key = key | 0;
}
const value = map[key];
res[value] = key;
});
return res;
}
export const tagClass = {
0: "universal",
1: "application",
2: "context",
3: "private",
};
export const tagClassByName = reverse(tagClass);
export const tag = {
0x00: "end",
0x01: "bool",
0x02: "int",
0x03: "bitstr",
0x04: "octstr",
0x05: "null_",
0x06: "objid",
0x07: "objDesc",
0x08: "external",
0x09: "real",
0x0a: "enum",
0x0b: "embed",
0x0c: "utf8str",
0x0d: "relativeOid",
0x10: "seq",
0x11: "set",
0x12: "numstr",
0x13: "printstr",
0x14: "t61str",
0x15: "videostr",
0x16: "ia5str",
0x17: "utctime",
0x18: "gentime",
0x19: "graphstr",
0x1a: "iso646str",
0x1b: "genstr",
0x1c: "unistr",
0x1d: "charstr",
0x1e: "bmpstr",
};
export const tagByName = reverse(tag);

View file

@ -1,386 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Fedor Indutny. All rights reserved. MIT license.
import bignum from "internal:deno_node/polyfills/_crypto/crypto_browserify/bn.js/bn.js";
import { DecoderBuffer } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/base/buffer.js";
import { Node } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/base/node.js";
import * as der from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/constants/der.js";
export function DERDecoder(entity) {
this.enc = "der";
this.name = entity.name;
this.entity = entity;
// Construct base tree
this.tree = new DERNode();
this.tree._init(entity.body);
}
DERDecoder.prototype.decode = function decode(data, options) {
if (!DecoderBuffer.isDecoderBuffer(data)) {
data = new DecoderBuffer(data, options);
}
return this.tree._decode(data, options);
};
// Tree methods
function DERNode(parent) {
Node.call(this, "der", parent);
}
// inherits(DERNode, Node);
DERNode.prototype = Object.create(Node.prototype, {
constructor: {
value: DERNode,
enumerable: false,
writable: true,
configurable: true,
},
});
DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
if (buffer.isEmpty()) {
return false;
}
const state = buffer.save();
const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
if (buffer.isError(decodedTag)) {
return decodedTag;
}
buffer.restore(state);
return decodedTag.tag === tag || decodedTag.tagStr === tag ||
(decodedTag.tagStr + "of") === tag || any;
};
DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
const decodedTag = derDecodeTag(
buffer,
'Failed to decode tag of "' + tag + '"',
);
if (buffer.isError(decodedTag)) {
return decodedTag;
}
let len = derDecodeLen(
buffer,
decodedTag.primitive,
'Failed to get length of "' + tag + '"',
);
// Failure
if (buffer.isError(len)) {
return len;
}
if (
!any &&
decodedTag.tag !== tag &&
decodedTag.tagStr !== tag &&
decodedTag.tagStr + "of" !== tag
) {
return buffer.error('Failed to match tag: "' + tag + '"');
}
if (decodedTag.primitive || len !== null) {
return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
}
// Indefinite length... find END tag
const state = buffer.save();
const res = this._skipUntilEnd(
buffer,
'Failed to skip indefinite length body: "' + this.tag + '"',
);
if (buffer.isError(res)) {
return res;
}
len = buffer.offset - state.offset;
buffer.restore(state);
return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
};
DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
for (;;) {
const tag = derDecodeTag(buffer, fail);
if (buffer.isError(tag)) {
return tag;
}
const len = derDecodeLen(buffer, tag.primitive, fail);
if (buffer.isError(len)) {
return len;
}
let res;
if (tag.primitive || len !== null) {
res = buffer.skip(len);
} else {
res = this._skipUntilEnd(buffer, fail);
}
// Failure
if (buffer.isError(res)) {
return res;
}
if (tag.tagStr === "end") {
break;
}
}
};
DERNode.prototype._decodeList = function decodeList(
buffer,
_tag,
decoder,
options,
) {
const result = [];
while (!buffer.isEmpty()) {
const possibleEnd = this._peekTag(buffer, "end");
if (buffer.isError(possibleEnd)) {
return possibleEnd;
}
const res = decoder.decode(buffer, "der", options);
if (buffer.isError(res) && possibleEnd) {
break;
}
result.push(res);
}
return result;
};
DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
if (tag === "bitstr") {
const unused = buffer.readUInt8();
if (buffer.isError(unused)) {
return unused;
}
return { unused: unused, data: buffer.raw() };
} else if (tag === "bmpstr") {
const raw = buffer.raw();
if (raw.length % 2 === 1) {
return buffer.error("Decoding of string type: bmpstr length mismatch");
}
let str = "";
for (let i = 0; i < raw.length / 2; i++) {
str += String.fromCharCode(raw.readUInt16BE(i * 2));
}
return str;
} else if (tag === "numstr") {
const numstr = buffer.raw().toString("ascii");
if (!this._isNumstr(numstr)) {
return buffer.error(
"Decoding of string type: " +
"numstr unsupported characters",
);
}
return numstr;
} else if (tag === "octstr") {
return buffer.raw();
} else if (tag === "objDesc") {
return buffer.raw();
} else if (tag === "printstr") {
const printstr = buffer.raw().toString("ascii");
if (!this._isPrintstr(printstr)) {
return buffer.error(
"Decoding of string type: " +
"printstr unsupported characters",
);
}
return printstr;
} else if (/str$/.test(tag)) {
return buffer.raw().toString();
} else {
return buffer.error("Decoding of string type: " + tag + " unsupported");
}
};
DERNode.prototype._decodeObjid = function decodeObjid(
buffer,
values,
relative,
) {
let result;
const identifiers = [];
let ident = 0;
let subident = 0;
while (!buffer.isEmpty()) {
subident = buffer.readUInt8();
ident <<= 7;
ident |= subident & 0x7f;
if ((subident & 0x80) === 0) {
identifiers.push(ident);
ident = 0;
}
}
if (subident & 0x80) {
identifiers.push(ident);
}
const first = (identifiers[0] / 40) | 0;
const second = identifiers[0] % 40;
if (relative) {
result = identifiers;
} else {
result = [first, second].concat(identifiers.slice(1));
}
if (values) {
let tmp = values[result.join(" ")];
if (tmp === undefined) {
tmp = values[result.join(".")];
}
if (tmp !== undefined) {
result = tmp;
}
}
return result;
};
DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
const str = buffer.raw().toString();
let year;
let mon;
let day;
let hour;
let min;
let sec;
if (tag === "gentime") {
year = str.slice(0, 4) | 0;
mon = str.slice(4, 6) | 0;
day = str.slice(6, 8) | 0;
hour = str.slice(8, 10) | 0;
min = str.slice(10, 12) | 0;
sec = str.slice(12, 14) | 0;
} else if (tag === "utctime") {
year = str.slice(0, 2) | 0;
mon = str.slice(2, 4) | 0;
day = str.slice(4, 6) | 0;
hour = str.slice(6, 8) | 0;
min = str.slice(8, 10) | 0;
sec = str.slice(10, 12) | 0;
if (year < 70) {
year = 2000 + year;
} else {
year = 1900 + year;
}
} else {
return buffer.error("Decoding " + tag + " time is not supported yet");
}
return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
};
DERNode.prototype._decodeNull = function decodeNull() {
return null;
};
DERNode.prototype._decodeBool = function decodeBool(buffer) {
const res = buffer.readUInt8();
if (buffer.isError(res)) {
return res;
} else {
return res !== 0;
}
};
DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
// Bigint, return as it is (assume big endian)
const raw = buffer.raw();
let res = new bignum(raw);
if (values) {
res = values[res.toString(10)] || res;
}
return res;
};
DERNode.prototype._use = function use(entity, obj) {
if (typeof entity === "function") {
entity = entity(obj);
}
return entity._getDecoder("der").tree;
};
// Utility methods
function derDecodeTag(buf, fail) {
let tag = buf.readUInt8(fail);
if (buf.isError(tag)) {
return tag;
}
const cls = der.tagClass[tag >> 6];
const primitive = (tag & 0x20) === 0;
// Multi-octet tag - load
if ((tag & 0x1f) === 0x1f) {
let oct = tag;
tag = 0;
while ((oct & 0x80) === 0x80) {
oct = buf.readUInt8(fail);
if (buf.isError(oct)) {
return oct;
}
tag <<= 7;
tag |= oct & 0x7f;
}
} else {
tag &= 0x1f;
}
const tagStr = der.tag[tag];
return {
cls: cls,
primitive: primitive,
tag: tag,
tagStr: tagStr,
};
}
function derDecodeLen(buf, primitive, fail) {
let len = buf.readUInt8(fail);
if (buf.isError(len)) {
return len;
}
// Indefinite form
if (!primitive && len === 0x80) {
return null;
}
// Definite form
if ((len & 0x80) === 0) {
// Short form
return len;
}
// Long form
const num = len & 0x7f;
if (num > 4) {
return buf.error("length octect is too long");
}
len = 0;
for (let i = 0; i < num; i++) {
len <<= 8;
const j = buf.readUInt8(fail);
if (buf.isError(j)) {
return j;
}
len |= j;
}
return len;
}

View file

@ -1,63 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Fedor Indutny. All rights reserved. MIT license.
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import { DERDecoder } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/decoders/der.js";
export function PEMDecoder(entity) {
DERDecoder.call(this, entity);
this.enc = "pem";
}
// inherits(PEMDecoder, DERDecoder);
PEMDecoder.prototype = Object.create(DERDecoder.prototype, {
constructor: {
value: PEMDecoder,
enumerable: false,
writable: true,
configurable: true,
},
});
PEMDecoder.prototype.decode = function decode(data, options) {
const lines = data.toString().split(/[\r\n]+/g);
const label = options.label.toUpperCase();
const re = /^-----(BEGIN|END) ([^-]+)-----$/;
let start = -1;
let end = -1;
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(re);
if (match === null) {
continue;
}
if (match[2] !== label) {
continue;
}
if (start === -1) {
if (match[1] !== "BEGIN") {
break;
}
start = i;
} else {
if (match[1] !== "END") {
break;
}
end = i;
break;
}
}
if (start === -1 || end === -1) {
throw new Error("PEM section not found for: " + label);
}
const base64 = lines.slice(start + 1, end).join("");
// Remove excessive symbols
base64.replace(/[^a-z0-9+/=]+/gi, "");
const input = Buffer.from(base64, "base64");
return DERDecoder.prototype.decode.call(this, input, options);
};

View file

@ -1,348 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Fedor Indutny. All rights reserved. MIT license.
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import { Node } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/base/node.js";
// Import DER constants
import * as der from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/constants/der.js";
export function DEREncoder(entity) {
this.enc = "der";
this.name = entity.name;
this.entity = entity;
// Construct base tree
this.tree = new DERNode();
this.tree._init(entity.body);
}
DEREncoder.prototype.encode = function encode(data, reporter) {
return this.tree._encode(data, reporter).join();
};
// Tree methods
function DERNode(parent) {
Node.call(this, "der", parent);
}
// inherits(DERNode, Node);
DERNode.prototype = Object.create(Node.prototype, {
constructor: {
value: DERNode,
enumerable: false,
writable: true,
configurable: true,
},
});
DERNode.prototype._encodeComposite = function encodeComposite(
tag,
primitive,
cls,
content,
) {
const encodedTag = encodeTag(tag, primitive, cls, this.reporter);
// Short form
if (content.length < 0x80) {
const header = Buffer.alloc(2);
header[0] = encodedTag;
header[1] = content.length;
return this._createEncoderBuffer([header, content]);
}
// Long form
// Count octets required to store length
let lenOctets = 1;
for (let i = content.length; i >= 0x100; i >>= 8) {
lenOctets++;
}
const header = Buffer.alloc(1 + 1 + lenOctets);
header[0] = encodedTag;
header[1] = 0x80 | lenOctets;
for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) {
header[i] = j & 0xff;
}
return this._createEncoderBuffer([header, content]);
};
DERNode.prototype._encodeStr = function encodeStr(str, tag) {
if (tag === "bitstr") {
return this._createEncoderBuffer([str.unused | 0, str.data]);
} else if (tag === "bmpstr") {
const buf = Buffer.alloc(str.length * 2);
for (let i = 0; i < str.length; i++) {
buf.writeUInt16BE(str.charCodeAt(i), i * 2);
}
return this._createEncoderBuffer(buf);
} else if (tag === "numstr") {
if (!this._isNumstr(str)) {
return this.reporter.error(
"Encoding of string type: numstr supports " +
"only digits and space",
);
}
return this._createEncoderBuffer(str);
} else if (tag === "printstr") {
if (!this._isPrintstr(str)) {
return this.reporter.error(
"Encoding of string type: printstr supports " +
"only latin upper and lower case letters, " +
"digits, space, apostrophe, left and rigth " +
"parenthesis, plus sign, comma, hyphen, " +
"dot, slash, colon, equal sign, " +
"question mark",
);
}
return this._createEncoderBuffer(str);
} else if (/str$/.test(tag)) {
return this._createEncoderBuffer(str);
} else if (tag === "objDesc") {
return this._createEncoderBuffer(str);
} else {
return this.reporter.error(
"Encoding of string type: " + tag +
" unsupported",
);
}
};
DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
if (typeof id === "string") {
if (!values) {
return this.reporter.error("string objid given, but no values map found");
}
// deno-lint-ignore no-prototype-builtins
if (!values.hasOwnProperty(id)) {
return this.reporter.error("objid not found in values map");
}
id = values[id].split(/[\s.]+/g);
for (let i = 0; i < id.length; i++) {
id[i] |= 0;
}
} else if (Array.isArray(id)) {
id = id.slice();
for (let i = 0; i < id.length; i++) {
id[i] |= 0;
}
}
if (!Array.isArray(id)) {
return this.reporter.error(
"objid() should be either array or string, " +
"got: " + JSON.stringify(id),
);
}
if (!relative) {
if (id[1] >= 40) {
return this.reporter.error("Second objid identifier OOB");
}
id.splice(0, 2, id[0] * 40 + id[1]);
}
// Count number of octets
let size = 0;
for (let i = 0; i < id.length; i++) {
let ident = id[i];
for (size++; ident >= 0x80; ident >>= 7) {
size++;
}
}
const objid = Buffer.alloc(size);
let offset = objid.length - 1;
for (let i = id.length - 1; i >= 0; i--) {
let ident = id[i];
objid[offset--] = ident & 0x7f;
while ((ident >>= 7) > 0) {
objid[offset--] = 0x80 | (ident & 0x7f);
}
}
return this._createEncoderBuffer(objid);
};
function two(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
}
DERNode.prototype._encodeTime = function encodeTime(time, tag) {
let str;
const date = new Date(time);
if (tag === "gentime") {
str = [
two(date.getUTCFullYear()),
two(date.getUTCMonth() + 1),
two(date.getUTCDate()),
two(date.getUTCHours()),
two(date.getUTCMinutes()),
two(date.getUTCSeconds()),
"Z",
].join("");
} else if (tag === "utctime") {
str = [
two(date.getUTCFullYear() % 100),
two(date.getUTCMonth() + 1),
two(date.getUTCDate()),
two(date.getUTCHours()),
two(date.getUTCMinutes()),
two(date.getUTCSeconds()),
"Z",
].join("");
} else {
this.reporter.error("Encoding " + tag + " time is not supported yet");
}
return this._encodeStr(str, "octstr");
};
DERNode.prototype._encodeNull = function encodeNull() {
return this._createEncoderBuffer("");
};
DERNode.prototype._encodeInt = function encodeInt(num, values) {
if (typeof num === "string") {
if (!values) {
return this.reporter.error("String int or enum given, but no values map");
}
// deno-lint-ignore no-prototype-builtins
if (!values.hasOwnProperty(num)) {
return this.reporter.error(
"Values map doesn't contain: " +
JSON.stringify(num),
);
}
num = values[num];
}
// Bignum, assume big endian
if (typeof num !== "number" && !Buffer.isBuffer(num)) {
const numArray = num.toArray();
if (!num.sign && numArray[0] & 0x80) {
numArray.unshift(0);
}
num = Buffer.from(numArray);
}
if (Buffer.isBuffer(num)) {
let size = num.length;
if (num.length === 0) {
size++;
}
const out = Buffer.alloc(size);
num.copy(out);
if (num.length === 0) {
out[0] = 0;
}
return this._createEncoderBuffer(out);
}
if (num < 0x80) {
return this._createEncoderBuffer(num);
}
if (num < 0x100) {
return this._createEncoderBuffer([0, num]);
}
let size = 1;
for (let i = num; i >= 0x100; i >>= 8) {
size++;
}
const out = new Array(size);
for (let i = out.length - 1; i >= 0; i--) {
out[i] = num & 0xff;
num >>= 8;
}
if (out[0] & 0x80) {
out.unshift(0);
}
return this._createEncoderBuffer(Buffer.from(out));
};
DERNode.prototype._encodeBool = function encodeBool(value) {
return this._createEncoderBuffer(value ? 0xff : 0);
};
DERNode.prototype._use = function use(entity, obj) {
if (typeof entity === "function") {
entity = entity(obj);
}
return entity._getEncoder("der").tree;
};
DERNode.prototype._skipDefault = function skipDefault(
dataBuffer,
reporter,
parent,
) {
const state = this._baseState;
let i;
if (state["default"] === null) {
return false;
}
const data = dataBuffer.join();
if (state.defaultBuffer === undefined) {
state.defaultBuffer = this._encodeValue(state["default"], reporter, parent)
.join();
}
if (data.length !== state.defaultBuffer.length) {
return false;
}
for (i = 0; i < data.length; i++) {
if (data[i] !== state.defaultBuffer[i]) {
return false;
}
}
return true;
};
// Utility methods
function encodeTag(tag, primitive, cls, reporter) {
let res;
if (tag === "seqof") {
tag = "seq";
} else if (tag === "setof") {
tag = "set";
}
// deno-lint-ignore no-prototype-builtins
if (der.tagByName.hasOwnProperty(tag)) {
res = der.tagByName[tag];
} else if (typeof tag === "number" && (tag | 0) === tag) {
res = tag;
} else {
return reporter.error("Unknown tag: " + tag);
}
if (res >= 0x1f) {
return reporter.error("Multi-octet tag encoding unsupported");
}
if (!primitive) {
res |= 0x20;
}
res |= der.tagClassByName[cls || "universal"] << 6;
return res;
}

View file

@ -1,30 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Fedor Indutny. All rights reserved. MIT license.
import { DEREncoder } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/encoders/der.js";
export function PEMEncoder(entity) {
DEREncoder.call(this, entity);
this.enc = "pem";
}
// inherits(PEMEncoder, DEREncoder);
PEMEncoder.prototype = Object.create(DEREncoder.prototype, {
constructor: {
value: PEMEncoder,
enumerable: false,
writable: true,
configurable: true,
},
});
PEMEncoder.prototype.encode = function encode(data, options) {
const buf = DEREncoder.prototype.encode.call(this, data);
const p = buf.toString("base64");
const out = ["-----BEGIN " + options.label + "-----"];
for (let i = 0; i < p.length; i += 64) {
out.push(p.slice(i, i + 64));
}
out.push("-----END " + options.label + "-----");
return out.join("\n");
};

View file

@ -1,96 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Fedor Indutny. All rights reserved. MIT license.
import bignum from "internal:deno_node/polyfills/_crypto/crypto_browserify/bn.js/bn.js";
import { Node } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/base/node.js";
import {
DecoderBuffer,
EncoderBuffer,
} from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/base/buffer.js";
import { Reporter } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/base/reporter.js";
import { DEREncoder } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/encoders/der.js";
import { PEMEncoder } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/encoders/pem.js";
import { DERDecoder } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/decoders/der.js";
import { PEMDecoder } from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/decoders/pem.js";
import * as der from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/constants/der.js";
export const base = {
DecoderBuffer,
EncoderBuffer,
Node,
Reporter,
};
export const encoders = { der: DEREncoder, pem: PEMEncoder };
export const decoders = { der: DERDecoder, pem: PEMDecoder };
export const constants = { der };
export { bignum };
export function define(name, body) {
return new Entity(name, body);
}
function Entity(name, body) {
this.name = name;
this.body = body;
this.decoders = {};
this.encoders = {};
}
Entity.prototype._createNamed = function createNamed(Base) {
const name = this.name;
function Generated(entity) {
this._initNamed(entity, name);
}
// inherits(Generated, Base);
Generated.prototype = Object.create(Base.prototype, {
constructor: {
value: Generated,
enumerable: false,
writable: true,
configurable: true,
},
});
Generated.prototype._initNamed = function _initNamed(entity, name) {
Base.call(this, entity, name);
};
return new Generated(this);
};
Entity.prototype._getDecoder = function _getDecoder(enc) {
enc = enc || "der";
// Lazily create decoder
// deno-lint-ignore no-prototype-builtins
if (!this.decoders.hasOwnProperty(enc)) {
this.decoders[enc] = this._createNamed(decoders[enc]);
}
return this.decoders[enc];
};
Entity.prototype.decode = function decode(data, enc, options) {
return this._getDecoder(enc).decode(data, options);
};
Entity.prototype._getEncoder = function _getEncoder(enc) {
enc = enc || "der";
// Lazily create encoder
// deno-lint-ignore no-prototype-builtins
if (!this.encoders.hasOwnProperty(enc)) {
this.encoders[enc] = this._createNamed(encoders[enc]);
}
return this.encoders[enc];
};
Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
return this._getEncoder(enc).encode(data, reporter);
};
export default {
base,
bignum,
constants,
decoders,
define,
encoders,
};

File diff suppressed because it is too large Load diff

View file

@ -1,244 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
// based on the aes implimentation in triple sec
// https://github.com/keybase/triplesec
// which is in turn based on the one from crypto-js
// https://code.google.com/p/crypto-js/
// deno-lint-ignore-file no-var no-inner-declarations
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
function asUInt32Array(buf) {
if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
var len = (buf.length / 4) | 0;
var out = new Array(len);
for (var i = 0; i < len; i++) {
out[i] = buf.readUInt32BE(i * 4);
}
return out;
}
function scrubVec(v) {
for (var i = 0; i < v.length; v++) {
v[i] = 0;
}
}
function cryptBlock(M, keySchedule, SUB_MIX, SBOX, nRounds) {
var SUB_MIX0 = SUB_MIX[0];
var SUB_MIX1 = SUB_MIX[1];
var SUB_MIX2 = SUB_MIX[2];
var SUB_MIX3 = SUB_MIX[3];
var s0 = M[0] ^ keySchedule[0];
var s1 = M[1] ^ keySchedule[1];
var s2 = M[2] ^ keySchedule[2];
var s3 = M[3] ^ keySchedule[3];
var t0, t1, t2, t3;
var ksRow = 4;
for (var round = 1; round < nRounds; round++) {
t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^
SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++];
t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^
SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++];
t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^
SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++];
t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^
SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++];
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) |
(SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) |
(SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) |
(SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) |
(SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
t0 = t0 >>> 0;
t1 = t1 >>> 0;
t2 = t2 >>> 0;
t3 = t3 >>> 0;
return [t0, t1, t2, t3];
}
// AES constants
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
var G = (function () {
// Compute double table
var d = new Array(256);
for (var j = 0; j < 256; j++) {
if (j < 128) {
d[j] = j << 1;
} else {
d[j] = (j << 1) ^ 0x11b;
}
}
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX = [[], [], [], []];
var INV_SUB_MIX = [[], [], [], []];
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; ++i) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX[0][x] = (t << 24) | (t >>> 8);
SUB_MIX[1][x] = (t << 16) | (t >>> 16);
SUB_MIX[2][x] = (t << 8) | (t >>> 24);
SUB_MIX[3][x] = t;
// Compute inv sub bytes, inv mix columns tables
t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX[3][sx] = t;
if (x === 0) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
return {
SBOX: SBOX,
INV_SBOX: INV_SBOX,
SUB_MIX: SUB_MIX,
INV_SUB_MIX: INV_SUB_MIX,
};
})();
export function AES(key) {
this._key = asUInt32Array(key);
this._reset();
}
AES.blockSize = 4 * 4;
AES.keySize = 256 / 8;
AES.prototype.blockSize = AES.blockSize;
AES.prototype.keySize = AES.keySize;
AES.prototype._reset = function () {
var keyWords = this._key;
var keySize = keyWords.length;
var nRounds = keySize + 6;
var ksRows = (nRounds + 1) * 4;
var keySchedule = [];
for (var k = 0; k < keySize; k++) {
keySchedule[k] = keyWords[k];
}
for (k = keySize; k < ksRows; k++) {
var t = keySchedule[k - 1];
if (k % keySize === 0) {
t = (t << 8) | (t >>> 24);
t = (G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) |
(G.SBOX[t & 0xff]);
t ^= RCON[(k / keySize) | 0] << 24;
} else if (keySize > 6 && k % keySize === 4) {
t = (G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) |
(G.SBOX[t & 0xff]);
}
keySchedule[k] = keySchedule[k - keySize] ^ t;
}
var invKeySchedule = [];
for (var ik = 0; ik < ksRows; ik++) {
var ksR = ksRows - ik;
var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)];
if (ik < 4 || ksR <= 4) {
invKeySchedule[ik] = tt;
} else {
invKeySchedule[ik] = G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]];
}
}
this._nRounds = nRounds;
this._keySchedule = keySchedule;
this._invKeySchedule = invKeySchedule;
};
AES.prototype.encryptBlockRaw = function (M) {
M = asUInt32Array(M);
return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds);
};
AES.prototype.encryptBlock = function (M) {
var out = this.encryptBlockRaw(M);
var buf = Buffer.allocUnsafe(16);
buf.writeUInt32BE(out[0], 0);
buf.writeUInt32BE(out[1], 4);
buf.writeUInt32BE(out[2], 8);
buf.writeUInt32BE(out[3], 12);
return buf;
};
AES.prototype.decryptBlock = function (M) {
M = asUInt32Array(M);
// swap
var m1 = M[1];
M[1] = M[3];
M[3] = m1;
var out = cryptBlock(
M,
this._invKeySchedule,
G.INV_SUB_MIX,
G.INV_SBOX,
this._nRounds,
);
var buf = Buffer.allocUnsafe(16);
buf.writeUInt32BE(out[0], 0);
buf.writeUInt32BE(out[3], 4);
buf.writeUInt32BE(out[2], 8);
buf.writeUInt32BE(out[1], 12);
return buf;
};
AES.prototype.scrub = function () {
scrubVec(this._keySchedule);
scrubVec(this._invKeySchedule);
scrubVec(this._key);
};

View file

@ -1,146 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
// deno-lint-ignore-file no-var no-inner-declarations
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import * as aes from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/aes.js";
import Transform from "internal:deno_node/polyfills/_crypto/crypto_browserify/cipher_base.js";
import { GHASH } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/ghash.js";
import { xor } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/xor.ts";
import { incr32 } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/incr32.js";
function xorTest(a, b) {
var out = 0;
if (a.length !== b.length) out++;
var len = Math.min(a.length, b.length);
for (var i = 0; i < len; ++i) {
out += a[i] ^ b[i];
}
return out;
}
function calcIv(self, iv, ck) {
if (iv.length === 12) {
self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]);
return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]);
}
var ghash = new GHASH(ck);
var len = iv.length;
var toPad = len % 16;
ghash.update(iv);
if (toPad) {
toPad = 16 - toPad;
ghash.update(Buffer.alloc(toPad, 0));
}
ghash.update(Buffer.alloc(8, 0));
var ivBits = len * 8;
var tail = Buffer.alloc(8);
// Fixed from the original
// https://github.com/crypto-browserify/browserify-aes/issues/58#issuecomment-451778917
tail.writeUIntBE(ivBits, 2, 6);
ghash.update(tail);
self._finID = ghash.state;
var out = Buffer.from(self._finID);
incr32(out);
return out;
}
export function StreamCipher(mode, key, iv, decrypt) {
Transform.call(this);
var h = Buffer.alloc(4, 0);
this._cipher = new aes.AES(key);
var ck = this._cipher.encryptBlock(h);
this._ghash = new GHASH(ck);
iv = calcIv(this, iv, ck);
this._prev = Buffer.from(iv);
this._cache = Buffer.allocUnsafe(0);
this._secCache = Buffer.allocUnsafe(0);
this._decrypt = decrypt;
this._alen = 0;
this._len = 0;
this._mode = mode;
this._authTag = null;
this._called = false;
}
// StreamCipher inherts Transform
StreamCipher.prototype = Object.create(Transform.prototype, {
constructor: {
value: StreamCipher,
enumerable: false,
writable: true,
configurable: true,
},
});
StreamCipher.prototype._update = function (chunk) {
if (!this._called && this._alen) {
var rump = 16 - (this._alen % 16);
if (rump < 16) {
rump = Buffer.alloc(rump, 0);
this._ghash.update(rump);
}
}
this._called = true;
var out = this._mode.encrypt(this, chunk);
if (this._decrypt) {
this._ghash.update(chunk);
} else {
this._ghash.update(out);
}
this._len += chunk.length;
return out;
};
StreamCipher.prototype._final = function () {
if (this._decrypt && !this._authTag) {
throw new Error("Unsupported state or unable to authenticate data");
}
var tag = xor(
this._ghash.final(this._alen * 8, this._len * 8),
this._cipher.encryptBlock(this._finID),
);
if (this._decrypt && xorTest(tag, this._authTag)) {
throw new Error("Unsupported state or unable to authenticate data");
}
this._authTag = tag;
this._cipher.scrub();
};
StreamCipher.prototype.getAuthTag = function getAuthTag() {
if (this._decrypt || !Buffer.isBuffer(this._authTag)) {
throw new Error("Attempting to get auth tag in unsupported state");
}
return this._authTag;
};
StreamCipher.prototype.setAuthTag = function setAuthTag(tag) {
if (!this._decrypt) {
throw new Error("Attempting to set auth tag in unsupported state");
}
this._authTag = tag;
};
StreamCipher.prototype.setAAD = function setAAD(buf) {
if (this._called) {
throw new Error("Attempting to set AAD in unsupported state");
}
this._ghash.update(buf);
this._alen += buf.length;
};
export default StreamCipher;

View file

@ -1,138 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
// deno-lint-ignore-file no-var
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import AuthCipher from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/auth_cipher.js";
import StreamCipher from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/stream_cipher.js";
import Transform from "internal:deno_node/polyfills/_crypto/crypto_browserify/cipher_base.js";
import * as aes from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/aes.js";
import ebtk from "internal:deno_node/polyfills/_crypto/crypto_browserify/evp_bytes_to_key.ts";
import { MODES } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/mod.js";
function Decipher(mode, key, iv) {
Transform.call(this);
this._cache = new Splitter();
this._last = void 0;
this._cipher = new aes.AES(key);
this._prev = Buffer.from(iv);
this._mode = mode;
this._autopadding = true;
}
Decipher.prototype = Object.create(Transform.prototype, {
constructor: {
value: Decipher,
enumerable: false,
writable: true,
configurable: true,
},
});
Decipher.prototype._update = function (data) {
this._cache.add(data);
var chunk;
var thing;
var out = [];
while ((chunk = this._cache.get(this._autopadding))) {
thing = this._mode.decrypt(this, chunk);
out.push(thing);
}
return Buffer.concat(out);
};
Decipher.prototype._final = function () {
var chunk = this._cache.flush();
if (this._autopadding) {
return unpad(this._mode.decrypt(this, chunk));
} else if (chunk) {
throw new Error("data not multiple of block length");
}
};
Decipher.prototype.setAutoPadding = function (setTo) {
this._autopadding = !!setTo;
return this;
};
function Splitter() {
this.cache = Buffer.allocUnsafe(0);
}
Splitter.prototype.add = function (data) {
this.cache = Buffer.concat([this.cache, data]);
};
Splitter.prototype.get = function (autoPadding) {
var out;
if (autoPadding) {
if (this.cache.length > 16) {
out = this.cache.slice(0, 16);
this.cache = this.cache.slice(16);
return out;
}
} else {
if (this.cache.length >= 16) {
out = this.cache.slice(0, 16);
this.cache = this.cache.slice(16);
return out;
}
}
return null;
};
Splitter.prototype.flush = function () {
if (this.cache.length) return this.cache;
};
function unpad(last) {
var padded = last[15];
if (padded < 1 || padded > 16) {
throw new Error("unable to decrypt data");
}
var i = -1;
while (++i < padded) {
if (last[i + (16 - padded)] !== padded) {
throw new Error("unable to decrypt data");
}
}
if (padded === 16) return;
return last.slice(0, 16 - padded);
}
export function createDecipheriv(suite, password, iv) {
var config = MODES[suite.toLowerCase()];
if (!config) throw new TypeError("invalid suite type");
if (typeof iv === "string") iv = Buffer.from(iv);
if (config.mode !== "GCM" && iv.length !== config.iv) {
throw new TypeError("invalid iv length " + iv.length);
}
if (typeof password === "string") password = Buffer.from(password);
if (password.length !== config.key / 8) {
throw new TypeError("invalid key length " + password.length);
}
if (config.type === "stream") {
return new StreamCipher(config.module, password, iv, true);
} else if (config.type === "auth") {
return new AuthCipher(config.module, password, iv, true);
}
return new Decipher(config.module, password, iv);
}
export function createDecipher(suite, password) {
var config = MODES[suite.toLowerCase()];
if (!config) throw new TypeError("invalid suite type");
var keys = ebtk(password, false, config.key, config.iv);
return createDecipheriv(suite, keys.key, keys.iv);
}

View file

@ -1,128 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
// deno-lint-ignore-file no-var
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import AuthCipher from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/auth_cipher.js";
import StreamCipher from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/stream_cipher.js";
import Transform from "internal:deno_node/polyfills/_crypto/crypto_browserify/cipher_base.js";
import * as aes from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/aes.js";
import ebtk from "internal:deno_node/polyfills/_crypto/crypto_browserify/evp_bytes_to_key.ts";
import { MODES } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/mod.js";
function Cipher(mode, key, iv) {
Transform.call(this);
this._cache = new Splitter();
this._cipher = new aes.AES(key);
this._prev = Buffer.from(iv);
this._mode = mode;
this._autopadding = true;
}
Cipher.prototype = Object.create(Transform.prototype, {
constructor: {
value: Cipher,
enumerable: false,
writable: true,
configurable: true,
},
});
Cipher.prototype._update = function (data) {
this._cache.add(data);
var chunk;
var thing;
var out = [];
while ((chunk = this._cache.get())) {
thing = this._mode.encrypt(this, chunk);
out.push(thing);
}
return Buffer.concat(out);
};
var PADDING = Buffer.alloc(16, 0x10);
Cipher.prototype._final = function () {
var chunk = this._cache.flush();
if (this._autopadding) {
chunk = this._mode.encrypt(this, chunk);
this._cipher.scrub();
return chunk;
}
if (!chunk.equals(PADDING)) {
this._cipher.scrub();
throw new Error("data not multiple of block length");
}
};
Cipher.prototype.setAutoPadding = function (setTo) {
this._autopadding = !!setTo;
return this;
};
function Splitter() {
this.cache = Buffer.allocUnsafe(0);
}
Splitter.prototype.add = function (data) {
this.cache = Buffer.concat([this.cache, data]);
};
Splitter.prototype.get = function () {
if (this.cache.length > 15) {
const out = this.cache.slice(0, 16);
this.cache = this.cache.slice(16);
return out;
}
return null;
};
Splitter.prototype.flush = function () {
var len = 16 - this.cache.length;
var padBuff = Buffer.allocUnsafe(len);
var i = -1;
while (++i < len) {
padBuff.writeUInt8(len, i);
}
return Buffer.concat([this.cache, padBuff]);
};
export function createCipheriv(suite, password, iv) {
var config = MODES[suite.toLowerCase()];
if (!config) throw new TypeError("invalid suite type");
if (typeof password === "string") password = Buffer.from(password);
if (password.length !== config.key / 8) {
throw new TypeError("invalid key length " + password.length);
}
if (typeof iv === "string") iv = Buffer.from(iv);
if (config.mode !== "GCM" && iv.length !== config.iv) {
throw new TypeError("invalid iv length " + iv.length);
}
if (config.type === "stream") {
return new StreamCipher(config.module, password, iv);
} else if (config.type === "auth") {
return new AuthCipher(config.module, password, iv);
}
return new Cipher(config.module, password, iv);
}
export function createCipher(suite, password) {
var config = MODES[suite.toLowerCase()];
if (!config) throw new TypeError("invalid suite type");
var keys = ebtk(password, false, config.key, config.iv);
return createCipheriv(suite, keys.key, keys.iv);
}

View file

@ -1,96 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
// Copyright 2009-2015, Emily Stark, Mike Hamburg and Dan Boneh at Stanford University. All rights reserved.
// deno-lint-ignore-file no-var
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
var ZEROES = Buffer.alloc(16, 0);
function toArray(buf) {
return [
buf.readUInt32BE(0),
buf.readUInt32BE(4),
buf.readUInt32BE(8),
buf.readUInt32BE(12),
];
}
function fromArray(out) {
var buf = Buffer.allocUnsafe(16);
buf.writeUInt32BE(out[0] >>> 0, 0);
buf.writeUInt32BE(out[1] >>> 0, 4);
buf.writeUInt32BE(out[2] >>> 0, 8);
buf.writeUInt32BE(out[3] >>> 0, 12);
return buf;
}
export function GHASH(key) {
this.h = key;
this.state = Buffer.alloc(16, 0);
this.cache = Buffer.allocUnsafe(0);
}
// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
// by Juho Vähä-Herttua
GHASH.prototype.ghash = function (block) {
var i = -1;
while (++i < block.length) {
this.state[i] ^= block[i];
}
this._multiply();
};
GHASH.prototype._multiply = function () {
var Vi = toArray(this.h);
var Zi = [0, 0, 0, 0];
var j, xi, lsbVi;
var i = -1;
while (++i < 128) {
xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0;
if (xi) {
// Z_i+1 = Z_i ^ V_i
Zi[0] ^= Vi[0];
Zi[1] ^= Vi[1];
Zi[2] ^= Vi[2];
Zi[3] ^= Vi[3];
}
// Store the value of LSB(V_i)
lsbVi = (Vi[3] & 1) !== 0;
// V_i+1 = V_i >> 1
for (j = 3; j > 0; j--) {
Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31);
}
Vi[0] = Vi[0] >>> 1;
// If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
if (lsbVi) {
Vi[0] = Vi[0] ^ (0xe1 << 24);
}
}
this.state = fromArray(Zi);
};
GHASH.prototype.update = function (buf) {
this.cache = Buffer.concat([this.cache, buf]);
var chunk;
while (this.cache.length >= 16) {
chunk = this.cache.slice(0, 16);
this.cache = this.cache.slice(16);
this.ghash(chunk);
}
};
GHASH.prototype.final = function (abl, bl) {
if (this.cache.length) {
this.ghash(Buffer.concat([this.cache, ZEROES], 16));
}
this.ghash(fromArray([0, abl, 0, bl]));
return this.state;
};

View file

@ -1,19 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
export function incr32(iv) {
let len = iv.length;
let item;
while (len--) {
item = iv.readUInt8(len);
if (item === 255) {
iv.writeUInt8(0, len);
} else {
item++;
iv.writeUInt8(item, len);
break;
}
}
}

View file

@ -1,13 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import { MODES } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/mod.js";
export * from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/encrypter.js";
export * from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/decrypter.js";
export function getCiphers() {
return Object.keys(MODES);
}

View file

@ -1,22 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import { xor } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/xor.ts";
export const encrypt = function (self, block) {
const data = xor(block, self._prev);
self._prev = self._cipher.encryptBlock(data);
return self._prev;
};
export const decrypt = function (self, block) {
const pad = self._prev;
self._prev = block;
const out = self._cipher.decryptBlock(block);
return xor(out, pad);
};

View file

@ -1,41 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import { xor } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/xor.ts";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
function encryptStart(self, data, decrypt) {
const len = data.length;
const out = xor(data, self._cache);
self._cache = self._cache.slice(len);
self._prev = Buffer.concat([self._prev, decrypt ? data : out]);
return out;
}
export const encrypt = function (self, data, decrypt) {
let out = Buffer.allocUnsafe(0);
let len;
while (data.length) {
if (self._cache.length === 0) {
self._cache = self._cipher.encryptBlock(self._prev);
self._prev = Buffer.allocUnsafe(0);
}
if (self._cache.length <= data.length) {
len = self._cache.length;
out = Buffer.concat([
out,
encryptStart(self, data.slice(0, len), decrypt),
]);
data = data.slice(len);
} else {
out = Buffer.concat([out, encryptStart(self, data, decrypt)]);
break;
}
}
return out;
};

View file

@ -1,47 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
function encryptByte(self, byteParam, decrypt) {
let pad;
let i = -1;
const len = 8;
let out = 0;
let bit, value;
while (++i < len) {
pad = self._cipher.encryptBlock(self._prev);
bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0;
value = pad[0] ^ bit;
out += (value & 0x80) >> (i % 8);
self._prev = shiftIn(self._prev, decrypt ? bit : value);
}
return out;
}
function shiftIn(buffer, value) {
const len = buffer.length;
let i = -1;
const out = Buffer.allocUnsafe(buffer.length);
buffer = Buffer.concat([buffer, Buffer.from([value])]);
while (++i < len) {
out[i] = buffer[i] << 1 | buffer[i + 1] >> (7);
}
return out;
}
export const encrypt = function (self, chunk, decrypt) {
const len = chunk.length;
const out = Buffer.allocUnsafe(len);
let i = -1;
while (++i < len) {
out[i] = encryptByte(self, chunk[i], decrypt);
}
return out;
};

View file

@ -1,30 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
function encryptByte(self, byteParam, decrypt) {
const pad = self._cipher.encryptBlock(self._prev);
const out = pad[0] ^ byteParam;
self._prev = Buffer.concat([
self._prev.slice(1),
Buffer.from([decrypt ? byteParam : out]),
]);
return out;
}
export const encrypt = function (self, chunk, decrypt) {
const len = chunk.length;
const out = Buffer.allocUnsafe(len);
let i = -1;
while (++i < len) {
out[i] = encryptByte(self, chunk[i], decrypt);
}
return out;
};

View file

@ -1,35 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import { xor } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/xor.ts";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import { incr32 } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/incr32.js";
function getBlock(self) {
const out = self._cipher.encryptBlockRaw(self._prev);
incr32(self._prev);
return out;
}
const blockSize = 16;
export const encrypt = function (self, chunk) {
const chunkNum = Math.ceil(chunk.length / blockSize);
const start = self._cache.length;
self._cache = Buffer.concat([
self._cache,
Buffer.allocUnsafe(chunkNum * blockSize),
]);
for (let i = 0; i < chunkNum; i++) {
const out = getBlock(self);
const offset = start + i * blockSize;
self._cache.writeUInt32BE(out[0], offset + 0);
self._cache.writeUInt32BE(out[1], offset + 4);
self._cache.writeUInt32BE(out[2], offset + 8);
self._cache.writeUInt32BE(out[3], offset + 12);
}
const pad = self._cache.slice(0, chunk.length);
self._cache = self._cache.slice(chunk.length);
return xor(chunk, pad);
};

View file

@ -1,12 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
export const encrypt = function (self, block) {
return self._cipher.encryptBlock(block);
};
export const decrypt = function (self, block) {
return self._cipher.decryptBlock(block);
};

View file

@ -1,221 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import * as ECB from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/ecb.js";
import * as CBC from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/cbc.js";
import * as CFB from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/cfb.js";
import * as CFB8 from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/cfb8.js";
import * as CFB1 from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/cfb1.js";
import * as OFB from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/ofb.js";
import * as CTR from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/modes/ctr.js";
const GCM = CTR;
const modeModules = {
ECB,
CBC,
CFB,
CFB8,
CFB1,
OFB,
CTR,
GCM,
};
export const MODES = {
"aes-128-ecb": {
"cipher": "AES",
"key": 128,
"iv": 0,
"mode": "ECB",
"type": "block",
},
"aes-192-ecb": {
"cipher": "AES",
"key": 192,
"iv": 0,
"mode": "ECB",
"type": "block",
},
"aes-256-ecb": {
"cipher": "AES",
"key": 256,
"iv": 0,
"mode": "ECB",
"type": "block",
},
"aes-128-cbc": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CBC",
"type": "block",
},
"aes-192-cbc": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CBC",
"type": "block",
},
"aes-256-cbc": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CBC",
"type": "block",
},
"aes128": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CBC",
"type": "block",
},
"aes192": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CBC",
"type": "block",
},
"aes256": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CBC",
"type": "block",
},
"aes-128-cfb": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CFB",
"type": "stream",
},
"aes-192-cfb": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CFB",
"type": "stream",
},
"aes-256-cfb": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CFB",
"type": "stream",
},
"aes-128-cfb8": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CFB8",
"type": "stream",
},
"aes-192-cfb8": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CFB8",
"type": "stream",
},
"aes-256-cfb8": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CFB8",
"type": "stream",
},
"aes-128-cfb1": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CFB1",
"type": "stream",
},
"aes-192-cfb1": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CFB1",
"type": "stream",
},
"aes-256-cfb1": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CFB1",
"type": "stream",
},
"aes-128-ofb": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "OFB",
"type": "stream",
},
"aes-192-ofb": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "OFB",
"type": "stream",
},
"aes-256-ofb": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "OFB",
"type": "stream",
},
"aes-128-ctr": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CTR",
"type": "stream",
},
"aes-192-ctr": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CTR",
"type": "stream",
},
"aes-256-ctr": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CTR",
"type": "stream",
},
"aes-128-gcm": {
"cipher": "AES",
"key": 128,
"iv": 12,
"mode": "GCM",
"type": "auth",
},
"aes-192-gcm": {
"cipher": "AES",
"key": 192,
"iv": 12,
"mode": "GCM",
"type": "auth",
},
"aes-256-gcm": {
"cipher": "AES",
"key": 256,
"iv": 12,
"mode": "GCM",
"type": "auth",
},
};
for (const mode of Object.values(MODES)) {
mode.module = modeModules[mode.mode];
}

View file

@ -1,22 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import { xor } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/xor.ts";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
function getBlock(self) {
self._prev = self._cipher.encryptBlock(self._prev);
return self._prev;
}
export const encrypt = function (self, chunk) {
while (self._cache.length < chunk.length) {
self._cache = Buffer.concat([self._cache, getBlock(self)]);
}
const pad = self._cache.slice(0, chunk.length);
self._cache = self._cache.slice(chunk.length);
return xor(chunk, pad);
};

View file

@ -1,40 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import * as aes from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/aes.js";
import Transform from "internal:deno_node/polyfills/_crypto/crypto_browserify/cipher_base.js";
export function StreamCipher(mode, key, iv, decrypt) {
Transform.call(this);
this._cipher = new aes.AES(key);
this._prev = Buffer.from(iv);
this._cache = Buffer.allocUnsafe(0);
this._secCache = Buffer.allocUnsafe(0);
this._decrypt = decrypt;
this._mode = mode;
}
// StreamCipher inherits Transform
StreamCipher.prototype = Object.create(Transform.prototype, {
constructor: {
value: StreamCipher,
enumerable: false,
writable: true,
configurable: true,
},
});
StreamCipher.prototype._update = function (chunk) {
return this._mode.encrypt(this, chunk, this._decrypt);
};
StreamCipher.prototype._final = function () {
this._cipher.scrub();
};
export default StreamCipher;

View file

@ -1,17 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2014-2017 browserify-aes contributors. All rights reserved. MIT license.
// Copyright 2013 Maxwell Krohn. All rights reserved. MIT license.
// Copyright 2009-2013 Jeff Mott. All rights reserved. MIT license.
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
export function xor(a: Buffer, b: Buffer): Buffer {
const length = Math.min(a.length, b.length);
const buffer = Buffer.allocUnsafe(length);
for (let i = 0; i < length; ++i) {
buffer[i] = a[i] ^ b[i];
}
return buffer;
}

View file

@ -1,47 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 crypto-browserify. All rights reserved. MIT license.
import { BN } from "internal:deno_node/polyfills/_crypto/crypto_browserify/bn.js/bn.js";
import { randomBytes } from "internal:deno_node/polyfills/_crypto/crypto_browserify/randombytes.ts";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
function blind(priv) {
const r = getr(priv);
const blinder = r.toRed(BN.mont(priv.modulus)).redPow(
new BN(priv.publicExponent),
).fromRed();
return { blinder: blinder, unblinder: r.invm(priv.modulus) };
}
function getr(priv) {
const len = priv.modulus.byteLength();
let r;
do {
r = new BN(randomBytes(len));
} while (
r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)
);
return r;
}
function crt(msg, priv) {
const blinds = blind(priv);
const len = priv.modulus.byteLength();
const blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus);
const c1 = blinded.toRed(BN.mont(priv.prime1));
const c2 = blinded.toRed(BN.mont(priv.prime2));
const qinv = priv.coefficient;
const p = priv.prime1;
const q = priv.prime2;
const m1 = c1.redPow(priv.exponent1).fromRed();
const m2 = c2.redPow(priv.exponent2).fromRed();
const h = m1.isub(m2).imul(qinv).umod(p).imul(q);
return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(
Buffer,
"be",
len,
);
}
crt.getr = getr;
export default crt;

View file

@ -1,110 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 crypto-browserify. All rights reserved. MIT license.
// deno-lint-ignore-file no-var
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import { Transform } from "internal:deno_node/polyfills/stream.ts";
import { StringDecoder } from "internal:deno_node/polyfills/string_decoder.ts";
export function CipherBase(hashMode) {
Transform.call(this);
this.hashMode = typeof hashMode === "string";
if (this.hashMode) {
this[hashMode] = this._finalOrDigest;
} else {
this.final = this._finalOrDigest;
}
if (this._final) {
this.__final = this._final;
this._final = null;
}
this._decoder = null;
this._encoding = null;
}
// inherits(CipherBase, Transform)
CipherBase.prototype = Object.create(Transform.prototype, {
constructor: {
value: CipherBase,
enumerable: false,
writable: true,
configurable: true,
},
});
CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
if (typeof data === "string") {
data = Buffer.from(data, inputEnc);
}
var outData = this._update(data);
if (this.hashMode) return this;
if (outputEnc) {
outData = this._toString(outData, outputEnc);
}
return outData;
};
CipherBase.prototype.setAutoPadding = function () {};
CipherBase.prototype.getAuthTag = function () {
throw new Error("trying to get auth tag in unsupported state");
};
CipherBase.prototype.setAuthTag = function () {
throw new Error("trying to set auth tag in unsupported state");
};
CipherBase.prototype.setAAD = function () {
throw new Error("trying to set aad in unsupported state");
};
CipherBase.prototype._transform = function (data, _, next) {
var err;
try {
if (this.hashMode) {
this._update(data);
} else {
this.push(this._update(data));
}
} catch (e) {
err = e;
} finally {
next(err);
}
};
CipherBase.prototype._flush = function (done) {
var err;
try {
this.push(this.__final());
} catch (e) {
err = e;
}
done(err);
};
CipherBase.prototype._finalOrDigest = function (outputEnc) {
var outData = this.__final() || Buffer.alloc(0);
if (outputEnc) {
outData = this._toString(outData, outputEnc, true);
}
return outData;
};
CipherBase.prototype._toString = function (value, enc, fin) {
if (!this._decoder) {
this._decoder = new StringDecoder(enc);
this._encoding = enc;
}
if (this._encoding !== enc) throw new Error("can't switch encodings");
var out = this._decoder.write(value);
if (fin) {
out += this._decoder.end();
}
return out;
};
export default CipherBase;

View file

@ -1,55 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 crypto-browserify. All rights reserved. MIT license.
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import { createHash } from "internal:deno_node/polyfills/internal/crypto/hash.ts";
// deno-lint-ignore camelcase
export function EVP_BytesToKey(
password: string | Buffer,
salt: string | Buffer,
keyBits: number,
ivLen: number,
) {
if (!Buffer.isBuffer(password)) password = Buffer.from(password, "binary");
if (salt) {
if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, "binary");
if (salt.length !== 8) {
throw new RangeError("salt should be Buffer with 8 byte length");
}
}
let keyLen = keyBits / 8;
const key = Buffer.alloc(keyLen);
const iv = Buffer.alloc(ivLen || 0);
let tmp = Buffer.alloc(0);
while (keyLen > 0 || ivLen > 0) {
const hash = createHash("md5");
hash.update(tmp);
hash.update(password);
if (salt) hash.update(salt);
tmp = hash.digest() as Buffer;
let used = 0;
if (keyLen > 0) {
const keyStart = key.length - keyLen;
used = Math.min(keyLen, tmp.length);
tmp.copy(key, keyStart, 0, used);
keyLen -= used;
}
if (used < tmp.length && ivLen > 0) {
const ivStart = iv.length - ivLen;
const length = Math.min(ivLen, tmp.length - used);
tmp.copy(iv, ivStart, used, used + length);
ivLen -= length;
}
}
tmp.fill(0);
return { key, iv };
}
export default EVP_BytesToKey;

View file

@ -1,4 +0,0 @@
{
"//": "Sets type module to make compat mode interpret .js as ESM",
"type": "module"
}

View file

@ -1,117 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 crypto-browserify. All rights reserved. MIT license.
// from https://github.com/crypto-browserify/parse-asn1/blob/fbd70dca8670d17955893e083ca69118908570be/asn1.js
import asn1 from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/mod.js";
import certificate from "internal:deno_node/polyfills/_crypto/crypto_browserify/parse_asn1/certificate.js";
export { certificate };
export const RSAPrivateKey = asn1.define("RSAPrivateKey", function () {
this.seq().obj(
this.key("version").int(),
this.key("modulus").int(),
this.key("publicExponent").int(),
this.key("privateExponent").int(),
this.key("prime1").int(),
this.key("prime2").int(),
this.key("exponent1").int(),
this.key("exponent2").int(),
this.key("coefficient").int(),
);
});
export const RSAPublicKey = asn1.define("RSAPublicKey", function () {
this.seq().obj(
this.key("modulus").int(),
this.key("publicExponent").int(),
);
});
export const PublicKey = asn1.define("SubjectPublicKeyInfo", function () {
this.seq().obj(
this.key("algorithm").use(AlgorithmIdentifier),
this.key("subjectPublicKey").bitstr(),
);
});
const AlgorithmIdentifier = asn1.define("AlgorithmIdentifier", function () {
this.seq().obj(
this.key("algorithm").objid(),
this.key("none").null_().optional(),
this.key("curve").objid().optional(),
this.key("params").seq().obj(
this.key("p").int(),
this.key("q").int(),
this.key("g").int(),
).optional(),
);
});
export const PrivateKey = asn1.define("PrivateKeyInfo", function () {
this.seq().obj(
this.key("version").int(),
this.key("algorithm").use(AlgorithmIdentifier),
this.key("subjectPrivateKey").octstr(),
);
});
export const EncryptedPrivateKey = asn1.define(
"EncryptedPrivateKeyInfo",
function () {
this.seq().obj(
this.key("algorithm").seq().obj(
this.key("id").objid(),
this.key("decrypt").seq().obj(
this.key("kde").seq().obj(
this.key("id").objid(),
this.key("kdeparams").seq().obj(
this.key("salt").octstr(),
this.key("iters").int(),
),
),
this.key("cipher").seq().obj(
this.key("algo").objid(),
this.key("iv").octstr(),
),
),
),
this.key("subjectPrivateKey").octstr(),
);
},
);
export const DSAPrivateKey = asn1.define("DSAPrivateKey", function () {
this.seq().obj(
this.key("version").int(),
this.key("p").int(),
this.key("q").int(),
this.key("g").int(),
this.key("pub_key").int(),
this.key("priv_key").int(),
);
});
export const DSAparam = asn1.define("DSAparam", function () {
this.int();
});
export const ECPrivateKey = asn1.define("ECPrivateKey", function () {
this.seq().obj(
this.key("version").int(),
this.key("privateKey").octstr(),
this.key("parameters").optional().explicit(0).use(ECParameters),
this.key("publicKey").optional().explicit(1).bitstr(),
);
});
const ECParameters = asn1.define("ECParameters", function () {
this.choice({
namedCurve: this.objid(),
});
});
export const signature = asn1.define("signature", function () {
this.seq().obj(
this.key("r").int(),
this.key("s").int(),
);
});

View file

@ -1,91 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 crypto-browserify. All rights reserved. MIT license.
// from https://github.com/crypto-browserify/parse-asn1/blob/fbd70dca8670d17955893e083ca69118908570be/certificate.js
import * as asn from "internal:deno_node/polyfills/_crypto/crypto_browserify/asn1.js/mod.js";
const Time = asn.define("Time", function () {
this.choice({
utcTime: this.utctime(),
generalTime: this.gentime(),
});
});
const AttributeTypeValue = asn.define("AttributeTypeValue", function () {
this.seq().obj(
this.key("type").objid(),
this.key("value").any(),
);
});
const AlgorithmIdentifier = asn.define("AlgorithmIdentifier", function () {
this.seq().obj(
this.key("algorithm").objid(),
this.key("parameters").optional(),
this.key("curve").objid().optional(),
);
});
const SubjectPublicKeyInfo = asn.define("SubjectPublicKeyInfo", function () {
this.seq().obj(
this.key("algorithm").use(AlgorithmIdentifier),
this.key("subjectPublicKey").bitstr(),
);
});
const RelativeDistinguishedName = asn.define(
"RelativeDistinguishedName",
function () {
this.setof(AttributeTypeValue);
},
);
const RDNSequence = asn.define("RDNSequence", function () {
this.seqof(RelativeDistinguishedName);
});
const Name = asn.define("Name", function () {
this.choice({
rdnSequence: this.use(RDNSequence),
});
});
const Validity = asn.define("Validity", function () {
this.seq().obj(
this.key("notBefore").use(Time),
this.key("notAfter").use(Time),
);
});
const Extension = asn.define("Extension", function () {
this.seq().obj(
this.key("extnID").objid(),
this.key("critical").bool().def(false),
this.key("extnValue").octstr(),
);
});
const TBSCertificate = asn.define("TBSCertificate", function () {
this.seq().obj(
this.key("version").explicit(0).int().optional(),
this.key("serialNumber").int(),
this.key("signature").use(AlgorithmIdentifier),
this.key("issuer").use(Name),
this.key("validity").use(Validity),
this.key("subject").use(Name),
this.key("subjectPublicKeyInfo").use(SubjectPublicKeyInfo),
this.key("issuerUniqueID").implicit(1).bitstr().optional(),
this.key("subjectUniqueID").implicit(2).bitstr().optional(),
this.key("extensions").explicit(3).seqof(Extension).optional(),
);
});
export const X509Certificate = asn.define("X509Certificate", function () {
this.seq().obj(
this.key("tbsCertificate").use(TBSCertificate),
this.key("signatureAlgorithm").use(AlgorithmIdentifier),
this.key("signatureValue").bitstr(),
);
});
export default X509Certificate;

View file

@ -1,37 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 crypto-browserify. All rights reserved. MIT license.
// from https://github.com/crypto-browserify/parse-asn1/blob/fbd70dca8670d17955893e083ca69118908570be/fixProc.js
import evp from "internal:deno_node/polyfills/_crypto/crypto_browserify/evp_bytes_to_key.ts";
import * as ciphers from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/mod.js";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
const findProc =
/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m;
const startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m;
const fullRegex =
/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m;
export default function (okey, password) {
const key = okey.toString();
const match = key.match(findProc);
let decrypted;
if (!match) {
const match2 = key.match(fullRegex);
decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ""), "base64");
} else {
const suite = "aes" + match[1];
const iv = Buffer.from(match[2], "hex");
const cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ""), "base64");
const cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key;
const out = [];
const cipher = ciphers.createDecipheriv(suite, cipherKey, iv);
out.push(cipher.update(cipherText));
out.push(cipher.final());
decrypted = Buffer.concat(out);
}
const tag = key.match(startRegex)[1];
return {
tag: tag,
data: decrypted,
};
}

View file

@ -1,138 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 crypto-browserify. All rights reserved. MIT license.
// from https://github.com/crypto-browserify/parse-asn1/blob/fbd70dca8670d17955893e083ca69118908570be/index.js
import * as asn1 from "internal:deno_node/polyfills/_crypto/crypto_browserify/parse_asn1/asn1.js";
import fixProc from "internal:deno_node/polyfills/_crypto/crypto_browserify/parse_asn1/fix_proc.js";
import * as ciphers from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/mod.js";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import { pbkdf2Sync } from "internal:deno_node/polyfills/internal/crypto/pbkdf2.ts";
const aesid = {
"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
"2.16.840.1.101.3.4.1.44": "aes-256-cfb",
};
export function parseKeys(buffer) {
let password;
if (typeof buffer === "object" && !Buffer.isBuffer(buffer)) {
password = buffer.passphrase;
buffer = buffer.key;
}
if (typeof buffer === "string") {
buffer = Buffer.from(buffer);
}
const stripped = fixProc(buffer, password);
const type = stripped.tag;
let data = stripped.data;
let subtype, ndata;
switch (type) {
case "CERTIFICATE":
ndata = asn1.certificate.decode(data, "der").tbsCertificate
.subjectPublicKeyInfo;
// falls through
case "PUBLIC KEY":
if (!ndata) {
ndata = asn1.PublicKey.decode(data, "der");
}
subtype = ndata.algorithm.algorithm.join(".");
switch (subtype) {
case "1.2.840.113549.1.1.1":
return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, "der");
case "1.2.840.10045.2.1":
ndata.subjectPrivateKey = ndata.subjectPublicKey;
return {
type: "ec",
data: ndata,
};
case "1.2.840.10040.4.1":
ndata.algorithm.params.pub_key = asn1.DSAparam.decode(
ndata.subjectPublicKey.data,
"der",
);
return {
type: "dsa",
data: ndata.algorithm.params,
};
default:
throw new Error("unknown key id " + subtype);
}
// throw new Error('unknown key type ' + type)
case "ENCRYPTED PRIVATE KEY":
data = asn1.EncryptedPrivateKey.decode(data, "der");
data = decrypt(data, password);
// falls through
case "PRIVATE KEY":
ndata = asn1.PrivateKey.decode(data, "der");
subtype = ndata.algorithm.algorithm.join(".");
switch (subtype) {
case "1.2.840.113549.1.1.1":
return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, "der");
case "1.2.840.10045.2.1":
return {
curve: ndata.algorithm.curve,
privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, "der")
.privateKey,
};
case "1.2.840.10040.4.1":
ndata.algorithm.params.priv_key = asn1.DSAparam.decode(
ndata.subjectPrivateKey,
"der",
);
return {
type: "dsa",
params: ndata.algorithm.params,
};
default:
throw new Error("unknown key id " + subtype);
}
// throw new Error('unknown key type ' + type)
case "RSA PUBLIC KEY":
return asn1.RSAPublicKey.decode(data, "der");
case "RSA PRIVATE KEY":
return asn1.RSAPrivateKey.decode(data, "der");
case "DSA PRIVATE KEY":
return {
type: "dsa",
params: asn1.DSAPrivateKey.decode(data, "der"),
};
case "EC PRIVATE KEY":
data = asn1.ECPrivateKey.decode(data, "der");
return {
curve: data.parameters.value,
privateKey: data.privateKey,
};
default:
throw new Error("unknown key type " + type);
}
}
export default parseKeys;
parseKeys.signature = asn1.signature;
function decrypt(data, password) {
const salt = data.algorithm.decrypt.kde.kdeparams.salt;
const iters = parseInt(
data.algorithm.decrypt.kde.kdeparams.iters.toString(),
10,
);
const algo = aesid[data.algorithm.decrypt.cipher.algo.join(".")];
const iv = data.algorithm.decrypt.cipher.iv;
const cipherText = data.subjectPrivateKey;
const keylen = parseInt(algo.split("-")[1], 10) / 8;
const key = pbkdf2Sync(password, salt, iters, keylen, "sha1");
const cipher = ciphers.createDecipheriv(algo, key, iv);
const out = [];
out.push(cipher.update(cipherText));
out.push(cipher.final());
return Buffer.concat(out);
}

View file

@ -1,22 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Calvin Metcalf. All rights reserved. MIT license.
import { createHash } from "internal:deno_node/polyfills/internal/crypto/hash.ts";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
export default function (seed, len) {
let t = Buffer.alloc(0);
let i = 0;
let c;
while (t.length < len) {
c = i2ops(i++);
t = Buffer.concat([t, createHash("sha1").update(seed).update(c).digest()]);
}
return t.slice(0, len);
}
function i2ops(c) {
const out = Buffer.allocUnsafe(4);
out.writeUInt32BE(c, 0);
return out;
}

View file

@ -1,15 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Calvin Metcalf. All rights reserved. MIT license.
import { publicEncrypt } from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/public_encrypt.js";
import { privateDecrypt } from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/private_decrypt.js";
export { privateDecrypt, publicEncrypt };
export function privateEncrypt(key, buf) {
return publicEncrypt(key, buf, true);
}
export function publicDecrypt(key, buf) {
return privateDecrypt(key, buf, true);
}

View file

@ -1,111 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Calvin Metcalf. All rights reserved. MIT license.
import parseKeys from "internal:deno_node/polyfills/_crypto/crypto_browserify/parse_asn1/mod.js";
import { createHash } from "internal:deno_node/polyfills/internal/crypto/hash.ts";
import mgf from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/mgf.js";
import { xor } from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/xor.js";
import { BN } from "internal:deno_node/polyfills/_crypto/crypto_browserify/bn.js/bn.js";
import { withPublic } from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/with_public.js";
import crt from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_rsa.js";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
export function privateDecrypt(privateKey, enc, reverse) {
let padding;
if (privateKey.padding) {
padding = privateKey.padding;
} else if (reverse) {
padding = 1;
} else {
padding = 4;
}
const key = parseKeys(privateKey);
const k = key.modulus.byteLength();
if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
throw new Error("decryption error");
}
let msg;
if (reverse) {
msg = withPublic(new BN(enc), key);
} else {
msg = crt(enc, key);
}
const zBuffer = Buffer.alloc(k - msg.length);
msg = Buffer.concat([zBuffer, msg], k);
if (padding === 4) {
return oaep(key, msg);
} else if (padding === 1) {
return pkcs1(key, msg, reverse);
} else if (padding === 3) {
return msg;
} else {
throw new Error("unknown padding");
}
}
function oaep(key, msg) {
const k = key.modulus.byteLength();
const iHash = createHash("sha1").update(Buffer.alloc(0)).digest();
const hLen = iHash.length;
if (msg[0] !== 0) {
throw new Error("decryption error");
}
const maskedSeed = msg.slice(1, hLen + 1);
const maskedDb = msg.slice(hLen + 1);
const seed = xor(maskedSeed, mgf(maskedDb, hLen));
const db = xor(maskedDb, mgf(seed, k - hLen - 1));
if (compare(iHash, db.slice(0, hLen))) {
throw new Error("decryption error");
}
let i = hLen;
while (db[i] === 0) {
i++;
}
if (db[i++] !== 1) {
throw new Error("decryption error");
}
return db.slice(i);
}
function pkcs1(_key, msg, reverse) {
const p1 = msg.slice(0, 2);
let i = 2;
let status = 0;
while (msg[i++] !== 0) {
if (i >= msg.length) {
status++;
break;
}
}
const ps = msg.slice(2, i - 1);
if (
(p1.toString("hex") !== "0002" && !reverse) ||
(p1.toString("hex") !== "0001" && reverse)
) {
status++;
}
if (ps.length < 8) {
status++;
}
if (status) {
throw new Error("decryption error");
}
return msg.slice(i);
}
function compare(a, b) {
a = Buffer.from(a);
b = Buffer.from(b);
let dif = 0;
let len = a.length;
if (a.length !== b.length) {
dif++;
len = Math.min(a.length, b.length);
}
let i = -1;
while (++i < len) {
dif += a[i] ^ b[i];
}
return dif;
}

View file

@ -1,104 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Calvin Metcalf. All rights reserved. MIT license.
import parseKeys from "internal:deno_node/polyfills/_crypto/crypto_browserify/parse_asn1/mod.js";
import { randomBytes } from "internal:deno_node/polyfills/_crypto/crypto_browserify/randombytes.ts";
import { createHash } from "internal:deno_node/polyfills/internal/crypto/hash.ts";
import mgf from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/mgf.js";
import { xor } from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/xor.js";
import { BN } from "internal:deno_node/polyfills/_crypto/crypto_browserify/bn.js/bn.js";
import { withPublic } from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/with_public.js";
import crt from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_rsa.js";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
export function publicEncrypt(publicKey, msg, reverse) {
let padding;
if (publicKey.padding) {
padding = publicKey.padding;
} else if (reverse) {
padding = 1;
} else {
padding = 4;
}
const key = parseKeys(publicKey);
let paddedMsg;
if (padding === 4) {
paddedMsg = oaep(key, msg);
} else if (padding === 1) {
paddedMsg = pkcs1(key, msg, reverse);
} else if (padding === 3) {
paddedMsg = new BN(msg);
if (paddedMsg.cmp(key.modulus) >= 0) {
throw new Error("data too long for modulus");
}
} else {
throw new Error("unknown padding");
}
if (reverse) {
return crt(paddedMsg, key);
} else {
return withPublic(paddedMsg, key);
}
}
function oaep(key, msg) {
const k = key.modulus.byteLength();
const mLen = msg.length;
const iHash = createHash("sha1").update(Buffer.alloc(0)).digest();
const hLen = iHash.length;
const hLen2 = 2 * hLen;
if (mLen > k - hLen2 - 2) {
throw new Error("message too long");
}
const ps = Buffer.alloc(k - mLen - hLen2 - 2);
const dblen = k - hLen - 1;
const seed = randomBytes(hLen);
const maskedDb = xor(
Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen),
mgf(seed, dblen),
);
const maskedSeed = xor(seed, mgf(maskedDb, hLen));
return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k));
}
function pkcs1(key, msg, reverse) {
const mLen = msg.length;
const k = key.modulus.byteLength();
if (mLen > k - 11) {
throw new Error("message too long");
}
let ps;
if (reverse) {
ps = Buffer.alloc(k - mLen - 3, 0xff);
} else {
ps = nonZero(k - mLen - 3);
}
return new BN(
Buffer.concat([
Buffer.from([
0,
reverse ? 1 : 2,
]),
ps,
Buffer.alloc(1),
msg,
], k),
);
}
function nonZero(len) {
const out = Buffer.allocUnsafe(len);
let i = 0;
let cache = randomBytes(len * 2);
let cur = 0;
let num;
while (i < len) {
if (cur === cache.length) {
cache = randomBytes(len * 2);
cur = 0;
}
num = cache[cur++];
if (num) {
out[i++] = num;
}
}
return out;
}

View file

@ -1,15 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Calvin Metcalf. All rights reserved. MIT license.
import { BN } from "internal:deno_node/polyfills/_crypto/crypto_browserify/bn.js/bn.js";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
export function withPublic(paddedMsg, key) {
return Buffer.from(
paddedMsg
.toRed(BN.mont(key.modulus))
.redPow(new BN(key.publicExponent))
.fromRed()
.toArray(),
);
}

View file

@ -1,11 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 Calvin Metcalf. All rights reserved. MIT license.
export function xor(a, b) {
const len = a.length;
let i = -1;
while (++i < len) {
a[i] ^= b[i];
}
return a;
}

View file

@ -1,47 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright 2017 crypto-browserify. All rights reserved. MIT license.
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import { nextTick } from "internal:deno_node/polyfills/_next_tick.ts";
// limit of Crypto.getRandomValues()
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
const MAX_BYTES = 65536;
// Node supports requesting up to this number of bytes
// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
const MAX_UINT32 = 4294967295;
export function randomBytes(
size: number,
cb?: (err: Error | null, b: Buffer) => void,
) {
// phantomjs needs to throw
if (size > MAX_UINT32) {
throw new RangeError("requested too many random bytes");
}
const bytes = Buffer.allocUnsafe(size);
if (size > 0) { // getRandomValues fails on IE if size == 0
if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
// can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
for (let generated = 0; generated < size; generated += MAX_BYTES) {
// buffer.slice automatically checks if the end is past the end of
// the buffer so we don't have to here
globalThis.crypto.getRandomValues(
bytes.slice(generated, generated + MAX_BYTES),
);
}
} else {
globalThis.crypto.getRandomValues(bytes);
}
}
if (typeof cb === "function") {
return nextTick(function () {
cb(null, bytes);
});
}
return bytes;
}

View file

@ -16,19 +16,8 @@ import type {
BinaryLike,
Encoding,
} from "internal:deno_node/polyfills/internal/crypto/types.ts";
import {
privateDecrypt,
privateEncrypt,
publicDecrypt,
publicEncrypt,
} from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/mod.js";
export {
privateDecrypt,
privateEncrypt,
publicDecrypt,
publicEncrypt,
} from "internal:deno_node/polyfills/_crypto/crypto_browserify/public_encrypt/mod.js";
const { ops } = globalThis.__bootstrap.core;
export type CipherCCMTypes =
| "aes-128-ccm"
@ -281,6 +270,34 @@ export function getCipherInfo(
notImplemented("crypto.getCipherInfo");
}
export function privateEncrypt(
privateKey: ArrayBufferView | string | KeyObject,
buffer: ArrayBufferView | string | KeyObject,
): Buffer {
const padding = privateKey.padding || 1;
return ops.op_node_private_encrypt(privateKey, buffer, padding);
}
export function privateDecrypt(
privateKey: ArrayBufferView | string | KeyObject,
buffer: ArrayBufferView | string | KeyObject,
): Buffer {
const padding = privateKey.padding || 1;
return ops.op_node_private_decrypt(privateKey, buffer, padding);
}
export function publicEncrypt(
publicKey: ArrayBufferView | string | KeyObject,
buffer: ArrayBufferView | string | KeyObject,
): Buffer {
const padding = publicKey.padding || 1;
return ops.op_node_public_encrypt(publicKey, buffer, padding);
}
export function publicDecrypt() {
notImplemented("crypto.publicDecrypt");
}
export default {
privateDecrypt,
privateEncrypt,

View file

@ -1,7 +1,6 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Copyright Joyent, Inc. and Node.js contributors. All rights reserved. MIT license.
import { getCiphers } from "internal:deno_node/polyfills/_crypto/crypto_browserify/browserify_aes/mod.js";
import { notImplemented } from "internal:deno_node/polyfills/_utils.ts";
import { Buffer } from "internal:deno_node/polyfills/buffer.ts";
import {
@ -47,6 +46,28 @@ const digestAlgorithms = [
"sha1",
];
// deno-fmt-ignore
const supportedCiphers = [
"aes-128-ecb", "aes-192-ecb",
"aes-256-ecb", "aes-128-cbc",
"aes-192-cbc", "aes-256-cbc",
"aes128", "aes192",
"aes256", "aes-128-cfb",
"aes-192-cfb", "aes-256-cfb",
"aes-128-cfb8", "aes-192-cfb8",
"aes-256-cfb8", "aes-128-cfb1",
"aes-192-cfb1", "aes-256-cfb1",
"aes-128-ofb", "aes-192-ofb",
"aes-256-ofb", "aes-128-ctr",
"aes-192-ctr", "aes-256-ctr",
"aes-128-gcm", "aes-192-gcm",
"aes-256-gcm"
];
export function getCiphers(): string[] {
return supportedCiphers;
}
let defaultEncoding = "buffer";
export function setDefaultEncoding(val: string) {
@ -112,7 +133,7 @@ export function setEngine(_engine: string, _flags: typeof constants) {
notImplemented("crypto.setEngine");
}
export { getCiphers, kHandle, kKeyObject };
export { kHandle, kKeyObject };
export default {
getDefaultEncoding,

View file

@ -24,6 +24,16 @@ impl Deref for StringOrBuffer {
}
}
impl<'a> TryFrom<&'a StringOrBuffer> for &'a str {
type Error = std::str::Utf8Error;
fn try_from(value: &'a StringOrBuffer) -> Result<Self, Self::Error> {
match value {
StringOrBuffer::String(s) => Ok(s.as_str()),
StringOrBuffer::Buffer(b) => std::str::from_utf8(b.as_ref()),
}
}
}
impl ToV8 for StringOrBuffer {
fn to_v8<'a>(
&mut self,