diff --git a/native/backup/conversion-utils.js b/native/backup/conversion-utils.js index da8826e1b..df8e33355 100644 --- a/native/backup/conversion-utils.js +++ b/native/backup/conversion-utils.js @@ -1,13 +1,19 @@ // @flow import { commUtilsModule } from '../native-modules.js'; import { arrayBufferFromBlob } from '../utils/blob-utils-module.js'; function getBackupBytesFromBlob(blob: Blob): Uint8Array { const buffer = arrayBufferFromBlob(blob); const str = commUtilsModule.decodeUTF8ArrayBufferToString(buffer); const decodedBuffer = commUtilsModule.base64DecodeBuffer(str); return new Uint8Array(decodedBuffer); } -export { getBackupBytesFromBlob }; +function convertObjToBytes(obj: T): Uint8Array { + const objStr = JSON.stringify(obj); + const objBuffer = commUtilsModule.encodeStringToUTF8ArrayBuffer(objStr ?? ''); + return new Uint8Array(objBuffer); +} + +export { getBackupBytesFromBlob, convertObjToBytes }; diff --git a/native/backup/encryption.js b/native/backup/encryption.js index 87710c23e..46d3abd6d 100644 --- a/native/backup/encryption.js +++ b/native/backup/encryption.js @@ -1,16 +1,34 @@ // @flow +import { hexToUintArray } from 'lib/media/data-utils.js'; +import type { Backup, BackupEncrypted } from 'lib/types/backup-types.js'; + +import { convertObjToBytes } from './conversion-utils.js'; import { fetchNativeKeychainCredentials } from '../account/native-credentials.js'; import { commCoreModule } from '../native-modules.js'; +import * as AES from '../utils/aes-crypto-module.js'; async function getBackupKey(backupID: string): Promise { const nativeCredentials = await fetchNativeKeychainCredentials(); if (!nativeCredentials) { throw new Error('Native credentials are missing'); } const { password } = nativeCredentials; const backupKey = await commCoreModule.computeBackupKey(password, backupID); return new Uint8Array(backupKey); } -export { getBackupKey }; +async function encryptBackup(backup: Backup): Promise { + const { backupID, userKeys, userData } = backup; + const userKeysBytes = convertObjToBytes(userKeys); + const backupKey = await getBackupKey(backupID); + const ct1 = AES.encrypt(backupKey, userKeysBytes); + + const userDataBytes = convertObjToBytes(userData); + const backupDataKey = hexToUintArray(userKeys.backupDataKey); + const ct2 = AES.encrypt(backupDataKey, userDataBytes); + + return { backupID, userKeys: ct1, userData: ct2 }; +} + +export { getBackupKey, encryptBackup };