diff --git a/src/utils/crypto.ts b/src/utils/crypto.ts index c974c29..dc55c47 100644 --- a/src/utils/crypto.ts +++ b/src/utils/crypto.ts @@ -1,4 +1,9 @@ -import { hexToString, stringToHex } from '.' +import { + hexStringToUint8Array, + hexToString, + stringToHex, + uint8ArrayToHexString +} from '.' const ENCRYPTION_ALGO_NAME = 'AES-GCM' @@ -14,7 +19,7 @@ export const generateEncryptionKey = async () => { const jsonString = JSON.stringify(key) const hexKey = stringToHex(jsonString) - const iv = new TextDecoder().decode( + const iv = uint8ArrayToHexString( window.crypto.getRandomValues(new Uint8Array(16)) ) @@ -25,7 +30,7 @@ export const importKey = async (key: string) => { const splittedKey = key.split('?iv=') const keyString = hexToString(splittedKey[0]) const jsonWebKey = JSON.parse(keyString) - const iv = new TextEncoder().encode(splittedKey[1]) + const iv = hexStringToUint8Array(splittedKey[1]) const cryptoKey = await window.crypto.subtle.importKey( 'jwk', diff --git a/src/utils/string.ts b/src/utils/string.ts index e0e8fea..c2007b5 100644 --- a/src/utils/string.ts +++ b/src/utils/string.ts @@ -37,3 +37,25 @@ export const hexToString = (hex: string) => { // Join the resulting characters into a single string return chars.join('') } + +// Function to convert a Uint8Array to a hexadecimal string +export const uint8ArrayToHexString = (uint8Array: Uint8Array) => { + // Convert each byte in the Uint8Array to a hexadecimal string, + // pad it with leading zeros if necessary, and join the results + return Array.from(uint8Array) + .map((byte) => byte.toString(16).padStart(2, '0')) // Convert byte to hexadecimal string + .join('') // Join all hexadecimal strings +} + +// Function to convert a hexadecimal string to a Uint8Array +export const hexStringToUint8Array = (hexString: string) => { + // Create a new Uint8Array with half the length of the hex string + const uint8Array = new Uint8Array(hexString.length / 2) + // Iterate over pairs of characters in the hex string + for (let i = 0; i < hexString.length; i += 2) { + // Parse the pair of characters as a hexadecimal value and store it in the Uint8Array + uint8Array[i / 2] = parseInt(hexString.substr(i, 2), 16) + } + // Return the resulting Uint8Array + return uint8Array +}