Skip to content

Commit 20146af

Browse files
committed
No more buffer
1 parent 17af75b commit 20146af

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

src/primitives/Secp256r1.ts

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import Random from './Random.js'
22
import { sha256 } from './Hash.js'
3+
import { toArray, toHex } from './utils.js'
34

45
export type P256Point = { x: bigint, y: bigint } | null
56

@@ -203,7 +204,7 @@ export default class Secp256r1 {
203204
private randomScalar (): bigint {
204205
while (true) {
205206
const bytes = Random(32)
206-
const k = BigInt('0x' + Buffer.from(bytes).toString('hex'))
207+
const k = BigInt('0x' + toHex(bytes))
207208
if (k > 0n && k < this.n) return k
208209
}
209210
}
@@ -284,21 +285,21 @@ export default class Secp256r1 {
284285
}
285286

286287
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))
290291
return BigInt('0x' + hex) % this.n
291292
}
292293

293-
private toBuffer (data: ByteSource): Buffer {
294+
private toBytes (data: ByteSource): Uint8Array {
294295
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)
299302
}
300-
if (data instanceof Uint8Array) return Buffer.from(data)
301-
if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength)
302303
throw new Error('Unsupported message format')
303304
}
304305

0 commit comments

Comments
 (0)