|
1 | 1 | import Random from './Random.js' |
2 | 2 | import { sha256 } from './Hash.js' |
| 3 | +import { toArray, toHex } from './utils.js' |
3 | 4 |
|
4 | 5 | export type P256Point = { x: bigint, y: bigint } | null |
5 | 6 |
|
@@ -203,7 +204,7 @@ export default class Secp256r1 { |
203 | 204 | private randomScalar (): bigint { |
204 | 205 | while (true) { |
205 | 206 | const bytes = Random(32) |
206 | | - const k = BigInt('0x' + Buffer.from(bytes).toString('hex')) |
| 207 | + const k = BigInt('0x' + toHex(bytes)) |
207 | 208 | if (k > 0n && k < this.n) return k |
208 | 209 | } |
209 | 210 | } |
@@ -284,21 +285,21 @@ export default class Secp256r1 { |
284 | 285 | } |
285 | 286 |
|
286 | 287 | private messageToBigInt (message: ByteSource, prehashed: boolean): bigint { |
287 | | - const bytes = this.toBuffer(message) |
288 | | - const digest = prehashed ? bytes : Buffer.from(sha256(bytes)) |
289 | | - const hex = digest.toString('hex') |
| 288 | + const bytes = this.toBytes(message) |
| 289 | + const digest = prehashed ? bytes : new Uint8Array(sha256(bytes)) |
| 290 | + const hex = toHex(Array.from(digest)) |
290 | 291 | return BigInt('0x' + hex) % this.n |
291 | 292 | } |
292 | 293 |
|
293 | | - private toBuffer (data: ByteSource): Buffer { |
| 294 | + private toBytes (data: ByteSource): Uint8Array { |
294 | 295 | if (typeof data === 'string') { |
295 | | - if (HEX_REGEX.test(data) && data.length % 2 === 0) { |
296 | | - return Buffer.from(data, 'hex') |
297 | | - } |
298 | | - return Buffer.from(data, 'utf8') |
| 296 | + const isHex = HEX_REGEX.test(data) && data.length % 2 === 0 |
| 297 | + return Uint8Array.from(toArray(data, isHex ? 'hex' : 'utf8')) |
| 298 | + } |
| 299 | + if (data instanceof Uint8Array) return data |
| 300 | + if (ArrayBuffer.isView(data)) { |
| 301 | + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength) |
299 | 302 | } |
300 | | - if (data instanceof Uint8Array) return Buffer.from(data) |
301 | | - if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength) |
302 | 303 | throw new Error('Unsupported message format') |
303 | 304 | } |
304 | 305 |
|
|
0 commit comments