import Sodium from 'react-native-sodium'; // @ts-ignore import CryptoJS, { AES } from 'react-native-crypto-js'; import Base64 from './base64'; const CRYPTO_BOX_NONCEBYTES = 24; export class EncryptionManager { static async generateCryptoBox(lib: any = Sodium) { return await lib.crypto_box_keypair(); } static encryptAES(message: string, key: string): string { return AES.encrypt(message, key).toString(); } static decryptAES(cipher: string, key: string) { const bytes = AES.decrypt(cipher, key); return bytes.toString(CryptoJS.enc.Utf8); } static async encryptSodium( message: string, publicKey: string, privateKey: string, lib: any = Sodium, ) { const newMessage = EncryptionManager.Base64Encode(message); const nonce = await lib.randombytes_buf(CRYPTO_BOX_NONCEBYTES); const cipher = await lib.crypto_box_easy(newMessage, nonce, publicKey, privateKey); return { cipher, nonce }; } static async decryptSodium( cipher: string, nonce: string, publicKey: string, privateKey: string, lib: any = Sodium, ) { try { const encoded = await lib.crypto_box_open_easy(cipher, nonce, publicKey, privateKey); return EncryptionManager.Base64Decode(encoded); } catch (e) { console.log('error encode', e); } } static Base64Encode(str: string) { return Base64.btoa( encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => // @ts-ignore String.fromCharCode('0x' + p1), ), ); } static Base64Decode(str: string) { return decodeURIComponent( Base64.atob(str) .split('') .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)) .join(''), ); } }