gx-twofish64
Version:
A library for encrypting and decrypting data using the Twofish algorithm and Base64 encoding. Based on the Genexus implementation (Encrypt64 and Decrypt64).
80 lines (78 loc) • 2.75 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
decrypt64: () => decrypt64,
encrypt64: () => encrypt64
});
module.exports = __toCommonJS(index_exports);
var import_twofish = require("twofish");
var twofish = (0, import_twofish.twofish)();
function padToBlockSize(text) {
const blockSize = 16;
const encoder = new TextEncoder();
const bytes = encoder.encode(text);
const paddingNeeded = blockSize - bytes.length % blockSize;
const paddedBytes = new Uint8Array(bytes.length + paddingNeeded);
paddedBytes.set(bytes);
for (let i = bytes.length; i < paddedBytes.length; i++) {
paddedBytes[i] = 32;
}
return paddedBytes;
}
function unpadText(buffer) {
const decoder = new TextDecoder("utf-8");
return decoder.decode(buffer).trimEnd();
}
function hexToBytes(hex) {
if (hex.length % 2 !== 0) throw new Error("Clave inv\xE1lida");
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return bytes;
}
function encrypt64(text, hexKey) {
const key = hexToBytes(hexKey);
const input = padToBlockSize(text);
const encrypted = new Uint8Array(input.length);
for (let i = 0; i < input.length; i += 16) {
const block = input.subarray(i, i + 16);
const encryptedBlock = twofish.encrypt(key, block);
encrypted.set(encryptedBlock, i);
}
return Buffer.from(encrypted).toString("base64");
}
function decrypt64(base64Text, hexKey) {
const key = hexToBytes(hexKey);
const input = Buffer.from(base64Text, "base64");
const decrypted = new Uint8Array(input.length);
for (let i = 0; i < input.length; i += 16) {
const block = input.subarray(i, i + 16);
const decryptedBlock = twofish.decrypt(key, block);
decrypted.set(decryptedBlock, i);
}
return unpadText(decrypted);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
decrypt64,
encrypt64
});