@heliomarpm/helpers
Version:
A library with many useful features
202 lines (201 loc) • 8.47 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cryptor = void 0;
const crypto_1 = require("crypto");
const util_1 = require("util");
const randomBytesAsync = (0, util_1.promisify)(crypto_1.randomBytes);
function validateInput(inputText, inputName = '') {
if (typeof inputText !== 'string' || inputText.trim() === '') {
const name = (inputName || '').trim() === '' ? '' : `${(inputName || '').trim()} `;
throw new Error(`Input ${name}must not be empty or whitespace.`);
}
}
exports.Cryptor = {
/**
* Generates a SHA256 hash of the given text.
*
* @param text - The input text to hash.
* @returns A Promise that resolves to a hexadecimal string representing the SHA256 hash of the text.
*
* @example
* ```js
* const hashedPass = await Cryptor.hash('myPassword');
* console.log(hashedPass); // e.g., "9a0b...7f"
* ```
*/
hash(text) {
return __awaiter(this, void 0, void 0, function* () {
validateInput(text, 'text');
const hash = (0, crypto_1.createHash)('sha256');
hash.update(text);
return hash.digest('hex');
});
},
/**
* Compares a plain text string to a hashed string to determine if they are equivalent.
*
* @param text - The plaintext string to hash and compare.
* @param hash - The hash string to compare against the hashed text.
* @returns A Promise that resolves to `true` if the hashed text matches the given hash, `false` otherwise.
*
* @example
* ```js
* const isMatch = await Cryptor.compareHash("myPassword", hashedPass);
* console.log(isMatch); // Outputs true if 'example' hashes to 'hash', otherwise false
* ```
*/
compareHash(text, hash) {
return __awaiter(this, void 0, void 0, function* () {
validateInput(text, 'text');
validateInput(hash, 'hash');
const textHash = yield this.hash(text);
return textHash === hash;
});
},
/**
* Generates a cryptographically secure random salt value as a hexadecimal string.
*
* @param length - The length of the salt in bytes. Defaults to 16.
* @returns A Promise that resolves to a hexadecimal string representing the generated salt.
*
* @example
* ```js
* const salt = await Cryptor.generateSalt();
* console.log(salt); // Outputs a random hexadecimal string of length 16.
* ```
*/
generateSalt() {
return __awaiter(this, arguments, void 0, function* (length = 16) {
if (length <= 0) {
throw new Error('Salt length must be greater than 0.');
}
const salt = yield randomBytesAsync(length);
return salt.toString('hex');
});
},
/**
* Generates a new 2048-bit RSA key pair and returns it as an object with `publicKey` and `privateKey` properties.
*
* @returns A Promise that resolves to an object with `publicKey` and `privateKey` properties, both as PEM-formatted strings.
*
* @example
* ```js
* const keyPair = await Cryptor.generateKeyPair();
* console.log(keyPair.publicKey); // Outputs the PEM-formatted public key
* console.log(keyPair.privateKey); // Outputs the PEM-formatted private key
* ```
*/
generateKeyPair() {
return __awaiter(this, void 0, void 0, function* () {
const { generateKeyPairSync } = yield Promise.resolve().then(() => __importStar(require('crypto')));
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
return { publicKey, privateKey };
});
},
/**
* Generates a digital signature for the given data using the private key.
*
* @param data - The data to sign.
* @param privateKey - The PEM-formatted private key to use for signing.
* @returns A Promise that resolves to the generated signature as a hexadecimal string.
*
* @example
* ```js
* const payload = JSON.stringify({id: 123, nome: "Heliomar", timestamp: Date.now()})
* const { publicKey, privateKey } = await Cryptor.generateSalt();
*
* const signature = await Cryptor.sign(payload, privateKey);
* console.log(Buffer.from(signature).toString("base64"));
*
* const isValid = await Cryptor.verify(payload, signature, publicKey);
* console.log(isValid); // Outputs true
* ```
*/
sign(data, privateKey) {
return __awaiter(this, void 0, void 0, function* () {
validateInput(data, 'data');
validateInput(privateKey, 'privateKey');
const { createSign } = yield Promise.resolve().then(() => __importStar(require('crypto')));
const signer = createSign('SHA256');
signer.update(data);
return signer.sign(privateKey, 'hex');
});
},
/**
* Verifies the digital signature of the given data using the public key.
*
* @param data - The data whose signature needs to be verified.
* @param signature - The hexadecimal string representing the signature to verify.
* @param publicKey - The PEM-formatted public key to use for verification.
* @returns A Promise that resolves to `true` if the signature is valid, `false` otherwise.
*
* @example
* ```js
* const isValid = await Cryptor.verify('Hello, world!', signature, publicKey);
* console.log(isValid); // Outputs true if the signature is valid, otherwise false
* ```
*/
verify(data, signature, publicKey) {
return __awaiter(this, void 0, void 0, function* () {
validateInput(data, 'data');
validateInput(signature, 'signature');
validateInput(publicKey, 'publicKey');
const { createVerify } = yield Promise.resolve().then(() => __importStar(require('crypto')));
const verifier = createVerify('SHA256');
verifier.update(data);
return verifier.verify(publicKey, signature, 'hex');
});
}
};