|
5 | 5 | */ |
6 | 6 | import { unsafe } from './aes.ts'; |
7 | 7 | import { |
| 8 | + aarray, |
8 | 9 | abytes, |
9 | 10 | anumber, |
10 | 11 | bytesToNumberBE, |
@@ -137,9 +138,9 @@ export function FF1( |
137 | 138 | key: TArg<Uint8Array>, |
138 | 139 | tweak: TArg<Uint8Array> = EMPTY_BUF |
139 | 140 | ): { encrypt(x: number[]): number[]; decrypt(x: number[]): number[] } { |
140 | | - anumber(radix); |
141 | | - abytes(key); |
142 | | - abytes(tweak); |
| 141 | + anumber(radix, 'radix'); |
| 142 | + abytes(key, undefined, 'key'); |
| 143 | + abytes(tweak, undefined, 'tweak'); |
143 | 144 | // This borrows caller key/tweak buffers by reference through the bound closure; mutating them |
144 | 145 | // after construction changes later encrypt/decrypt outputs. |
145 | 146 | const PQ = getRound.bind(null, radix, key, tweak); |
@@ -174,7 +175,7 @@ export function FF1( |
174 | 175 | // Binary wrapper uses little-endian bit order within each byte so bit 0 stays |
175 | 176 | // in the first numeral slot for this library-defined byte-array surface. |
176 | 177 | const binLE = { |
177 | | - encode(bytes: TArg<Uint8Array>): number[] { |
| 178 | + encode(bytes: TArg<Uint8Array> | number[]): number[] { |
178 | 179 | const x = []; |
179 | 180 | for (let i = 0; i < bytes.length; i++) { |
180 | 181 | for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1) x.push(tmp & 1); |
@@ -214,9 +215,27 @@ export function BinaryFF1( |
214 | 215 | ): TRet<Cipher> { |
215 | 216 | const ff1 = FF1(2, key, tweak); |
216 | 217 | return { |
217 | | - encrypt: (x: TArg<Uint8Array>): TRet<Uint8Array> => |
218 | | - binLE.decode(ff1.encrypt(binLE.encode(x))) as TRet<Uint8Array>, |
219 | | - decrypt: (x: TArg<Uint8Array>): TRet<Uint8Array> => |
220 | | - binLE.decode(ff1.decrypt(binLE.encode(x))) as TRet<Uint8Array>, |
| 218 | + encrypt: (x: TArg<Uint8Array> | number[]): TRet<Uint8Array> => { |
| 219 | + if (Array.isArray(x)) { |
| 220 | + aarray<number>(x, 'x', (elm, title) => { |
| 221 | + anumber(elm, title); |
| 222 | + if (elm > 255) throw new RangeError(`"${title}" expected byte`); |
| 223 | + }); |
| 224 | + } else { |
| 225 | + x = abytes(x, undefined, 'x'); |
| 226 | + } |
| 227 | + return binLE.decode(ff1.encrypt(binLE.encode(x))) as TRet<Uint8Array>; |
| 228 | + }, |
| 229 | + decrypt: (x: TArg<Uint8Array> | number[]): TRet<Uint8Array> => { |
| 230 | + if (Array.isArray(x)) { |
| 231 | + aarray<number>(x, 'x', (elm, title) => { |
| 232 | + anumber(elm, title); |
| 233 | + if (elm > 255) throw new RangeError(`"${title}" expected byte`); |
| 234 | + }); |
| 235 | + } else { |
| 236 | + x = abytes(x, undefined, 'x'); |
| 237 | + } |
| 238 | + return binLE.decode(ff1.decrypt(binLE.encode(x))) as TRet<Uint8Array>; |
| 239 | + }, |
221 | 240 | } as TRet<Cipher>; |
222 | 241 | } |
0 commit comments