Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does not work with Node.js Web Crypto and UUID #11

Closed
bkiac opened this issue Jan 2, 2023 · 1 comment
Closed

Does not work with Node.js Web Crypto and UUID #11

bkiac opened this issue Jan 2, 2023 · 1 comment

Comments

@bkiac
Copy link

bkiac commented Jan 2, 2023

Maybe I'm doing something wrong but I can't get a UUID -> encrypt -> encode -> decode -> decrypt -> UUID flow working.

import crypto from 'crypto'
import {Encoder, Encrypter} from 'objectid64'

global.crypto = crypto.webcrypto

const encoder = new Encoder()

const key = await Encrypter.generateKey()
const encrypter = new Encrypter(key)

const uuid = crypto.randomUUID()
console.log(uuid) // 4874c42f-61e3-42c8-9a39-4007a81737e7

const binUuid = encoder.toBinUUID(uuid)
const encrypted = await encrypter.fromUUID(binUuid)
const encoded = encoder.fromBinUUID(encrypted)
console.log(encoded) // MxbKSQB-fuDtqUJayvuVCO

const decoded = encoder.toBinUUID(encoded)
const decrypted = await encrypter.toUUID(decoded)
const uuid2 = encoder.fromBinUUID(decrypted)
console.log(uuid2) // 4874c42f-61e3-42c8-9C3, uuid is not recovered in full

console.log(uuid === uuid2) // false

Node.js version: 16.17.1
objectid64 version: 3.2.1

@bkiac
Copy link
Author

bkiac commented Jan 2, 2023

The bug was in my code, it's unrelated to this package (or the Node.js Web Crypto implementation), this is the working code:

import crypto from 'crypto'
import {Encoder, Encrypter} from 'objectid64'

global.crypto = crypto.webcrypto

const uuidStringToBinary = (enc: Encoder, uuid: string): Uint8Array =>
  enc.toBinUUID(enc.fromUUID(uuid))
const uuidBinaryToString = (enc: Encoder, uuid: Uint8Array): string =>
  enc.toUUID(enc.fromBinUUID(uuid))

const encoder = new Encoder()

const key = await Encrypter.generateKey()
const encrypter = new Encrypter(key)

const uuid = crypto.randomUUID()

const binUuid = uuidStringToBinary(encoder, uuid)
const encrypted = await encrypter.fromUUID(binUuid)
const encoded = encoder.fromBinUUID(encrypted)

const decoded = encoder.toBinUUID(encoded)
const decrypted = await encrypter.toUUID(decoded)
const uuid2 = uuidBinaryToString(encoder, decrypted)

console.log(uuid === uuid2) // true

@bkiac bkiac closed this as completed Jan 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant