diff --git a/native/backup/conversion-utils.js b/native/backup/conversion-utils.js --- a/native/backup/conversion-utils.js +++ b/native/backup/conversion-utils.js @@ -10,4 +10,10 @@ 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 --- a/native/backup/encryption.js +++ b/native/backup/encryption.js @@ -1,7 +1,12 @@ // @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(); @@ -13,4 +18,17 @@ 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 };