### Start Example App Metro Server Source: https://github.com/margelo/react-native-quick-crypto/blob/main/CONTRIBUTING.md Starts the Metro server for the example application. ```sh bun example ``` -------------------------------- ### Run Example App Source: https://github.com/margelo/react-native-quick-crypto/blob/main/CONTRIBUTING.md Start the example application on iOS or Android. ```sh bun ios # or android ``` -------------------------------- ### Start Metro Bundler Source: https://github.com/margelo/react-native-quick-crypto/blob/main/CONTRIBUTING.md Start the Metro bundler/packager for the example app. ```sh bun start ``` -------------------------------- ### Run Development Server Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/README.md Use these commands to start the development server for the project. Ensure you have npm, pnpm, or yarn installed. ```bash npm run dev # or pnpm dev # or yarn dev ``` -------------------------------- ### Install crypto and Buffer polyfills Source: https://github.com/margelo/react-native-quick-crypto/blob/main/README.md Installs the crypto and Buffer polyfills by calling the install function as early as possible in your application's entry point. ```typescript import { install } from 'react-native-quick-crypto'; install(); ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/margelo/react-native-quick-crypto/blob/main/CONTRIBUTING.md Run this command in the root directory to install all necessary project dependencies. ```sh bun i ``` -------------------------------- ### Bootstrap Project Dependencies Source: https://github.com/margelo/react-native-quick-crypto/blob/main/CONTRIBUTING.md Sets up the project by installing all dependencies and pods. ```sh bun bootstrap ``` -------------------------------- ### Install React Native Quick Crypto Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/guides/migration.mdx Install RNQC and its dependencies, then run `pod install` for iOS. This step replaces the legacy libraries with the new, faster implementation. ```bash npm install react-native-quick-crypto react-native-nitro-modules cd ios && pod install ``` -------------------------------- ### Install Dependencies for Secure Storage Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/guides/secure-storage.mdx Installs the necessary libraries for MMKV storage and keychain access. ```bash npm install react-native-mmkv react-native-keychain ``` -------------------------------- ### Install React Native Quick Crypto Source: https://context7.com/margelo/react-native-quick-crypto/llms.txt Install the package and its peer dependencies, then rebuild the native binary. For Expo, use `npx expo install` and configure `app.json` for optional sodium support. ```bash # React Native npm install react-native-quick-crypto react-native-nitro-modules react-native-quick-base64 cd ios && pod install # Expo npx expo install react-native-quick-crypto # app.json — optional sodium support # { "expo": { "plugins": [["react-native-quick-crypto", { "sodiumEnabled": true }]] } } npx expo prebuild && npx expo run:ios ``` -------------------------------- ### Install react-native-quick-crypto for Expo Source: https://github.com/margelo/react-native-quick-crypto/blob/main/README.md Installs the library for Expo and runs prebuild to prepare native modules. ```sh expo install react-native-quick-crypto expo prebuild ``` -------------------------------- ### Import install function Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/install.mdx Import the `install` function at the very top of your application's entry file. ```typescript import { install } from 'react-native-quick-crypto'; ``` -------------------------------- ### Start Metro Server Source: https://github.com/margelo/react-native-quick-crypto/blob/main/example/README.md Starts the Metro bundler for React Native. Use npm or Yarn to execute. ```bash # using npm npm start # OR using Yarn yarn start ``` -------------------------------- ### Install react-native-quick-crypto for React Native Source: https://github.com/margelo/react-native-quick-crypto/blob/main/README.md Installs the necessary packages for React Native and runs pod install for iOS dependencies. ```sh bun add react-native-quick-crypto react-native-nitro-modules react-native-quick-base64 cd ios && pod install ``` -------------------------------- ### Install Dependencies (Expo) Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/introduction/complete-setup.mdx Install the package for Expo projects using the Expo CLI. ```bash npx expo install react-native-quick-crypto ``` -------------------------------- ### Install babel-plugin-module-resolver Source: https://github.com/margelo/react-native-quick-crypto/blob/main/README.md Install the necessary babel plugin for module resolution. ```sh yarn add --dev babel-plugin-module-resolver ``` -------------------------------- ### Install Pods (iOS) Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/introduction/complete-setup.mdx Navigate to the iOS directory and install CocoaPods for React Native CLI projects. ```bash cd ios && pod install ``` -------------------------------- ### Execute install function Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/install.mdx Call `install()` before any other imports that might depend on crypto. This modifies global objects like `Buffer` and `crypto`. ```typescript install(); // Now import your App import App from './src/App'; ``` -------------------------------- ### Verify global crypto and Buffer usage Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/install.mdx After calling `install()`, you can use global `crypto` and `Buffer` without explicit imports. This demonstrates the successful polyfilling. ```typescript // Anywhere in your app const id = crypto.randomUUID(); const buf = Buffer.from('hello'); ``` -------------------------------- ### Basic Verification Setup Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/signing.mdx Initializes a `Verify` object with a specified algorithm and updates it with the data to be verified. The `update` method must be called with the exact same data and in the same order as used during signing. ```ts import { createVerify } from 'react-native-quick-crypto'; const verify = createVerify('SHA256'); verify.update('some data to sign'); verify.end(); const isValid = verify.verify(publicKey, signature); console.log(isValid); // true or false ``` -------------------------------- ### Install Dependencies (React Native CLI) Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/introduction/complete-setup.mdx Install the package and the required react-native-nitro-modules core for React Native CLI projects. ```bash bun add react-native-quick-crypto react-native-nitro-modules ``` -------------------------------- ### Install React Native Quick Crypto Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/introduction/quick-start.mdx Add the necessary dependencies using your preferred package manager. Ensure you include react-native-nitro-modules and react-native-quick-base64 for full functionality. ```bash npm install react-native-quick-crypto react-native-nitro-modules react-native-quick-base64 ``` ```bash yarn add react-native-quick-crypto react-native-nitro-modules react-native-quick-base64 ``` ```bash pnpm add react-native-quick-crypto react-native-nitro-modules react-native-quick-base64 ``` ```bash bun add react-native-quick-crypto react-native-nitro-modules react-native-quick-base64 ``` -------------------------------- ### Example TypeTable Component Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/guides/writing-documentation.mdx Demonstrates how to use the TypeTable component to document parameters for methods. Ensure the 'data' and 'encoding' properties are correctly defined with their types and descriptions. ```tsx import { TypeTable } from 'fumadocs-ui/components/type-table'; ``` -------------------------------- ### Import and Use randomBytes Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/guides/writing-documentation.mdx A basic example of importing and using the randomBytes function from the library. This snippet is suitable for demonstrating simple cryptographic operations. ```typescript import { randomBytes } from 'react-native-quick-crypto'; const buf = randomBytes(32); ``` -------------------------------- ### Pre-generate Diffie-Hellman Instances Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/diffie-hellman.mdx For performance, especially if you anticipate needing DH instances, pre-generate them in the background. This example uses `setTimeout` to defer key generation. ```typescript import { getDiffieHellman } from 'react-native-quick-crypto'; async function prepareSecureSession(): Promise { return new Promise((resolve) => { setTimeout(() => { const dh = getDiffieHellman('modp15'); dh.generateKeys(); resolve(dh); }, 0); }); } const dh = await prepareSecureSession(); ``` -------------------------------- ### Orchestrate Cross-Cutting Audits Source: https://github.com/margelo/react-native-quick-crypto/blob/main/plans/done/security-audit.md Example of launching parallel agents for cross-cutting concerns like dependency and build system reviews. ```bash Launch in parallel: 1. general-purpose (dependency) → Run npm audit, check CVEs, review lockfiles 2. general-purpose (build) → Review .github/workflows/, expo plugin, .npmignore ``` -------------------------------- ### Example Usage of TOTP Generation Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/guides/totp-2fa.mdx Demonstrates how to use the `generateTOTP` function with a sample secret key. Note that in production, the secret should be decoded from Base32. ```typescript // In real apps, decode the Base32 secret from the QR code first! // calculating 'secret' from a string for demo purposes: const secret = Buffer.from('MY_SECRET_KEY', 'utf8'); const code = generateTOTP(secret); console.log(`Your 2FA code is: ${code}`); // "849102" ``` -------------------------------- ### Process Certificate Request Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/certificate.mdx A real-world example demonstrating how to validate a certificate request by verifying its SPKAC signature and extracting the public key and challenge. ```typescript import { Certificate } from 'react-native-quick-crypto'; function processCertificateRequest(spkac: Buffer) { // Verify the SPKAC signature if (!Certificate.verifySpkac(spkac)) { throw new Error('Invalid SPKAC signature'); } // Extract the public key and challenge const publicKey = Certificate.exportPublicKey(spkac); const challenge = Certificate.exportChallenge(spkac); return { publicKey: publicKey.toString(), challenge: challenge.toString() }; } ``` -------------------------------- ### RSA Key Signing Schemes Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/signing.mdx Details the supported signature schemes for RSA keys, including the default RSASSA-PKCS1-v1_5 and the more secure RSA-PSS. Examples show how to specify the padding scheme when signing. ```APIDOC ## RSA Keys ### RSASSA-PKCS1-v1_5 This is the default RSA signature scheme. ```ts // PKCS#1 v1.5 (default) sign.sign(rsaPrivateKey); ``` ### RSA-PSS Probabilistic Signature Scheme, which is more secure than PKCS#1 v1.5. ```ts import { constants } from 'react-native-quick-crypto'; // RSA-PSS (recommended) sign.sign({ key: rsaPrivateKey, padding: constants.RSA_PKCS1_PSS_PADDING }); ``` ``` -------------------------------- ### Basic Signing with Different Output Encodings Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/signing.mdx Demonstrates how to create a signature using a private key and retrieve it as a Buffer, hex string, or base64 string. Ensure the `Sign` object is created with the correct algorithm. ```ts import { createSign } from 'react-native-quick-crypto'; const sign = createSign('SHA256'); sign.update('data to sign'); // As Buffer const signatureBuffer = sign.sign(privateKey); // As hex string const signatureHex = sign.sign(privateKey, 'hex'); // As base64 const signatureB64 = sign.sign(privateKey, 'base64'); ``` -------------------------------- ### install() - Polyfill global.crypto and global.Buffer Source: https://context7.com/margelo/react-native-quick-crypto/llms.txt Injects the RNQC bindings into `global.crypto` and `global.Buffer`. This should be called as early as possible in your application's startup process to ensure libraries that rely on these globals automatically use the native implementation. ```APIDOC ## install() ### Description Injects the RNQC bindings into `global.crypto` and `global.Buffer`. Call this as early as possible (e.g., in `index.js`) so that libraries like `ethers`, `jsonwebtoken`, and `viem` pick up the native implementation automatically. ### Method ```ts import QuickCrypto from 'react-native-quick-crypto'; // Call once at app startup QuickCrypto.install(); // After install(), standard Web Crypto APIs are available globally: const id = crypto.randomUUID(); const bytes = crypto.getRandomValues(new Uint8Array(16)); ``` ``` -------------------------------- ### Get Cipher Algorithm Information Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/utilities.mdx Call `getCipherInfo()` with a cipher name or NID to get detailed information about its properties, such as block size, key length, and IV length. This helps in configuring cryptographic operations correctly. ```typescript import { getCipherInfo } from 'react-native-quick-crypto'; const info = getCipherInfo('aes-256-gcm'); // { // name: 'aes-256-gcm', // nid: 901, // blockSize: 1, // ivLength: 12, // keyLength: 32, // mode: 'gcm' // } ``` -------------------------------- ### Install CocoaPods Dependencies for iOS Source: https://github.com/margelo/react-native-quick-crypto/blob/main/CONTRIBUTING.md Build the CocoaPods dependencies required for iOS development. ```sh pod install ``` -------------------------------- ### Get Supported Hashes Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/utilities.mdx Returns an array of supported hash algorithm names available in the environment. ```typescript import { getHashes } from 'react-native-quick-crypto'; const hashes = getHashes(); // ['sha1', 'sha256', 'sha512', 'sha3-256', 'blake2b512', ...] ``` -------------------------------- ### Get Supported Ciphers Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/utilities.mdx Returns an array of supported cipher algorithm names available in the environment. ```typescript import { getCiphers } from 'react-native-quick-crypto'; const ciphers = getCiphers(); // ['aes-128-cbc', 'aes-128-gcm', 'aes-256-gcm', 'chacha20-poly1305', ...] ``` -------------------------------- ### Multi-Party Document Signing Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/signing.mdx Demonstrates how multiple parties can sign the same document sequentially, with each signature incorporating previous ones. This example shows the creation of a `SignedDocument` class that manages content and signatures, and includes methods for adding signatures and verifying them individually or all at once. ```APIDOC ## Multi-Party Document Signing This example illustrates a scenario where multiple parties sign the same document. A `SignedDocument` class is provided to manage the document content and an array of signatures. Each new signature includes the document content, signer information, timestamp, and all preceding signatures. ### Class: `SignedDocument` #### Constructor - `constructor(content: string)`: Initializes the document with the given content. #### Methods - `addSignature(signerName: string, privateKey: any): void`: - Adds a new signature to the document. - The data signed includes the document content, signer name, timestamp, and all previous signatures. - Uses `createSign('SHA256')` for signing. - `verifySignature(index: number, publicKey: any): boolean`: - Verifies the signature at the specified index using the provided public key. - Reconstructs the data that was originally signed for verification. - Returns `true` if the signature is valid, `false` otherwise. - `verifyAll(publicKeys: Map): boolean`: - Verifies all signatures in the document using a map of signer names to their corresponding public keys. - Returns `true` if all signatures are valid, `false` if any signature fails verification. - `getSignatures(): Signature[]`: - Returns a copy of the current list of signatures. ### Usage Example ```ts import { createSign, createVerify } from 'react-native-quick-crypto'; interface Signature { signer: string; signedAt: number; signature: string; } class SignedDocument { private content: string; private signatures: Signature[] = []; constructor(content: string) { this.content = content; } addSignature(signerName: string, privateKey: any): void { const timestamp = Date.now(); const dataToSign = JSON.stringify({ content: this.content, signer: signerName, signedAt: timestamp, previousSignatures: this.signatures }); const sign = createSign('SHA256'); sign.update(dataToSign); const signature = sign.sign(privateKey, 'base64'); this.signatures.push({ signer: signerName, signedAt: timestamp, signature }); } verifySignature( index: number, publicKey: any ): boolean { if (index >= this.signatures.length) { return false; } const sig = this.signatures[index]; const previousSigs = this.signatures.slice(0, index); const dataToVerify = JSON.stringify({ content: this.content, signer: sig.signer, signedAt: sig.signedAt, previousSignatures: previousSigs }); const verify = createVerify('SHA256'); verify.update(dataToVerify); return verify.verify(publicKey, sig.signature, 'base64'); } verifyAll(publicKeys: Map): boolean { for (let i = 0; i < this.signatures.length; i++) { const sig = this.signatures[i]; const publicKey = publicKeys.get(sig.signer); if (!publicKey || !this.verifySignature(i, publicKey)) { console.log(`Signature ${i} (${sig.signer}) failed verification`); return false; } } return true; } getSignatures(): Signature[] { return [...this.signatures]; } } // Usage const document = new SignedDocument('Contract: Transfer $1M...'); // Alice signs document.addSignature('Alice', alicePrivateKey); // Bob signs document.addSignature('Bob', bobPrivateKey); // Charlie signs document.addSignature('Charlie', charliePrivateKey); // Verify all signatures const publicKeys = new Map([ ['Alice', alicePublicKey], ['Bob', bobPublicKey], ['Charlie', charliePublicKey] ]); const allValid = document.verifyAll(publicKeys); console.log('All signatures valid:', allValid); ``` ``` -------------------------------- ### Get ECDH Private Key Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/ecdh.mdx Retrieve the ECDH private key. This key should be kept secret and never transmitted. ```typescript const privateKey = ecdh.getPrivateKey(); // Buffer ``` -------------------------------- ### Get ECDH Public Key Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/ecdh.mdx Retrieve the ECDH public key in various encodings. The default encoding is a Buffer. ```typescript const ecdh = createECDH('prime256v1'); ecdh.generateKeys(); const publicKey = ecdh.getPublicKey(); // Buffer const publicKeyHex = ecdh.getPublicKey('hex'); // string const publicKeyB64 = ecdh.getPublicKey('base64'); // string ``` -------------------------------- ### JWT Token Implementation Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/signing.mdx A complete example demonstrating JWT creation and verification using RSA keys and SHA256 for signing. This includes key generation, token encoding, signing, and verification logic. ```typescript import { createSign, createVerify, generateKeyPairSync } from 'react-native-quick-crypto'; // Generate keys (do once, save securely) const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048, publicExponent: 0x10001, }); function createJWT(payload: object): string { // Create header const header = { alg: 'RS256', typ: 'JWT' }; // Encode header and payload const encodedHeader = Buffer.from(JSON.stringify(header)) .toString('base64url'); const encodedPayload = Buffer.from(JSON.stringify(payload)) .toString('base64url'); const dataToSign = `${encodedHeader}.${encodedPayload}`; // Sign const sign = createSign('SHA256'); sign.update(dataToSign); const signature = sign.sign(privateKey, 'base64url'); // Combine return `${dataToSign}.${signature}`; } function verifyJWT(token: string): { valid: boolean; payload?: any } { const parts = token.split('.'); if (parts.length !== 3) { return { valid: false }; } const [encodedHeader, encodedPayload, signature] = parts; const dataToVerify = `${encodedHeader}.${encodedPayload}`; // Verify signature const verify = createVerify('SHA256'); verify.update(dataToVerify); const isValid = verify.verify(publicKey, signature, 'base64url'); if (!isValid) { return { valid: false }; } // Decode payload const payload = JSON.parse( Buffer.from(encodedPayload, 'base64url').toString() ); // Check expiration if (payload.exp && payload.exp < Date.now() / 1000) { return { valid: false }; } return { valid: true, payload }; } // Usage const jwt = createJWT({ sub: 'user123', iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 3600 // 1 hour }); console.log('JWT:', jwt); const result = verifyJWT(jwt); console.log('Valid:', result.valid); console.log('Payload:', result.payload); ``` -------------------------------- ### Rebuild Native App Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/introduction/quick-start.mdx After installation, rebuild your native application to include the new C++ code. This is required for both Android and iOS. ```bash npx react-native run-android ``` ```bash npx react-native run-ios ``` -------------------------------- ### Uninstall Legacy Libraries Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/guides/migration.mdx Remove existing crypto shims before installing RNQC. This command uninstalls `react-native-crypto`, `rn-nodeify`, and `react-native-randombytes`. ```bash npm uninstall react-native-crypto rn-nodeify react-native-randombytes ``` -------------------------------- ### Basic Verification with Sign Object Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/signing.mdx Demonstrates how to verify signatures using the Sign object with different signature encodings (hex, base64) and buffer types. Ensure the public key and signature match the data signed. ```typescript import { createVerify } from 'react-native-quick-crypto'; const verify = createVerify('SHA256'); verify.update('data to sign'); // Verify hex signature const isValid = verify.verify(publicKey, signatureHex, 'hex'); // Verify base64 signature const isValid2 = verify.verify(publicKey, signatureB64, 'base64'); // Verify buffer signature const isValid3 = verify.verify(publicKey, signatureBuffer); ``` -------------------------------- ### RNQC Digest Comparison Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/guides/migration.mdx Example of hashing a string using `react-native-quick-crypto`. This method uses a chainable API with `createHash`, `update`, and `digest`. ```typescript import { createHash } from 'react-native-quick-crypto'; const digest = createHash('sha256').update('Hello world').digest('hex'); ``` -------------------------------- ### Add New Documentation Page Frontmatter Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/guides/contributing.mdx When creating a new documentation page, include this YAML frontmatter at the top of your `.mdx` file. ```yaml --- title: Your Page Title description: A brief description of the page content. --- ``` -------------------------------- ### Expo Crypto Digest Comparison Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/guides/migration.mdx Example of hashing a string using `expo-crypto`. This method uses `digestStringAsync` and requires specifying the algorithm. ```typescript import * as Crypto from 'expo-crypto'; const digest = await Crypto.digestStringAsync( Crypto.CryptoDigestAlgorithm.SHA256, 'Hello world' ); ``` -------------------------------- ### Import Keys from PEM, DER, or Raw Buffers Source: https://context7.com/margelo/react-native-quick-crypto/llms.txt Imports keys into `KeyObject` handles from various formats. `KeyObject`s keep key material in native memory. Ensure the correct key format and passphrase (if encrypted) are provided. ```ts import { createPublicKey, createPrivateKey, createSecretKey, randomBytes } from 'react-native-quick-crypto'; // Import a PEM public key const pubKey = createPublicKey(`-----BEGIN PUBLIC KEY-----\n...`); console.log(pubKey.asymmetricKeyType); // 'rsa' // Import an encrypted PKCS#8 private key const privKey = createPrivateKey({ key: encryptedPem, passphrase: 'user-password' }); // Create a symmetric key object from raw bytes const secret = createSecretKey(randomBytes(32)); console.log(secret.type); // 'secret' console.log(secret.symmetricKeySize); // 32 // Convert to/from WebCrypto CryptoKey const cryptoKey = secret.toCryptoKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']); ``` -------------------------------- ### Encrypt Wallet with Scrypt Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/scrypt.mdx Example demonstrating wallet encryption using scrypt for key derivation and AES-256-CTR for symmetric encryption. This function derives a secure encryption key from a password and uses it along with a random salt and IV to encrypt the private key. ```typescript import { scrypt, randomBytes, createCipheriv } from 'react-native-quick-crypto'; function encryptWallet(privateKey: Buffer, password: string): Promise { return new Promise((resolve, reject) => { const salt = randomBytes(32); const iv = randomBytes(16); // Derive encryption key scrypt(password, salt, 32, { N: 32768, r: 8, p: 1 }, (err, derivedKey) => { if (err) return reject(err); const cipherKey = derivedKey.slice(0, 32); const cipher = createCipheriv('aes-256-ctr', cipherKey, iv); let ciphertext = cipher.update(privateKey); ciphertext = Buffer.concat([ciphertext, cipher.final()]); resolve({ kdf: 'scrypt', ciphertext: ciphertext.toString('hex') }); }); }); } ``` -------------------------------- ### Prebuild (Expo) Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/introduction/complete-setup.mdx Generate the native android and ios directories for Expo projects after adding the config plugin. This library requires native code and will not work in Expo Go. ```bash npx expo prebuild ``` -------------------------------- ### User Registration Password Hashing Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/pbkdf2.mdx This example demonstrates how to securely hash a user's password during registration using the asynchronous PBKDF2 function. It generates a random salt and returns both the salt and the derived hash in hexadecimal format. ```typescript import { pbkdf2, randomBytes } from 'react-native-quick-crypto'; function hashUserPassword(password: string): Promise<{ salt: string, hash: string }> { return new Promise((resolve, reject) => { const salt = randomBytes(16); const iterations = 600000; pbkdf2(password, salt, iterations, 64, 'sha512', (err, key) => { if (err) return reject(err); resolve({ salt: salt.toString('hex'), hash: key.toString('hex') }); }); }); } ``` -------------------------------- ### Orchestrate Module Audit Source: https://github.com/margelo/react-native-quick-crypto/blob/main/plans/done/security-audit.md Example of launching parallel agents for a single module audit, covering C++ and TypeScript code, API surface, and testing. ```bash Launch in parallel: 1. crypto-specialist → Read cpp/cipher/GCMCipher.cpp, check correctness & timing 2. cpp-specialist → Read cpp/cipher/GCMCipher.cpp, check memory safety 3. typescript-specialist → Read src/cipher.ts + src/specs/cipher.nitro.ts, check API surface 4. testing-specialist → Read example/src/tests/cipher/, compare against implementation, find gaps ``` -------------------------------- ### x509.checkHost(name[, options]) Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/x509.mdx Checks whether the certificate matches the given hostname. It can optionally be configured with various wildcard and subject matching options. ```APIDOC ## x509.checkHost(name[, options]) ### Description Checks whether the certificate matches the given hostname. It can optionally be configured with various wildcard and subject matching options. ### Parameters #### Path Parameters - **name** (string) - Required - The hostname to check. - **options** (CheckOptions) - Optional - Optional check configuration. #### Request Body (No request body defined) ### Response #### Success Response (200) - **string | undefined** - The matched hostname, or `undefined` if no match. ### Request Example ```ts const cert = new X509Certificate(pemString); cert.checkHost('example.com'); // 'example.com' cert.checkHost('wrong.com'); // undefined // Disable wildcard matching cert.checkHost('sub.example.com', { wildcards: false }); ``` #### CheckOptions | Option | Type | Default | Description | | :---------------------- | :--------------------------------- | :---------- | :---------------------------------- | | `subject` | `'default' | 'always' | 'never'` | `'default'` | When to check the subject CN | | `wildcards` | `boolean` | `true` | Allow wildcard certificate matching | | `partialWildcards` | `boolean` | `true` | Allow partial wildcard matching | | `multiLabelWildcards` | `boolean` | `false` | Allow multi-label wildcard matching | | `singleLabelSubdomains` | `boolean` | `false` | Match single-label subdomains | ``` -------------------------------- ### Match Encoding for Signing and Verification Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/signing.mdx Use the same encoding or serialization format for the data when signing and verifying. For example, if you stringify JSON data for signing, do the same for verification. ```typescript // ❌ Wrong: Encoding mismatch - stringified vs object // sign.update(JSON.stringify(data)); // Stringified // verify.update(data); // Not stringified! Will fail! ``` ```typescript // ✅ Correct: Use same encoding const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); const data = { foo: 'bar' }; const payload = JSON.stringify(data); const sign = createSign('SHA256'); sign.update(payload); const signature = sign.sign(privateKey); const verify = createVerify('SHA256'); verify.update(payload); // Same encoding verify.verify(publicKey, signature); // Success ``` -------------------------------- ### scrypt(password, salt, keylen[, options], callback) Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/scrypt.mdx Asynchronously derives a key using the scrypt algorithm. It takes the password, salt, desired key length, optional parameters (N, r, p, maxmem), and a callback function. ```APIDOC ## scrypt(password, salt, keylen[, options], callback) ### Description Asynchronously derives a key using the scrypt algorithm. It takes the password, salt, desired key length, optional parameters (N, r, p, maxmem), and a callback function. ### Parameters #### Parameters - **password** (string | Buffer | TypedArray) - Required - The password. - **salt** (string | Buffer | TypedArray) - Required - Salt. Should be random. - **keylen** (number) - Required - Desired output length. - **options** (Object) - Optional - Parameters for scrypt. - **N** (number) - Optional - Cost factor. Default: 16384. - **r** (number) - Optional - Block size. Default: 8. - **p** (number) - Optional - Parallelization. Default: 1. - **maxmem** (number) - Optional - Memory limit check. Default: 32MB. Increase if N is high. - **callback** (Function) - Required - Called with `(err, derivedKey)`. ### Returns `void` ### Request Example ```ts import { scrypt, randomBytes } from 'react-native-quick-crypto'; const pass = 'correct horse battery staple'; const salt = randomBytes(16); const opts = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }; scrypt(pass, salt, 64, opts, (err, key) => { if (err) throw err; console.log('Derived Key:', key.toString('hex')); }); ``` ``` -------------------------------- ### createPublicKey / createPrivateKey / createSecretKey Source: https://context7.com/margelo/react-native-quick-crypto/llms.txt Import keys from PEM, DER, or raw buffers into `KeyObject` handles, which keep key material in native memory (not exposed to the JS GC heap). ```APIDOC ## createPublicKey / createPrivateKey / createSecretKey — Key Import Import keys from PEM, DER, or raw buffers into `KeyObject` handles, which keep key material in native memory (not exposed to the JS GC heap). ```ts import { createPublicKey, createPrivateKey, createSecretKey, randomBytes } from 'react-native-quick-crypto'; // Import a PEM public key const pubKey = createPublicKey(`-----BEGIN PUBLIC KEY-----\n...`); console.log(pubKey.asymmetricKeyType); // 'rsa' // Import an encrypted PKCS#8 private key const privKey = createPrivateKey({ key: encryptedPem, passphrase: 'user-password' }); // Create a symmetric key object from raw bytes const secret = createSecretKey(randomBytes(32)); console.log(secret.type); // 'secret' console.log(secret.symmetricKeySize); // 32 // Convert to/from WebCrypto CryptoKey const cryptoKey = secret.toCryptoKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']); ``` ``` -------------------------------- ### Derive Keys using BLAKE3 Context Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/blake3.mdx Demonstrates how to derive distinct encryption and signing keys from a master key using BLAKE3's context string feature for Key Derivation (KDF) mode. Ensure the master key is a 32-byte high-entropy buffer. ```typescript import { createBlake3 } from 'react-native-quick-crypto'; import { Buffer } from 'buffer'; const masterKey = Buffer.from('...'); // 32 bytes high-entropy function deriveKeys(master: Buffer) { // Derive Encryption Key const enc = createBlake3({ context: 'my-app-v1-encryption' }); enc.update(master); const encryptionKey = enc.digest(); // Derive Signing Key const sign = createBlake3({ context: 'my-app-v1-signing' }); sign.update(master); const signingKey = sign.digest(); return { encryptionKey, signingKey }; } ``` -------------------------------- ### Validate Server Certificate Fingerprint and Validity Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/x509.mdx Example demonstrating certificate pinning by checking the certificate's fingerprint and validity dates against current time. ```typescript import { X509Certificate } from 'react-native-quick-crypto'; const PINNED_FINGERPRINT = 'AB:CD:EF:...'; function validateServerCert(pemCert: string): boolean { const cert = new X509Certificate(pemCert); // Check fingerprint if (cert.fingerprint256 !== PINNED_FINGERPRINT) { return false; } // Check validity const now = new Date(); if (now < cert.validFromDate || now > cert.validToDate) { return false; } return true; } ``` -------------------------------- ### Instantiate X509Certificate Source: https://github.com/margelo/react-native-quick-crypto/blob/main/docs/content/docs/api/x509.mdx Create a new X509Certificate instance by providing PEM or DER encoded certificate data. This is the first step to accessing certificate properties. ```typescript import { X509Certificate } from 'react-native-quick-crypto'; const cert = new X509Certificate(pemString); ```