50 lines
1.5 KiB
TypeScript
50 lines
1.5 KiB
TypeScript
import { PlaintextBlock} from './'
|
|
|
|
export const preprocessPlaintextHex = (hexPlaintext: string): PlaintextBlock[] => {
|
|
/**
|
|
* @param {string} hexPlaintext - The plaintext to encrypt, as a hexadecimal string.
|
|
* @returns {PlaintextBlock[]} Blocks of 128 bits representing the plaintext. Each block is a 4x4 column-major matrix.
|
|
*/
|
|
const blockSize = 16 // 128 bits = 16 bytes
|
|
|
|
// Convert the hex string into a byte array, where each pair of hex digits is a byte
|
|
const byteArray = new Uint8Array(hexPlaintext.match(/.{1,2}/g)!.map(byte => parseInt(byte, 16)))
|
|
|
|
// Loop through the byteArray and split it into 128-bit blocks
|
|
const blocks: Uint8Array[] = []
|
|
for (let i = 0;i < byteArray.length;i += blockSize) {
|
|
const block = byteArray.slice(i, i + blockSize)
|
|
|
|
if (block.length < blockSize) {
|
|
// Pad the block with zeroes
|
|
const paddedBlock = new Uint8Array(blockSize)
|
|
paddedBlock.set(block)
|
|
blocks.push(paddedBlock)
|
|
} else {
|
|
blocks.push(block)
|
|
}
|
|
}
|
|
|
|
const plaintextBlocks: number[][][] = blocks.map(block => {
|
|
// Block is a 128-bit array containing 16 8-bit integers.
|
|
|
|
const matrix: number[][] = [
|
|
[0, 0, 0, 0],
|
|
[0, 0, 0, 0],
|
|
[0, 0, 0, 0],
|
|
[0, 0, 0, 0],
|
|
]
|
|
|
|
// Fill the matrix in column-major order, i.e., top-to-bottom + left-to-right
|
|
for (let i = 0;i < blockSize;i++) {
|
|
const row = i % 4
|
|
const col = Math.floor(i / 4)
|
|
matrix[row][col] = block[i]
|
|
}
|
|
|
|
return matrix
|
|
})
|
|
|
|
return plaintextBlocks
|
|
}
|