main funcions fixes

This commit is contained in:
2025-09-29 22:06:11 +09:00
parent 40e016e128
commit c8c3274527
7995 changed files with 1517998 additions and 1057 deletions

View File

@@ -0,0 +1,71 @@
/** Predefined algorithm types */
export declare type DigestAlgorithmType = 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512' | 'sha512-224' | 'sha512-256' | 'sha3-224' | 'sha3-256' | 'sha3-384' | 'sha3-512' | 'shake128' | 'shake256' | 'SHA1' | 'SHA224' | 'SHA256' | 'SHA384' | 'SHA512' | 'SHA512-224' | 'SHA512-256' | 'SHA3-224' | 'SHA3-256' | 'SHA3-384' | 'SHA3-512' | 'SHAKE128' | 'SHAKE256';
export declare type EncryptionAlgorithmType = 'rsa' | 'dsa' | 'RSA' | 'DSA';
export default interface SignerObject {
/**
* Returns the digest algorithm used in `digestData`.
* To use the algorithm other than defined in `DigestAlgorithmType`,
* return an integer array of values from OID string.
* (e.g. [1,3,14,3,2,26] for 'sha1')
*
* @note
* The newer digest algorithm (including SHA224, SHA512-256, SHA3 algorithms, etc.)
* might not be supported by Windows.
*/
getDigestAlgorithm(): DigestAlgorithmType | number[];
/**
* Returns the encryption algorithm used in `encryptData`.
* To use the algorithm other than defined in `EncryptionAlgorithmType`,
* return an integer array of values from OID string.
* (e.g. [1,2,840,113549,1,1,1] for 'rsa')
*/
getEncryptionAlgorithm(): EncryptionAlgorithmType | number[];
/**
* Returns the certificate data, which format is DER binary (X.509 certificate data
* or '.p7b' file data which is based on DER and contains certificates).
*
* You can return an `Array` (not an `ArrayLike`), which contains one or more certificates in format above.
* In this case, each certificates are stored to signed data in order.
* Note that this library does not sort certificates, so the implementation should have responsible for the order of certificates.
*/
getCertificateData(): ArrayBuffer | ArrayBufferView | Array<ArrayBuffer | ArrayBufferView>;
/**
* Returns the public key data, which format is DER binary (X.509 Public Key or '.p7b' file data which is based on DER).
*
* You can return an `Array` (not an `ArrayLike`), which contains one or more public keys in format above.
* In this case, each public keys are stored to signed data in order.
* Note that this library does not sort public keys, so the implementation should have responsible for the order of keys.
*
* @deprecated This method is renamed to {@link getCertificateData} due to the actual purpose of this method
* and `getPublicKeyData` will no longer be used in the future.
*/
getPublicKeyData?(): ArrayBuffer | ArrayBufferView | Array<ArrayBuffer | ArrayBufferView>;
/**
* Digests specified data. The digest algorithm type must be same as the result of `getDigestAlgorithm`.
* Must pick all data from `dataIterator` (until `dataIterator.next().done` is `true`).
*/
digestData(dataIterator: Iterator<ArrayBuffer, void>): PromiseLike<ArrayBuffer | ArrayBufferView>;
/**
* Encrypts specified data with **private key** (i.e. can be verified with the public key from `getCertificateData`). The private key type (algorithm) must be same as the result of `getEncryptionAlgorithm`.
* Must pick all data from `dataIterator` (until `dataIterator.next().done` is `true`).
*
* This method must be implemented if `signData` is not implemented.
*/
encryptData?(dataIterator: Iterator<ArrayBuffer, void>): PromiseLike<ArrayBuffer | ArrayBufferView>;
/**
* Signs specified data with **private key** (i.e. can be verified with the public key from `getCertificateData`).
* The private key type (algorithm) must be same as the result of `getEncryptionAlgorithm`, and the digest algorithm must be same as the result of `getDigestAlgorithm`.
* Must pick all data from `dataIterator` (until `dataIterator.next().done` is `true`).
*
* This method must be implemented if `encryptData` is not implemented.
*
* Note that even if `signData` is implemented, `digestData` must be implemented.
*/
signData?(dataIterator: Iterator<ArrayBuffer, void>): PromiseLike<ArrayBuffer | ArrayBufferView>;
/**
* Make 'timestamp' data, generated by TSA, from specified data (omit this method if not using timestamp).
* Must return entire timestamp response data.
* @param reqData timestamp request data (`TimeStampReq`) to send to TSA
*/
timestampData?(reqData: ArrayBuffer): PromiseLike<ArrayBuffer | ArrayBufferView>;
}

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-enable @typescript-eslint/method-signature-style */

View File

@@ -0,0 +1,7 @@
import DERObject from './data/DERObject.js';
export declare function toUint8Array(bin: ArrayBuffer | ArrayBufferView): Uint8Array;
/** @return [length, afterOffset] */
export declare function calculateDERLength(data: number[] | Uint8Array, offset: number): [number, number];
/** @return [issuer, serialNumber] */
export declare function pickIssuerAndSerialNumberDERFromCert(bin: ArrayBuffer | ArrayBufferView | Array<ArrayBuffer | ArrayBufferView>): [number[], number[]];
export declare function certBinToCertificatesDER(bin: ArrayBuffer | ArrayBufferView | Array<ArrayBuffer | ArrayBufferView>): DERObject[];

View File

@@ -0,0 +1,253 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.certBinToCertificatesDER = exports.pickIssuerAndSerialNumberDERFromCert = exports.calculateDERLength = exports.toUint8Array = void 0;
var DERObject_js_1 = require("./data/DERObject.js");
var KnownOids_js_1 = require("./data/KnownOids.js");
function toUint8Array(bin) {
if ('buffer' in bin) {
return new Uint8Array(bin.buffer, bin.byteOffset, bin.byteLength);
}
else {
return new Uint8Array(bin);
}
}
exports.toUint8Array = toUint8Array;
/** @return [length, afterOffset] */
function calculateDERLength(data, offset) {
var actualLength = 0;
var value = data[offset];
if (value == null) {
throw new Error('Invalid "offset" value');
}
else if (value < 0x80) {
actualLength = value;
++offset;
}
else if (value === 0x80) {
throw new Error('Not supported certificate data (variable length)');
}
else {
var c = value & 0x7f;
++offset;
while (c--) {
if (offset >= data.length) {
throw new Error('Invalid certificate data (invalid sequence length)');
}
actualLength <<= 8;
actualLength |= data[offset];
++offset;
}
}
return [actualLength, offset];
}
exports.calculateDERLength = calculateDERLength;
function skipField(data, offsetOfDataHead) {
var _a = calculateDERLength(data, offsetOfDataHead + 1), len = _a[0], off = _a[1];
return off + len;
}
function pickCertificatesIfDERHasSignedData(ub, offset) {
var _a, _b, _c, _d, _e;
if (ub.length < offset + 2) {
return null;
}
if (ub[offset] !== 0x30) {
return null;
}
var tempLength;
_a = calculateDERLength(ub, offset + 1), tempLength = _a[0], offset = _a[1];
if (tempLength > ub.length - offset) {
throw new Error('Invalid certificate data (insufficient data length)');
}
// if the first item is not contentType, then return
if (ub[offset] !== 0x6) {
return null;
}
var signedDataOid = KnownOids_js_1.OID_SIGNED_DATA.toDER();
for (var i = 0; i < signedDataOid.length; ++i) {
if (ub[offset + i] !== signedDataOid[i]) {
return null;
}
}
// if contentType is OID_SIGNED_DATA, then check sequence format
// ContentInfo.content
offset += signedDataOid.length;
// [0] IMPLICIT
if (ub[offset] !== 0xa0) {
throw new Error('Invalid certificate data (no content in contentInfo)');
}
_b = calculateDERLength(ub, offset + 1), tempLength = _b[0], offset = _b[1];
if (offset + tempLength > ub.length) {
throw new Error('Invalid certificate data (invalid length for content)');
}
// sequence
if (ub[offset] !== 0x30) {
throw new Error('Invalid certificate data (unexpected signedData)');
}
_c = calculateDERLength(ub, offset + 1), tempLength = _c[0], offset = _c[1];
if (offset + tempLength > ub.length) {
throw new Error('Invalid certificate data (invalid length for signedData)');
}
// version
if (ub[offset] !== 0x2 ||
ub[offset + 1] !== 0x1 ||
ub[offset + 2] !== 0x1) {
throw new Error('Invalid certificate data (unexpected signedData.version)');
}
offset += 3;
// digestAlgorithms (skip)
if (ub[offset] !== 0x31) {
throw new Error('Invalid certificate data (no signedData.digestAlgorithms)');
}
_d = calculateDERLength(ub, offset + 1), tempLength = _d[0], offset = _d[1];
if (offset + tempLength > ub.length) {
throw new Error('Invalid certificate data (invalid length for signedData.digestAlgorithms)');
}
offset += tempLength;
// contentInfo (skip)
if (ub[offset] !== 0x30) {
throw new Error('Invalid certificate data (no signedData.contentInfo)');
}
_e = calculateDERLength(ub, offset + 1), tempLength = _e[0], offset = _e[1];
if (offset + tempLength > ub.length) {
throw new Error('Invalid certificate data (invalid length for signedData.contentInfo)');
}
offset += tempLength;
// certificates
if (ub[offset] !== 0xa0) {
throw new Error('Invalid certificate data (no signedData.certificates)');
}
var _f = calculateDERLength(ub, offset + 1), certsLength = _f[0], newOffset = _f[1];
if (newOffset + certsLength > ub.length) {
throw new Error('Invalid certificate data (invalid length for signedData.certificates)');
}
return ub.subarray(offset, newOffset + certsLength);
}
/** @return [issuer, serialNumber] */
function pickIssuerAndSerialNumberDERFromCert(bin) {
var _a, _b;
if (Array.isArray(bin)) {
// use first one and call again
if (bin.length === 0) {
throw new Error('No data is specified.');
}
return pickIssuerAndSerialNumberDERFromCert(bin[0]);
}
var ub = toUint8Array(bin);
if (ub.length < 2) {
throw new Error('Invalid certificate data');
}
if (ub[0] !== 0x30) {
throw new Error('Not supported certificate data (non-`Certificate`-format data)');
}
var certsBin = pickCertificatesIfDERHasSignedData(ub, 0);
if (certsBin) {
// certificates
var _c = calculateDERLength(certsBin, 1), tempLength_1 = _c[0], eaten_1 = _c[1];
if (eaten_1 + tempLength_1 > certsBin.length) {
throw new Error('Invalid certificate data (invalid length for signedData.certificates)');
}
// pick first certificate and call again
if (certsBin[eaten_1] !== 0x30) {
throw new Error('Invalid certificate data (no signedData.certificates[0])');
}
var _d = calculateDERLength(certsBin, eaten_1 + 1), certLength = _d[0], tempOffset = _d[1];
if (tempOffset + certLength > certsBin.length) {
throw new Error('Invalid certificate data (invalid length for signedData.certificates[0])');
}
return pickIssuerAndSerialNumberDERFromCert(certsBin.subarray(eaten_1, tempOffset + certLength));
}
var tempLength;
var eaten;
_a = calculateDERLength(ub, 1), tempLength = _a[0], eaten = _a[1];
if (tempLength > ub.length - eaten) {
throw new Error('Invalid certificate data (insufficient data length)');
}
if (ub[eaten] !== 0x30) {
throw new Error('Invalid certificate data (missing tbsCertificate)');
}
// Certificate
var tbsCertificateLen;
_b = calculateDERLength(ub, eaten + 1), tbsCertificateLen = _b[0], eaten = _b[1];
if (tbsCertificateLen > ub.length - eaten) {
throw new Error('Invalid certificate data (invalid tbsCertificate length)');
}
var tbsOffsetLast = eaten + tbsCertificateLen;
// TBSCertificate
// :skip version
if (ub[eaten] === 0xa0) {
eaten = skipField(ub, eaten);
if (eaten >= tbsOffsetLast) {
throw new Error('Invalid certificate data (insufficient tbsCertificate data: after version)');
}
}
// pick serialNumber
if (ub[eaten] !== 2) {
throw new Error('Invalid certificate data (invalid serialNumber)');
}
var offsetAfterSerialNumber = skipField(ub, eaten);
if (eaten >= tbsOffsetLast) {
throw new Error('Invalid certificate data (insufficient tbsCertificate data: after serialNumber)');
}
var serialNumberDER = [].slice.call(ub, eaten, offsetAfterSerialNumber);
eaten = offsetAfterSerialNumber;
// :skip algorithmIdentifier
if (ub[eaten] !== 0x30) {
throw new Error('Invalid certificate data (invalid algorithmIdentifier)');
}
eaten = skipField(ub, eaten);
if (eaten >= tbsOffsetLast) {
throw new Error('Invalid certificate data (insufficient tbsCertificate data: after serialNumber)');
}
// pick issuer
// Name ::= CHOICE { RDNSequence }
// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
if (ub[eaten] !== 0x30) {
throw new Error('Invalid certificate data (invalid issuer)');
}
var offsetAfterIssuer = skipField(ub, eaten);
if (offsetAfterIssuer > tbsOffsetLast) {
throw new Error('Invalid certificate data (insufficient tbsCertificate data: issuer)');
}
return [
// return entire issuer sequence
[].slice.call(ub, eaten, offsetAfterIssuer),
serialNumberDER,
];
}
exports.pickIssuerAndSerialNumberDERFromCert = pickIssuerAndSerialNumberDERFromCert;
function certBinToCertificatesDER(bin) {
if (Array.isArray(bin)) {
// use all items, map with `certBinToCertificatesDER`, and concat all
return bin
.map(certBinToCertificatesDER)
.reduce(function (prev, cur) { return prev.concat(cur); }, []);
}
var ub = toUint8Array(bin);
var certsBin = pickCertificatesIfDERHasSignedData(ub, 0);
if (certsBin) {
// certificates
var _a = calculateDERLength(certsBin, 1), tempLength = _a[0], eaten = _a[1];
if (eaten + tempLength > certsBin.length) {
throw new Error('Invalid certificate data (invalid length for signedData.certificates)');
}
var offsetLast = eaten + tempLength;
var rawData = [];
for (var offset = eaten; offset < offsetLast;) {
// pick certificates
if (certsBin[offset] !== 0x30) {
throw new Error('Invalid certificate data (no signedData.certificates[*])');
}
var _b = calculateDERLength(certsBin, offset + 1), certLength = _b[0], tempOffset = _b[1];
if (tempOffset + certLength > certsBin.length) {
throw new Error('Invalid certificate data (invalid length for signedData.certificates[*])');
}
rawData.push(new DERObject_js_1.RawDERObject(certsBin.subarray(offset, tempOffset + certLength)));
offset = tempOffset + certLength;
}
return rawData;
}
else {
return [new DERObject_js_1.RawDERObject(ub)];
}
}
exports.certBinToCertificatesDER = certBinToCertificatesDER;

View File

@@ -0,0 +1,7 @@
import DERObject from './DERObject.js';
import ObjectIdentifier from './ObjectIdentifier.js';
export default class AlgorithmIdentifier implements DERObject {
algorithm: ObjectIdentifier;
constructor(algorithm: ObjectIdentifier);
toDER(): number[];
}

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var derUtil_js_1 = require("./derUtil.js");
var AlgorithmIdentifier = /** @class */ (function () {
function AlgorithmIdentifier(algorithm) {
this.algorithm = algorithm;
}
AlgorithmIdentifier.prototype.toDER = function () {
var r = this.algorithm.toDER();
return derUtil_js_1.makeDERSequence(r.concat(
// parameters is not used now
[0x05, 0x00]));
};
return AlgorithmIdentifier;
}());
exports.default = AlgorithmIdentifier;

View File

@@ -0,0 +1,8 @@
import DERObject from './DERObject.js';
import ObjectIdentifier from './ObjectIdentifier.js';
export default class Attribute implements DERObject {
attrType: ObjectIdentifier;
attrValues: DERObject[];
constructor(attrType: ObjectIdentifier, attrValues: DERObject[]);
toDER(): number[];
}

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var derUtil_js_1 = require("./derUtil.js");
var Attribute = /** @class */ (function () {
function Attribute(attrType, attrValues) {
this.attrType = attrType;
this.attrValues = attrValues;
}
Attribute.prototype.toDER = function () {
return derUtil_js_1.makeDERSequence(this.attrType.toDER().concat(derUtil_js_1.arrayToDERSet(this.attrValues)));
};
return Attribute;
}());
exports.default = Attribute;

View File

@@ -0,0 +1,4 @@
import ContentInfo from './ContentInfo.js';
import SignedData from './SignedData.js';
export default class CertificateDataRoot extends ContentInfo<SignedData> {
}

View File

@@ -0,0 +1,26 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var ContentInfo_js_1 = require("./ContentInfo.js");
var CertificateDataRoot = /** @class */ (function (_super) {
__extends(CertificateDataRoot, _super);
function CertificateDataRoot() {
return _super !== null && _super.apply(this, arguments) || this;
}
return CertificateDataRoot;
}(ContentInfo_js_1.default));
exports.default = CertificateDataRoot;

View File

@@ -0,0 +1,8 @@
import DERObject from './DERObject.js';
import ObjectIdentifier from './ObjectIdentifier.js';
export default class ContentInfo<TContent extends DERObject = DERObject> implements DERObject {
contentType: ObjectIdentifier;
content: TContent;
constructor(contentType: ObjectIdentifier, content: TContent);
toDER(): number[];
}

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var derUtil_js_1 = require("./derUtil.js");
// abstract
var ContentInfo = /** @class */ (function () {
function ContentInfo(contentType, content) {
this.contentType = contentType;
this.content = content;
}
ContentInfo.prototype.toDER = function () {
return derUtil_js_1.makeDERSequence(this.contentType
.toDER()
.concat(derUtil_js_1.makeDERTaggedData(0, this.content.toDER())));
};
return ContentInfo;
}());
exports.default = ContentInfo;

View File

@@ -0,0 +1,8 @@
export default interface DERObject {
toDER: () => number[];
}
export declare class RawDERObject implements DERObject {
data: number[] | Uint8Array;
constructor(data: number[] | Uint8Array);
toDER(): number[];
}

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RawDERObject = void 0;
var RawDERObject = /** @class */ (function () {
function RawDERObject(data) {
this.data = data;
}
RawDERObject.prototype.toDER = function () {
return [].slice.call(this.data);
};
return RawDERObject;
}());
exports.RawDERObject = RawDERObject;

View File

@@ -0,0 +1,8 @@
import AlgorithmIdentifier from './AlgorithmIdentifier.js';
import DERObject from './DERObject.js';
export default class DigestInfo implements DERObject {
digestAlgorithm: AlgorithmIdentifier;
digest: ArrayBuffer | ArrayBufferView;
constructor(digestAlgorithm: AlgorithmIdentifier, digest: ArrayBuffer | ArrayBufferView);
toDER(): number[];
}

View File

@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var derUtil_js_1 = require("./derUtil.js");
var DigestInfo = /** @class */ (function () {
function DigestInfo(digestAlgorithm, digest) {
this.digestAlgorithm = digestAlgorithm;
this.digest = digest;
}
DigestInfo.prototype.toDER = function () {
var digest = this.digest;
var digestArray;
if ('buffer' in digest) {
digestArray = new Uint8Array(digest.buffer, digest.byteOffset, digest.byteLength);
}
else {
digestArray = new Uint8Array(digest);
}
var derData = this.digestAlgorithm
.toDER()
.concat(derUtil_js_1.makeDEROctetString(digestArray));
return derUtil_js_1.makeDERSequence(derData);
};
return DigestInfo;
}());
exports.default = DigestInfo;

View File

@@ -0,0 +1,7 @@
import DERObject from './DERObject.js';
export default class IssuerAndSerialNumber implements DERObject {
issuer: DERObject;
serialNumber: DERObject;
constructor(issuer: DERObject, serialNumber: DERObject);
toDER(): number[];
}

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var derUtil_js_1 = require("./derUtil.js");
var IssuerAndSerialNumber = /** @class */ (function () {
function IssuerAndSerialNumber(issuer, serialNumber) {
this.issuer = issuer;
this.serialNumber = serialNumber;
}
IssuerAndSerialNumber.prototype.toDER = function () {
return derUtil_js_1.makeDERSequence(this.issuer.toDER().concat(this.serialNumber.toDER()));
};
return IssuerAndSerialNumber;
}());
exports.default = IssuerAndSerialNumber;

View File

@@ -0,0 +1,23 @@
import ObjectIdentifier from './ObjectIdentifier.js';
export declare const OID_SHA1_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA256_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA384_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA512_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA224_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA512_224_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA512_256_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA3_224_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA3_256_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA3_384_NO_SIGN: ObjectIdentifier;
export declare const OID_SHA3_512_NO_SIGN: ObjectIdentifier;
export declare const OID_SHAKE128_NO_SIGN: ObjectIdentifier;
export declare const OID_SHAKE256_NO_SIGN: ObjectIdentifier;
export declare const OID_RSA: ObjectIdentifier;
export declare const OID_DSA: ObjectIdentifier;
export declare const OID_SIGNED_DATA: ObjectIdentifier;
export declare const OID_CONTENT_TYPE: ObjectIdentifier;
export declare const OID_MESSAGE_DIGEST: ObjectIdentifier;
export declare const OID_SPC_STATEMENT_TYPE_OBJID: ObjectIdentifier;
export declare const OID_SPC_SP_OPUS_INFO_OBJID: ObjectIdentifier;
export declare const OID_SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID: ObjectIdentifier;
export declare const OID_RFC3161_COUNTER_SIGNATURE: ObjectIdentifier;

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OID_RFC3161_COUNTER_SIGNATURE = exports.OID_SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID = exports.OID_SPC_SP_OPUS_INFO_OBJID = exports.OID_SPC_STATEMENT_TYPE_OBJID = exports.OID_MESSAGE_DIGEST = exports.OID_CONTENT_TYPE = exports.OID_SIGNED_DATA = exports.OID_DSA = exports.OID_RSA = exports.OID_SHAKE256_NO_SIGN = exports.OID_SHAKE128_NO_SIGN = exports.OID_SHA3_512_NO_SIGN = exports.OID_SHA3_384_NO_SIGN = exports.OID_SHA3_256_NO_SIGN = exports.OID_SHA3_224_NO_SIGN = exports.OID_SHA512_256_NO_SIGN = exports.OID_SHA512_224_NO_SIGN = exports.OID_SHA224_NO_SIGN = exports.OID_SHA512_NO_SIGN = exports.OID_SHA384_NO_SIGN = exports.OID_SHA256_NO_SIGN = exports.OID_SHA1_NO_SIGN = void 0;
var ObjectIdentifier_js_1 = require("./ObjectIdentifier.js");
// 1.3.14.3.2.26
// prettier-ignore
exports.OID_SHA1_NO_SIGN = new ObjectIdentifier_js_1.default([1, 3, 14, 3, 2, 26]);
// 2.16.840.1.101.3.4.2.1
// prettier-ignore
exports.OID_SHA256_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 1]);
// 2.16.840.1.101.3.4.2.2
// prettier-ignore
exports.OID_SHA384_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 2]);
// 2.16.840.1.101.3.4.2.3
// prettier-ignore
exports.OID_SHA512_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 3]);
// 2.16.840.1.101.3.4.2.4
// prettier-ignore
exports.OID_SHA224_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 4]);
// 2.16.840.1.101.3.4.2.5
// prettier-ignore
exports.OID_SHA512_224_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 5]);
// 2.16.840.1.101.3.4.2.6
// prettier-ignore
exports.OID_SHA512_256_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 6]);
// 2.16.840.1.101.3.4.2.7
// prettier-ignore
exports.OID_SHA3_224_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 7]);
// 2.16.840.1.101.3.4.2.8
// prettier-ignore
exports.OID_SHA3_256_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 8]);
// 2.16.840.1.101.3.4.2.9
// prettier-ignore
exports.OID_SHA3_384_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 9]);
// 2.16.840.1.101.3.4.2.10
// prettier-ignore
exports.OID_SHA3_512_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 10]);
// 2.16.840.1.101.3.4.2.11
// prettier-ignore
exports.OID_SHAKE128_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 11]);
// 2.16.840.1.101.3.4.2.12
// prettier-ignore
exports.OID_SHAKE256_NO_SIGN = new ObjectIdentifier_js_1.default([2, 16, 840, 1, 101, 3, 4, 2, 12]);
// 1.2.840.113549.1.1.1
// prettier-ignore
exports.OID_RSA = new ObjectIdentifier_js_1.default([1, 2, 840, 113549, 1, 1, 1]);
// 1.2.840.10040.4.1
// prettier-ignore
exports.OID_DSA = new ObjectIdentifier_js_1.default([1, 2, 840, 10040, 4, 1]);
// 1.2.840.113549.1.7.2
// prettier-ignore
exports.OID_SIGNED_DATA = new ObjectIdentifier_js_1.default([1, 2, 840, 113549, 1, 7, 2]);
// 1.2.840.113549.1.9.3
// prettier-ignore
exports.OID_CONTENT_TYPE = new ObjectIdentifier_js_1.default([1, 2, 840, 113549, 1, 9, 3]);
// 1.2.840.113549.1.9.4
// prettier-ignore
exports.OID_MESSAGE_DIGEST = new ObjectIdentifier_js_1.default([1, 2, 840, 113549, 1, 9, 4]);
// 1.3.6.1.4.1.311.2.1.11
// prettier-ignore
exports.OID_SPC_STATEMENT_TYPE_OBJID = new ObjectIdentifier_js_1.default([1, 3, 6, 1, 4, 1, 311, 2, 1, 11]);
// 1.3.6.1.4.1.311.2.1.12
// prettier-ignore
exports.OID_SPC_SP_OPUS_INFO_OBJID = new ObjectIdentifier_js_1.default([1, 3, 6, 1, 4, 1, 311, 2, 1, 12]);
// 1.3.6.1.4.1.311.2.1.21
// prettier-ignore
exports.OID_SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID = new ObjectIdentifier_js_1.default([1, 3, 6, 1, 4, 1, 311, 2, 1, 21]);
// 1.3.6.1.4.1.311.3.3.1
// prettier-ignore
exports.OID_RFC3161_COUNTER_SIGNATURE = new ObjectIdentifier_js_1.default([1, 3, 6, 1, 4, 1, 311, 3, 3, 1]);

View File

@@ -0,0 +1,6 @@
import DERObject from './DERObject.js';
export default class ObjectIdentifier implements DERObject {
value: number[];
constructor(value: number[] | string);
toDER(): number[];
}

View File

@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var derUtil_js_1 = require("./derUtil.js");
var ObjectIdentifier = /** @class */ (function () {
function ObjectIdentifier(value) {
if (typeof value === 'string') {
this.value = value.split(/\./g).map(function (s) { return Number(s); });
}
else {
this.value = value;
}
}
ObjectIdentifier.prototype.toDER = function () {
var id = this.value;
var r = [];
if (id.length < 2) {
throw new Error("Unexpected 'value' field");
}
// first byte will be (x * 40 + y) for 'x.y.****'
r.push(id[0] * 40 + id[1]);
for (var i = 2; i < id.length; ++i) {
// store as variable-length value
var val = id[i];
var isFirst = true;
var insertPos = r.length;
while (true) {
var v = val & 0x7f;
if (!isFirst) {
v += 0x80;
}
r.splice(insertPos, 0, v);
if (val < 0x80) {
break;
}
isFirst = false;
val = Math.floor(val / 0x80);
}
}
return [0x06].concat(derUtil_js_1.makeDERLength(r.length)).concat(r);
};
return ObjectIdentifier;
}());
exports.default = ObjectIdentifier;

View File

@@ -0,0 +1,13 @@
import DigestAlgorithmIdentifier from './AlgorithmIdentifier.js';
import ContentInfo from './ContentInfo.js';
import DERObject from './DERObject.js';
export default class SignedData implements DERObject {
version: number;
digestAlgorithms: DigestAlgorithmIdentifier[];
contentInfo: ContentInfo;
signerInfos: DERObject[];
certificates?: DERObject[] | undefined;
crls?: DERObject[] | undefined;
constructor(version: number, digestAlgorithms: DigestAlgorithmIdentifier[], contentInfo: ContentInfo, signerInfos: DERObject[], certificates?: DERObject[] | undefined, crls?: DERObject[] | undefined);
toDER(): number[];
}

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var derUtil_js_1 = require("./derUtil.js");
var SignedData = /** @class */ (function () {
function SignedData(version, digestAlgorithms, contentInfo, signerInfos, certificates, crls) {
this.version = version;
this.digestAlgorithms = digestAlgorithms;
this.contentInfo = contentInfo;
this.signerInfos = signerInfos;
this.certificates = certificates;
this.crls = crls;
}
SignedData.prototype.toDER = function () {
var r = [0x02, 0x01, this.version & 0xff]
.concat(derUtil_js_1.arrayToDERSet(this.digestAlgorithms))
.concat(this.contentInfo.toDER());
if (this.certificates && this.certificates.length > 0) {
var allCertsDER = derUtil_js_1.arrayToDERSet(this.certificates);
// IMPLICIT SET
allCertsDER[0] = 0xa0;
r = r.concat(allCertsDER);
}
if (this.crls) {
r = r.concat(derUtil_js_1.makeDERTaggedData(1, derUtil_js_1.arrayToDERSet(this.crls)));
}
r = r.concat(derUtil_js_1.arrayToDERSet(this.signerInfos));
return derUtil_js_1.makeDERSequence(r);
};
return SignedData;
}());
exports.default = SignedData;

View File

@@ -0,0 +1,15 @@
import DERObject from './DERObject.js';
import IssuerAndSerialNumber from './IssuerAndSerialNumber.js';
import AlgorithmIdentifier from './AlgorithmIdentifier.js';
import Attribute from './Attribute.js';
export default class SignerInfo implements DERObject {
version: number;
issuerAndSerialNumber: IssuerAndSerialNumber;
digestAlgorithm: AlgorithmIdentifier;
digestEncryptionAlgorithm: AlgorithmIdentifier;
encryptedDigest: Uint8Array;
authenticatedAttributes?: Attribute[] | undefined;
unauthenticatedAttributes?: Attribute[] | undefined;
constructor(version: number, issuerAndSerialNumber: IssuerAndSerialNumber, digestAlgorithm: AlgorithmIdentifier, digestEncryptionAlgorithm: AlgorithmIdentifier, encryptedDigest: Uint8Array, authenticatedAttributes?: Attribute[] | undefined, unauthenticatedAttributes?: Attribute[] | undefined);
toDER(): number[];
}

View File

@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var derUtil_js_1 = require("./derUtil.js");
var SignerInfo = /** @class */ (function () {
function SignerInfo(version, issuerAndSerialNumber, digestAlgorithm, digestEncryptionAlgorithm, encryptedDigest, authenticatedAttributes, unauthenticatedAttributes) {
this.version = version;
this.issuerAndSerialNumber = issuerAndSerialNumber;
this.digestAlgorithm = digestAlgorithm;
this.digestEncryptionAlgorithm = digestEncryptionAlgorithm;
this.encryptedDigest = encryptedDigest;
this.authenticatedAttributes = authenticatedAttributes;
this.unauthenticatedAttributes = unauthenticatedAttributes;
}
SignerInfo.prototype.toDER = function () {
var r = [0x02, 0x01, this.version & 0xff]
.concat(this.issuerAndSerialNumber.toDER())
.concat(this.digestAlgorithm.toDER());
if (this.authenticatedAttributes &&
this.authenticatedAttributes.length > 0) {
var a = derUtil_js_1.arrayToDERSet(this.authenticatedAttributes);
// [0] IMPLICIT
a[0] = 0xa0;
r = r.concat(a);
}
r = r
.concat(this.digestEncryptionAlgorithm.toDER())
.concat(derUtil_js_1.makeDEROctetString(this.encryptedDigest));
if (this.unauthenticatedAttributes &&
this.unauthenticatedAttributes.length > 0) {
var u = derUtil_js_1.arrayToDERSet(this.unauthenticatedAttributes);
// [1] IMPLICIT
u[0] = 0xa1;
r = r.concat(u);
}
return derUtil_js_1.makeDERSequence(r);
};
return SignerInfo;
}());
exports.default = SignerInfo;

View File

@@ -0,0 +1,21 @@
import ContentInfo from './ContentInfo.js';
import DigestInfo from './DigestInfo.js';
import ObjectIdentifier from './ObjectIdentifier.js';
import DERObject from './DERObject.js';
export declare const SPC_INDIRECT_DATA_OBJID: ObjectIdentifier;
export declare class SpcAttributeTypeAndOptionalValue<TValue extends DERObject = DERObject> {
type: ObjectIdentifier;
value: TValue;
constructor(type: ObjectIdentifier, value: TValue);
toDER(): number[];
}
export default class SpcIndirectDataContent implements DERObject {
data: SpcAttributeTypeAndOptionalValue;
messageDigest: DigestInfo;
constructor(data: SpcAttributeTypeAndOptionalValue, messageDigest: DigestInfo);
toDER(): number[];
toDERWithoutHeader(): number[];
}
export declare class SpcIndirectDataContentInfo extends ContentInfo<SpcIndirectDataContent> {
constructor(content: SpcIndirectDataContent);
}

View File

@@ -0,0 +1,57 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpcIndirectDataContentInfo = exports.SpcAttributeTypeAndOptionalValue = exports.SPC_INDIRECT_DATA_OBJID = void 0;
var ContentInfo_js_1 = require("./ContentInfo.js");
var ObjectIdentifier_js_1 = require("./ObjectIdentifier.js");
var derUtil_js_1 = require("./derUtil.js");
// prettier-ignore
exports.SPC_INDIRECT_DATA_OBJID = new ObjectIdentifier_js_1.default([1, 3, 6, 1, 4, 1, 311, 2, 1, 4]);
var SpcAttributeTypeAndOptionalValue = /** @class */ (function () {
function SpcAttributeTypeAndOptionalValue(type, value) {
this.type = type;
this.value = value;
}
SpcAttributeTypeAndOptionalValue.prototype.toDER = function () {
return derUtil_js_1.makeDERSequence(this.type.toDER().concat(this.value.toDER()));
};
return SpcAttributeTypeAndOptionalValue;
}());
exports.SpcAttributeTypeAndOptionalValue = SpcAttributeTypeAndOptionalValue;
var SpcIndirectDataContent = /** @class */ (function () {
function SpcIndirectDataContent(data, messageDigest) {
this.data = data;
this.messageDigest = messageDigest;
}
SpcIndirectDataContent.prototype.toDER = function () {
return derUtil_js_1.makeDERSequence(this.toDERWithoutHeader());
};
// this is used for calculating 'messageDigest'
SpcIndirectDataContent.prototype.toDERWithoutHeader = function () {
return this.data.toDER().concat(this.messageDigest.toDER());
};
return SpcIndirectDataContent;
}());
exports.default = SpcIndirectDataContent;
var SpcIndirectDataContentInfo = /** @class */ (function (_super) {
__extends(SpcIndirectDataContentInfo, _super);
function SpcIndirectDataContentInfo(content) {
return _super.call(this, exports.SPC_INDIRECT_DATA_OBJID, content) || this;
}
return SpcIndirectDataContentInfo;
}(ContentInfo_js_1.default));
exports.SpcIndirectDataContentInfo = SpcIndirectDataContentInfo;

View File

@@ -0,0 +1,16 @@
import DERObject from './DERObject.js';
/**
* Abstract data SpcLink. Must use either `SpcLinkUrl` or `SpcLinkFile` instead.
*/
export default abstract class SpcLink implements DERObject {
private readonly tag;
value: DERObject;
constructor(tag: number, value: DERObject);
toDER(): number[];
}
export declare class SpcLinkUrl extends SpcLink {
constructor(url: string);
}
export declare class SpcLinkFile extends SpcLink {
constructor(file: string);
}

View File

@@ -0,0 +1,65 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpcLinkFile = exports.SpcLinkUrl = void 0;
var DERObject_js_1 = require("./DERObject.js");
var derUtil_js_1 = require("./derUtil.js");
/**
* Abstract data SpcLink. Must use either `SpcLinkUrl` or `SpcLinkFile` instead.
*/
var SpcLink = /** @class */ (function () {
function SpcLink(tag, value) {
this.tag = tag;
this.value = value;
}
SpcLink.prototype.toDER = function () {
var v = this.value.toDER();
if (this.tag === 2) {
// EXPLICIT
return derUtil_js_1.makeDERTaggedData(this.tag, v);
}
else {
// IMPLICIT
v[0] = 0x80 + this.tag;
return v;
}
};
return SpcLink;
}());
exports.default = SpcLink;
var SpcLinkUrl = /** @class */ (function (_super) {
__extends(SpcLinkUrl, _super);
function SpcLinkUrl(url) {
return _super.call(this, 0, new DERObject_js_1.RawDERObject(derUtil_js_1.makeDERIA5String(url))) || this;
}
return SpcLinkUrl;
}(SpcLink));
exports.SpcLinkUrl = SpcLinkUrl;
// moniker is not supported now (currently unused)
var SpcLinkFile = /** @class */ (function (_super) {
__extends(SpcLinkFile, _super);
function SpcLinkFile(file) {
var _this = this;
var v = derUtil_js_1.makeDERBMPString(file);
// [0] IMPLICIT BMPSTRING
v[0] = 0x80;
_this = _super.call(this, 2, new DERObject_js_1.RawDERObject(v)) || this;
return _this;
}
return SpcLinkFile;
}(SpcLink));
exports.SpcLinkFile = SpcLinkFile;

View File

@@ -0,0 +1,19 @@
import DERObject from './DERObject.js';
import ObjectIdentifier from './ObjectIdentifier.js';
import { SpcAttributeTypeAndOptionalValue } from './SpcIndirectDataContent.js';
import SpcLink from './SpcLink.js';
export declare const SPC_PE_IMAGE_DATA_OBJID: ObjectIdentifier;
export declare const enum SpcPeImageFlags {
IncludeResources = 0,
IncludeDebugInfo = 1,
IncludeImportAddressTable = 2
}
export default class SpcPeImageData implements DERObject {
flags: SpcPeImageFlags;
file: SpcLink;
constructor(flags: SpcPeImageFlags, file: SpcLink);
toDER(): number[];
}
export declare class SpcPeImageAttributeTypeAndOptionalValue extends SpcAttributeTypeAndOptionalValue<SpcPeImageData> {
constructor(value: SpcPeImageData);
}

View File

@@ -0,0 +1,44 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpcPeImageAttributeTypeAndOptionalValue = exports.SPC_PE_IMAGE_DATA_OBJID = void 0;
var ObjectIdentifier_js_1 = require("./ObjectIdentifier.js");
var SpcIndirectDataContent_js_1 = require("./SpcIndirectDataContent.js");
var derUtil_js_1 = require("./derUtil.js");
// prettier-ignore
exports.SPC_PE_IMAGE_DATA_OBJID = new ObjectIdentifier_js_1.default([1, 3, 6, 1, 4, 1, 311, 2, 1, 15]);
var SpcPeImageData = /** @class */ (function () {
function SpcPeImageData(flags, file) {
this.flags = flags;
this.file = file;
}
SpcPeImageData.prototype.toDER = function () {
return derUtil_js_1.makeDERSequence([0x03, 0x01, this.flags & 0xff].concat(
// undocumented -- SpcLink must be tagged
derUtil_js_1.makeDERTaggedData(0, this.file.toDER())));
};
return SpcPeImageData;
}());
exports.default = SpcPeImageData;
var SpcPeImageAttributeTypeAndOptionalValue = /** @class */ (function (_super) {
__extends(SpcPeImageAttributeTypeAndOptionalValue, _super);
function SpcPeImageAttributeTypeAndOptionalValue(value) {
return _super.call(this, exports.SPC_PE_IMAGE_DATA_OBJID, value) || this;
}
return SpcPeImageAttributeTypeAndOptionalValue;
}(SpcIndirectDataContent_js_1.SpcAttributeTypeAndOptionalValue));
exports.SpcPeImageAttributeTypeAndOptionalValue = SpcPeImageAttributeTypeAndOptionalValue;

View File

@@ -0,0 +1,8 @@
import DERObject from './DERObject.js';
export declare function makeDERLength(length: number): number[];
export declare function makeDERIA5String(text: string): number[];
export declare function makeDERBMPString(text: string): number[];
export declare function makeDEROctetString(bin: number[] | Uint8Array): number[];
export declare function makeDERTaggedData(tag: number, body: number[]): number[];
export declare function makeDERSequence(body: number[]): number[];
export declare function arrayToDERSet(items: Array<DERObject | number[]>): number[];

View File

@@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayToDERSet = exports.makeDERSequence = exports.makeDERTaggedData = exports.makeDEROctetString = exports.makeDERBMPString = exports.makeDERIA5String = exports.makeDERLength = void 0;
function makeDERLength(length) {
if (length < 0x80) {
return [length];
}
var r = [];
while (true) {
r.push(length & 0xff);
if (length < 0x100) {
break;
}
length >>= 8;
}
r.push(0x80 + r.length);
return r.reverse();
}
exports.makeDERLength = makeDERLength;
function makeDERIA5String(text) {
// convert to char-code array and filter to [0-127]
var r = [].map
.call(text, function (c) { return c.charCodeAt(0); })
.filter(function (n) { return n < 128; });
return [0x16].concat(makeDERLength(r.length)).concat(r);
}
exports.makeDERIA5String = makeDERIA5String;
function makeDERBMPString(text) {
// convert to char-code array
// NOTE: In ECMAScript `charCodeAt` returns surrogate pair for >=0x10000 codes,
// and surrogate pair is valid for BMPString data
var r = [].map.call(text, function (c) { return c.charCodeAt(0); });
var ua = new Uint8Array(r.length * 2);
var dv = new DataView(ua.buffer);
// store codes as big-endian
r.forEach(function (v, i) {
dv.setUint16(i * 2, v, false);
});
return [0x1e].concat(makeDERLength(ua.length)).concat(
// convert Uint8Array to number[] (not using spread operator)
[].slice.call(ua));
}
exports.makeDERBMPString = makeDERBMPString;
function makeDEROctetString(bin) {
if (!(bin instanceof Array)) {
// convert Uint8Array to number[] (not using spread operator)
bin = [].slice.call(bin);
}
return [0x04].concat(makeDERLength(bin.length)).concat(bin);
}
exports.makeDEROctetString = makeDEROctetString;
function makeDERTaggedData(tag, body) {
return [0xa0 + tag].concat(makeDERLength(body.length)).concat(body);
}
exports.makeDERTaggedData = makeDERTaggedData;
function makeDERSequence(body) {
return [0x30].concat(makeDERLength(body.length)).concat(body);
}
exports.makeDERSequence = makeDERSequence;
function arrayToDERSet(items) {
var r = items.reduce(function (prev, item) {
return prev.concat(item instanceof Array ? item : item.toDER());
}, []);
return [0x31].concat(makeDERLength(r.length)).concat(r);
}
exports.arrayToDERSet = arrayToDERSet;

View File

@@ -0,0 +1,13 @@
import { NtExecutable } from 'pe-library';
import SignerObject, { DigestAlgorithmType, EncryptionAlgorithmType } from './SignerObject.js';
/**
* Generates the executable binary data with signed info.
* This function is like an extension of `generate` method of `NtExecutable`.
* @param executable a valid instance of `NtExecutable`
* @param signer user-defined `SignerObject` instance for signing
* @param alignment alignment value for placing certificate data
* (using `executable.getFileAlignment()` if omitted)
* @return Promise-like (Thenable) object which will resolve with generated executable binary
*/
export declare function generateExecutableWithSign(executable: NtExecutable, signer: SignerObject, alignment?: number): PromiseLike<ArrayBuffer>;
export { SignerObject, DigestAlgorithmType, EncryptionAlgorithmType };

View File

@@ -0,0 +1,400 @@
"use strict";
// refs.
// - Windows Authenticode Portable Executable Signature Format
// https://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/authenticode_pe.docx
// - RFC 2315 - PKCS #7: Cryptographic Message Syntax Version 1.5
// https://tools.ietf.org/html/rfc2315
// - RFC 3280 - Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile
// https://tools.ietf.org/html/rfc3280
// - Object IDs associated with Microsoft cryptography
// https://support.microsoft.com/en-us/help/287547/object-ids-associated-with-microsoft-cryptography
// - OID repository
// http://oid-info.com/
// - RFC 3161 - Internet X.509 Public Key Infrastructure Time-Stamp Protocol (TSP)
// https://tools.ietf.org/html/rfc3161
// - mono/AuthenticodeDeformatter.cs
// https://github.com/mono/mono/blob/master/mcs/class/Mono.Security/Mono.Security.Authenticode/AuthenticodeDeformatter.cs
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateExecutableWithSign = void 0;
var pe_library_1 = require("pe-library");
var functions_js_1 = require("../util/functions.js");
var certUtil_js_1 = require("./certUtil.js");
var AlgorithmIdentifier_js_1 = require("./data/AlgorithmIdentifier.js");
var CertificateDataRoot_js_1 = require("./data/CertificateDataRoot.js");
var DERObject_js_1 = require("./data/DERObject.js");
var DigestInfo_js_1 = require("./data/DigestInfo.js");
var IssuerAndSerialNumber_js_1 = require("./data/IssuerAndSerialNumber.js");
var KnownOids = require("./data/KnownOids.js");
var SignedData_js_1 = require("./data/SignedData.js");
var SignerInfo_js_1 = require("./data/SignerInfo.js");
var SpcIndirectDataContent_js_1 = require("./data/SpcIndirectDataContent.js");
var SpcPeImageData_js_1 = require("./data/SpcPeImageData.js");
var SpcLink_js_1 = require("./data/SpcLink.js");
var Attribute_js_1 = require("./data/Attribute.js");
var derUtil_js_1 = require("./data/derUtil.js");
var ContentInfo_js_1 = require("./data/ContentInfo.js");
var ObjectIdentifier_js_1 = require("./data/ObjectIdentifier.js");
var timestamp_js_1 = require("./timestamp.js");
function makeSimpleIterator(data) {
var done = false;
return {
next: function () {
if (done) {
return {
done: true,
value: undefined,
};
}
else {
done = true;
return {
done: false,
value: data,
};
}
},
};
}
function validateSignerObject(signer) {
if (!signer.encryptData && !signer.signData) {
throw new Error('Signer object must implement either `encryptData` or `signData`.');
}
}
function calculateExecutableDigest(executable, signer, alignment) {
function inner() {
var checkSumOffset, certificateTableOffset, rawHeader, targetSections, sectionCount, sectionStartOffset, sectionEndOffset, sectionHeadersSize, secHeader, secArray_1, off, _i, targetSections_1, section, exData, alignedLength, diff;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
checkSumOffset = executable.dosHeader.newHeaderAddress + 88;
certificateTableOffset = executable.dosHeader.newHeaderAddress +
executable.newHeader.getDataDirectoryOffset() +
pe_library_1.Format.ImageDataDirectoryArray.itemSize *
pe_library_1.Format.ImageDirectoryEntry.Certificate;
rawHeader = executable.getRawHeader();
targetSections = executable.getAllSections();
sectionCount = targetSections.length;
sectionStartOffset = rawHeader.byteLength;
sectionEndOffset = functions_js_1.roundUp(sectionStartOffset +
sectionCount * pe_library_1.Format.ImageSectionHeaderArray.itemSize, executable.getFileAlignment());
sectionHeadersSize = sectionEndOffset - sectionStartOffset;
secHeader = new ArrayBuffer(sectionHeadersSize);
{
secArray_1 = pe_library_1.Format.ImageSectionHeaderArray.from(secHeader, sectionCount);
targetSections.forEach(function (sec, i) {
secArray_1.set(i, sec.info);
});
}
// pick from head to immediately before checksum
return [4 /*yield*/, functions_js_1.allocatePartialBinary(rawHeader, 0, checkSumOffset)];
case 1:
// pick from head to immediately before checksum
_a.sent();
// pick from the end of checksum to immediately before 'Certificate Table' header
return [4 /*yield*/, functions_js_1.allocatePartialBinary(rawHeader, checkSumOffset + 4, certificateTableOffset - (checkSumOffset + 4))];
case 2:
// pick from the end of checksum to immediately before 'Certificate Table' header
_a.sent();
off = certificateTableOffset +
pe_library_1.Format.ImageDataDirectoryArray.itemSize;
return [4 /*yield*/, functions_js_1.allocatePartialBinary(executable.getRawHeader(), off, executable.getTotalHeaderSize() - off)];
case 3:
_a.sent();
// pick section header
return [4 /*yield*/, secHeader];
case 4:
// pick section header
_a.sent();
_i = 0, targetSections_1 = targetSections;
_a.label = 5;
case 5:
if (!(_i < targetSections_1.length)) return [3 /*break*/, 8];
section = targetSections_1[_i];
if (!section.data) return [3 /*break*/, 7];
return [4 /*yield*/, section.data];
case 6:
_a.sent();
_a.label = 7;
case 7:
_i++;
return [3 /*break*/, 5];
case 8:
exData = executable.getExtraData();
if (!(exData !== null)) return [3 /*break*/, 11];
return [4 /*yield*/, exData];
case 9:
_a.sent();
alignedLength = functions_js_1.roundUp(exData.byteLength, alignment);
diff = alignedLength - exData.byteLength;
if (!(diff !== 0)) return [3 /*break*/, 11];
return [4 /*yield*/, new Uint8Array(diff).buffer];
case 10:
_a.sent();
_a.label = 11;
case 11: return [2 /*return*/];
}
});
}
return signer.digestData(inner());
}
function getAlgorithmIdentifierObject(type) {
if (typeof type !== 'string') {
return new AlgorithmIdentifier_js_1.default(new ObjectIdentifier_js_1.default(type));
}
switch (type) {
case 'sha1':
case 'SHA1':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA1_NO_SIGN);
case 'sha256':
case 'SHA256':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA256_NO_SIGN);
case 'sha384':
case 'SHA384':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA384_NO_SIGN);
case 'sha512':
case 'SHA512':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA512_NO_SIGN);
case 'sha224':
case 'SHA224':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA224_NO_SIGN);
case 'sha512-224':
case 'SHA512-224':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA512_224_NO_SIGN);
case 'sha512-256':
case 'SHA512-256':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA512_256_NO_SIGN);
case 'sha3-224':
case 'SHA3-224':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA3_224_NO_SIGN);
case 'sha3-256':
case 'SHA3-256':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA3_256_NO_SIGN);
case 'sha3-384':
case 'SHA3-384':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA3_384_NO_SIGN);
case 'sha3-512':
case 'SHA3-512':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHA3_512_NO_SIGN);
case 'shake128':
case 'SHAKE128':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHAKE128_NO_SIGN);
case 'shake256':
case 'SHAKE256':
return new AlgorithmIdentifier_js_1.default(KnownOids.OID_SHAKE256_NO_SIGN);
default:
throw new Error('Invalid or unsupported digest algorithm');
}
}
function doSign(signer, digestAlgorithm, dataIterator) {
if (signer.signData) {
return signer.signData(dataIterator);
}
else {
return signer.digestData(dataIterator).then(function (digestAttributes) {
// encrypting DigestInfo with digest of 'attributes' set
var digestInfoBin = new Uint8Array(new DigestInfo_js_1.default(digestAlgorithm, digestAttributes).toDER()).buffer;
// (eencryptData should be defined here)
return signer.encryptData(makeSimpleIterator(digestInfoBin));
});
}
}
/**
* Generates the executable binary data with signed info.
* This function is like an extension of `generate` method of `NtExecutable`.
* @param executable a valid instance of `NtExecutable`
* @param signer user-defined `SignerObject` instance for signing
* @param alignment alignment value for placing certificate data
* (using `executable.getFileAlignment()` if omitted)
* @return Promise-like (Thenable) object which will resolve with generated executable binary
*/
function generateExecutableWithSign(executable, signer, alignment) {
validateSignerObject(signer);
var certAlignment;
if (typeof alignment === 'number') {
if (alignment <= 0) {
throw new Error('Invalid alignment value');
}
certAlignment = alignment;
}
else {
certAlignment = executable.getFileAlignment();
}
var digestAlgorithm = getAlgorithmIdentifierObject(signer.getDigestAlgorithm());
var digestEncryptionAlgorithm;
var a = signer.getEncryptionAlgorithm();
if (typeof a !== 'string') {
digestEncryptionAlgorithm = new AlgorithmIdentifier_js_1.default(new ObjectIdentifier_js_1.default(a));
}
else {
switch (a) {
case 'rsa':
case 'RSA':
digestEncryptionAlgorithm = new AlgorithmIdentifier_js_1.default(KnownOids.OID_RSA);
break;
case 'dsa':
case 'DSA':
digestEncryptionAlgorithm = new AlgorithmIdentifier_js_1.default(KnownOids.OID_DSA);
break;
default:
throw new Error('Invalid or unsupported digest encryption algorithm');
}
}
// (for compatibility)
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
var cert = signer.getCertificateData
? signer.getCertificateData()
: signer.getPublicKeyData();
var _a = certUtil_js_1.pickIssuerAndSerialNumberDERFromCert(cert), issuer = _a[0], serialNumber = _a[1];
return (
// calculate digest
calculateExecutableDigest(executable, signer, certAlignment)
// make content, content's digest, and sign
.then(function (digest) {
var content = new SpcIndirectDataContent_js_1.default(new SpcPeImageData_js_1.SpcPeImageAttributeTypeAndOptionalValue(new SpcPeImageData_js_1.default(0 /* IncludeResources */, new SpcLink_js_1.SpcLinkFile(''))), new DigestInfo_js_1.default(digestAlgorithm, digest));
return (signer
.digestData(makeSimpleIterator(new Uint8Array(content.toDERWithoutHeader())
.buffer))
// make sign
.then(function (contentDigest) {
var attributes = [
new Attribute_js_1.default(KnownOids.OID_SPC_SP_OPUS_INFO_OBJID,
// (SpcSpOpusInfo) null sequence
[new DERObject_js_1.RawDERObject([0x30, 0x00])]),
new Attribute_js_1.default(KnownOids.OID_CONTENT_TYPE, [
SpcIndirectDataContent_js_1.SPC_INDIRECT_DATA_OBJID,
]),
new Attribute_js_1.default(KnownOids.OID_SPC_STATEMENT_TYPE_OBJID, [
new DERObject_js_1.RawDERObject(derUtil_js_1.makeDERSequence(KnownOids.OID_SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID.toDER())),
]),
new Attribute_js_1.default(KnownOids.OID_MESSAGE_DIGEST, [
new DERObject_js_1.RawDERObject(derUtil_js_1.makeDEROctetString(certUtil_js_1.toUint8Array(contentDigest))),
]),
];
// get digest of 'attributes' set
var attrBin = new Uint8Array(derUtil_js_1.arrayToDERSet(attributes)).buffer;
return doSign(signer, digestAlgorithm, makeSimpleIterator(attrBin)).then(function (signed) {
return [content, attributes, signed];
});
}));
})
// make cert bin
.then(function (_a) {
var content = _a[0], attributes = _a[1], signed = _a[2];
var signerInfo = new SignerInfo_js_1.default(
// version
1,
// issuerAndSerialNumber
new IssuerAndSerialNumber_js_1.default(new DERObject_js_1.RawDERObject(issuer), new DERObject_js_1.RawDERObject(serialNumber)),
// digestAlgorithm
digestAlgorithm,
// digestEncryptionAlgorithm
digestEncryptionAlgorithm,
// encryptedDigest
certUtil_js_1.toUint8Array(signed),
// authenticatedAttributes
attributes);
if (!signer.timestampData) {
return [content, signerInfo];
}
// timestamp
return (signer
// make digest of encrypted data for make timestamp
.digestData(makeSimpleIterator(functions_js_1.cloneToArrayBuffer(signed)))
.then(function (digestEncryptedBase) {
var digestEncrypted = timestamp_js_1.createTimestampRequest(digestEncryptedBase, digestAlgorithm);
// request timestamp
return signer.timestampData(digestEncrypted).then(function (timestamp) {
// pick up signedData
var timestampSignedData = timestamp_js_1.pickSignedDataFromTimestampResponse(timestamp);
// add timestamp to 'unauthenticatedAttributes'
signerInfo.unauthenticatedAttributes = [
new Attribute_js_1.default(KnownOids.OID_RFC3161_COUNTER_SIGNATURE, [
new ContentInfo_js_1.default(KnownOids.OID_SIGNED_DATA, new DERObject_js_1.RawDERObject(certUtil_js_1.toUint8Array(timestampSignedData))),
]),
];
return [content, signerInfo];
});
}));
})
.then(function (_a) {
var content = _a[0], signerInfo = _a[1];
// make certificate data
var root = new CertificateDataRoot_js_1.default(KnownOids.OID_SIGNED_DATA, new SignedData_js_1.default(
// version
1,
// digestAlgorithms
[digestAlgorithm],
// contentInfo
new SpcIndirectDataContent_js_1.SpcIndirectDataContentInfo(content),
// signerInfos
[signerInfo],
// certificates
certUtil_js_1.certBinToCertificatesDER(cert)));
var certBin = new Uint8Array(root.toDER());
var resultBin = new ArrayBuffer(8 + certBin.length);
// make WIN_CERTIFICATE
var resultView = new DataView(resultBin);
// dwLength
resultView.setUint32(0, certBin.length + 8, true);
// wRevision : 0x0200 (revision 2)
resultView.setUint16(4, 0x200, true);
// wCertificateType : 0x0002
resultView.setUint16(6, 0x2, true);
functions_js_1.copyBuffer(resultBin, 8, certBin, 0, certBin.byteLength);
return resultBin;
})
.then(function (certBin) {
var alignedSize = functions_js_1.roundUp(certBin.byteLength, certAlignment);
// NOTE: The certificate data must follow the extra data.
// To achieve this, the another size between them must be added to the padding size.
// (The extra data may not be aligned, but the certificate data should be aligned.)
var paddingSize = alignedSize;
var exData = executable.getExtraData();
if (exData !== null) {
var diffSize = functions_js_1.roundUp(exData.byteLength, certAlignment) -
exData.byteLength;
paddingSize += diffSize;
}
var newBin = executable.generate(paddingSize);
var certOffset = newBin.byteLength - alignedSize;
var dirArray = pe_library_1.Format.ImageDataDirectoryArray.from(newBin, executable.dosHeader.newHeaderAddress +
executable.newHeader.getDataDirectoryOffset());
dirArray.set(pe_library_1.Format.ImageDirectoryEntry.Certificate, {
size: alignedSize,
virtualAddress: certOffset,
});
// recalculate checksum
pe_library_1.calculateCheckSumForPE(newBin, true);
// write Certificate section data
functions_js_1.copyBuffer(newBin, certOffset, certBin, 0, certBin.byteLength);
return newBin;
}));
}
exports.generateExecutableWithSign = generateExecutableWithSign;

View File

@@ -0,0 +1,3 @@
import AlgorithmIdentifier from './data/AlgorithmIdentifier.js';
export declare function createTimestampRequest(data: ArrayBuffer | ArrayBufferView, algorithmIdentifier: AlgorithmIdentifier): ArrayBufferLike;
export declare function pickSignedDataFromTimestampResponse(data: ArrayBuffer | ArrayBufferView): ArrayBuffer;

View File

@@ -0,0 +1,122 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pickSignedDataFromTimestampResponse = exports.createTimestampRequest = void 0;
var functions_js_1 = require("../util/functions.js");
var certUtil_js_1 = require("./certUtil.js");
var derUtil_js_1 = require("./data/derUtil.js");
var KnownOids_js_1 = require("./data/KnownOids.js");
function createTimestampRequest(data, algorithmIdentifier) {
return new Uint8Array(derUtil_js_1.makeDERSequence(
// version
[0x2, 0x1, 0x1]
// messageImprint
.concat(derUtil_js_1.makeDERSequence(algorithmIdentifier
.toDER()
.concat(derUtil_js_1.makeDEROctetString(certUtil_js_1.toUint8Array(data)))))
// certReq
.concat([0x01, 0x01, 0xff]))).buffer;
}
exports.createTimestampRequest = createTimestampRequest;
function pickSignedDataFromTimestampResponse(data) {
var _a, _b, _c, _d, _e, _f;
var ub = certUtil_js_1.toUint8Array(data);
if (ub.length < 2 || ub[0] !== 0x30) {
throw new Error('Invalid or unexpected timestamp response');
}
var len;
var offset;
_a = certUtil_js_1.calculateDERLength(ub, 1), len = _a[0], offset = _a[1];
if (len > ub.length - offset) {
throw new Error('Invalid or unexpected timestamp response (insufficient buffer)');
}
var dataLast = offset + len;
// status PKIStatusInfo
if (ub[offset] !== 0x30) {
throw new Error('Invalid or unexpected timestamp response (no PKIStatusInfo)');
}
_b = certUtil_js_1.calculateDERLength(ub, offset + 1), len = _b[0], offset = _b[1];
if (offset >= dataLast) {
throw new Error('Invalid or unexpected timestamp response (invalid length for PKIStatusInfo)');
}
var timeStampTokenOffset = offset + len;
// PKIStatusInfo.status
if (ub[offset] !== 0x2 || ub[offset + 1] !== 0x1) {
throw new Error('Invalid or unexpected timestamp response (invalid PKIStatusInfo.status)');
}
var status = ub[offset + 2];
switch (status) {
case 0: // granted
case 1: // grantedWithMods
break;
case 2: // rejection
case 3: // waiting
case 4: // revocationWarning
case 5: /* revocationNotification */ {
var msg = "Timestamp response has error status " + status;
// PKIStatusInfo.statusString
if (offset + 3 < timeStampTokenOffset && ub[offset + 3] === 0x30) {
_c = certUtil_js_1.calculateDERLength(ub, offset + 4), len = _c[0], offset = _c[1];
if (offset + len <= timeStampTokenOffset &&
ub[offset] === 0xc) {
_d = certUtil_js_1.calculateDERLength(ub, offset + 1), len = _d[0], offset = _d[1];
if (offset + len <= timeStampTokenOffset) {
var statusString =
// pick UTF8String body
[].slice
.call(ub, offset, offset + len)
// map 0x20<=x<=0x7e values to chars, and other values to '%xx' to be parsed by decodeURIComponent
.map(function (val) {
if (val >= 0x20 && val <= 0x7e) {
return String.fromCharCode(val);
}
else {
var s = val.toString(16);
if (s.length === 1) {
s = '0' + s;
}
return '%' + s;
}
})
.join('');
msg += ', text = ' + decodeURIComponent(statusString);
}
}
}
throw new Error(msg);
}
default:
throw new Error("Unexpected PKIStatusInfo.status: " + (status !== null && status !== void 0 ? status : '(unknown)'));
}
// TimeStampToken ::= ContentInfo
if (timeStampTokenOffset + 1 >= dataLast ||
ub[timeStampTokenOffset] !== 0x30) {
throw new Error('Invalid or unexpected timestamp response (no TimeStampToken)');
}
_e = certUtil_js_1.calculateDERLength(ub, timeStampTokenOffset + 1), len = _e[0], offset = _e[1];
if (offset + len > dataLast) {
throw new Error('Invalid or unexpected timestamp response (insufficient data for TimeStampToken)');
}
// ContentInfo.contentType
var signedDataOid = KnownOids_js_1.OID_SIGNED_DATA.toDER();
if (ub[offset] !== 0x6) {
throw new Error('Invalid or unexpected timestamp response (no contentType in TimeStampToken)');
}
for (var i = 0; i < signedDataOid.length; ++i) {
if (ub[offset + i] !== signedDataOid[i]) {
throw new Error('Invalid or unexpected timestamp response (unexpected TimeStampToken.contentType octet)');
}
}
// ContentInfo.content
offset += signedDataOid.length;
// [0] IMPLICIT
if (ub[offset] !== 0xa0) {
throw new Error('Invalid or unexpected timestamp response (no content in TimeStampToken)');
}
_f = certUtil_js_1.calculateDERLength(ub, offset + 1), len = _f[0], offset = _f[1];
if (offset + len > dataLast) {
throw new Error('Invalid or unexpected timestamp response (invalid length for TimeStampToken.content)');
}
// return content data (=== SignedData)
return functions_js_1.allocatePartialBinary(ub, offset, len);
}
exports.pickSignedDataFromTimestampResponse = pickSignedDataFromTimestampResponse;