Changeset View
Changeset View
Standalone View
Standalone View
lib/utils/pkcs7-padding.js
- This file was added.
// @flow | |||||
import invariant from 'invariant'; | |||||
/** | |||||
* PKCS#7 padding function for `Uint8Array` data. | |||||
* | |||||
* @param {Uint8Array} data - The data to be padded. | |||||
* @param {number} blockSizeBytes - The block size in bytes. | |||||
* @returns {Uint8Array} The padded data as a new Uint8Array. | |||||
*/ | |||||
export function pkcs7pad(data: Uint8Array, blockSizeBytes: number): Uint8Array { | |||||
ashoat: Nit: we don't use inline exports in the codebase **except** for Flow types and for files in… | |||||
bartekAuthorUnsubmitted Done Inline ActionsSure, will do bartek: Sure, will do | |||||
invariant(blockSizeBytes > 0, 'block size must be positive'); | |||||
invariant(blockSizeBytes < 256, 'block size must be less than 256'); | |||||
atulUnsubmitted Not Done Inline ActionsWould it maybe make more sense to throw exceptions instead of using invariant? CC @ashoat atul: Would it maybe make more sense to throw exceptions instead of using `invariant`?
CC @ashoat | |||||
ashoatUnsubmitted Not Done Inline ActionsI think invariant is good for "programmer error" type scenarios like this but I don't feel strongly. Ultimately invariant just throws an exception so it doesn't really matter ashoat: I think `invariant` is good for "programmer error" type scenarios like this but I don't feel… | |||||
bartekAuthorUnsubmitted Done Inline ActionsI'd stick to invariant because it looks clean. bartek: I'd stick to `invariant` because it looks clean. | |||||
const padding = blockSizeBytes - (data.length % blockSizeBytes); | |||||
const padded = new Uint8Array(data.length + padding); | |||||
padded.set(data); | |||||
padded.fill(padding, data.length); | |||||
return padded; | |||||
} | |||||
/** | |||||
* PKCS#7 unpadding function for `Uint8Array` data. | |||||
* | |||||
* @param {Uint8Array} data - The padded data to be unpadded. | |||||
* @returns {Uint8Array} The unpadded data as a new Uint8Array. | |||||
* @throws {Error} If the padding is invalid. | |||||
*/ | |||||
export function pkcs7unpad(data: Uint8Array): Uint8Array { | |||||
const padding = data[data.length - 1]; | |||||
invariant(padding > 0, 'padding must be positive'); | |||||
invariant(data.length >= padding, 'data length must be at least padding'); | |||||
invariant( | |||||
data.subarray(data.length - padding).every(x => x === padding), | |||||
'invalid padding', | |||||
); | |||||
const unpadded = data.subarray(0, data.length - padding); | |||||
return unpadded; | |||||
} |
Nit: we don't use inline exports in the codebase except for Flow types and for files in lib/types (and other "types" files like that)
Can you move these to be a single export declaration at the bottom of the file?