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).
54 lines (53 loc) • 1.71 kB
JavaScript
// src/index.ts
import { twofish as createTwofish } from "twofish";
var twofish = createTwofish();
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);
}
export {
decrypt64,
encrypt64
};