### Install react-native-webview-crypto
Source: https://github.com/webview-crypto/react-native-webview-crypto/blob/master/readme.md
Installs the react-native-webview-crypto library and links it to your React Native project. Ensure 'react-native link' is run after installation.
```sh
npm install --save react-native-webview react-native-webview-crypto
react-native link
```
--------------------------------
### Complete ECDSA Sign/Verify Workflow Example in JavaScript
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Demonstrates a full sign-and-verify workflow using ECDSA. It generates a key pair, signs a message, and then verifies the signature using the public key. It also tests verification with tampered data to show failure. This example requires `signData` and `verifySignature` to be defined.
```javascript
async function signVerifyExample() {
const keyPair = await window.crypto.subtle.generateKey(
{ name: "ECDSA", namedCurve: "P-256" },
true,
["sign", "verify"]
);
const message = "Important document";
const signature = await signData(message, keyPair.privateKey); // Assumes signData is defined
const isValid = await verifySignature(message, signature, keyPair.publicKey); // Assumes verifySignature is defined
console.log("Signature valid:", isValid); // true
const isTamperedValid = await verifySignature(
"Tampered document",
signature,
keyPair.publicKey
);
console.log("Tampered signature valid:", isTamperedValid); // false
}
```
--------------------------------
### Usage Example for Hashing Data with SHA-256 in JavaScript
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Provides a practical example of using the `hashData` function to generate a SHA-256 hash for a given string. It also includes an assertion to verify that hashing the same data twice produces identical results. This example requires `hashData` to be defined.
```javascript
async function hashExample() {
const data = "Data to hash";
const hash = await hashData(data); // Assumes hashData is defined
console.log("SHA-256 hash:", hash);
// Verify hash consistency
const hash2 = await hashData(data);
console.assert(hash === hash2, "Hashes should match");
}
```
--------------------------------
### Complete ECDSA Signing Example in JavaScript
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Illustrates a complete signing workflow using ECDSA. It generates an ECDSA key pair, signs a message using the private key, and logs the resulting signature. The public key is also returned for subsequent verification. This example requires the `signData` function to be defined elsewhere.
```javascript
async function signatureExample() {
const keyPair = await window.crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-256"
},
true,
["sign", "verify"]
);
const message = "Document to sign";
const signature = await signData(message, keyPair.privateKey); // Assumes signData is defined
console.log("Signature:", signature);
return { signature, publicKey: keyPair.publicKey };
}
```
--------------------------------
### Complete AES-GCM Encrypt/Decrypt Example in JavaScript
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Demonstrates a full encrypt-decrypt workflow using AES-GCM. It generates a key, encrypts a message, and then decrypts it, asserting that the original and decrypted messages match. This example requires the `encryptData` function to be defined elsewhere.
```javascript
async function encryptDecryptExample() {
const key = await window.crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
const originalMessage = "Confidential data";
const { ciphertext, iv } = await encryptData(originalMessage, key); // Assumes encryptData is defined
const decryptedMessage = await decryptData(ciphertext, key, iv);
console.log("Original:", originalMessage);
console.log("Decrypted:", decryptedMessage);
console.assert(originalMessage === decryptedMessage);
}
```
--------------------------------
### Initialize PolyfillCrypto in React Native App
Source: https://github.com/webview-crypto/react-native-webview-crypto/blob/master/readme.md
Renders the PolyfillCrypto component to enable crypto functionality. This component starts a hidden WebView that proxies crypto calls. Import React, View, and PolyfillCrypto, then include PolyfillCrypto within your component's render method.
```javascript
import React, { Component } from 'react'
import { View } from 'react-native'
import App from './app'
import PolyfillCrypto from 'react-native-webview-crypto'
class TopLevelComponent extends Component {
render() {
return (
)
}
}
AppRegistry.registerComponent('WhateverName', () => TopLevelComponent)
```
--------------------------------
### PolyfillCrypto Component Setup
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
The PolyfillCrypto component must be rendered in your application to enable crypto functionality. It renders a hidden WebView that processes all cryptographic operations and automatically polyfills `window.crypto.subtle` globally.
```APIDOC
## PolyfillCrypto Component Setup
### Description
The `PolyfillCrypto` component is a React component that must be rendered in your application to enable crypto functionality. It renders a hidden WebView that processes all cryptographic operations. Once rendered, it automatically polyfills `window.crypto.subtle` globally.
### Usage
```javascript
import React, { Component } from 'react';
import { View, AppRegistry } from 'react-native';
import PolyfillCrypto from 'react-native-webview-crypto';
class App extends Component {
render() {
return (
);
}
}
AppRegistry.registerComponent('MyApp', () => App);
```
```
--------------------------------
### Import Order for react-native-crypto Compatibility
Source: https://github.com/webview-crypto/react-native-webview-crypto/blob/master/readme.md
Demonstrates the correct import order when using 'react-native-crypto' with 'react-native-webview-crypto' to avoid cyclic require warnings. Import 'react-native-crypto' before 'react-native-webview-crypto'.
```javascript
import 'react-native-crypto'
import WebviewCrypto from 'react-native-webview-crypto'
```
--------------------------------
### Export and Encrypt Key with crypto.subtle.wrapKey() (JavaScript)
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Exports and encrypts a key in a single operation using `crypto.subtle.wrapKey()`. This is useful for secure key storage or transmission. It takes the key to wrap, a wrapping key, and an algorithm configuration. It returns the wrapped key as a Uint8Array.
```javascript
async function wrapKeyForStorage(keyToWrap, wrappingKey) {
try {
const wrappedKey = await window.crypto.subtle.wrapKey(
"jwk",
keyToWrap,
wrappingKey,
{
name: "AES-GCM",
iv: window.crypto.getRandomValues(new Uint8Array(12))
}
);
return new Uint8Array(wrappedKey);
} catch (error) {
console.error("Key wrapping failed:", error);
throw error;
}
}
// Complete wrap example
async function keyWrappingExample() {
// Generate wrapping key
const wrappingKey = await window.crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["wrapKey", "unwrapKey"]
);
// Generate key to wrap
const keyToWrap = await window.crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
const wrapped = await wrapKeyForStorage(keyToWrap, wrappingKey);
console.log("Wrapped key:", wrapped);
}
```
--------------------------------
### Render PolyfillCrypto Component in React Native
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Renders the hidden WebView component necessary for cryptographic operations. This component must be included in your application's root view to globally polyfill `window.crypto.subtle`. No specific inputs are required, and it outputs by enabling the crypto API.
```javascript
import React, { Component } from 'react';
import { View, AppRegistry } from 'react-native';
import PolyfillCrypto from 'react-native-webview-crypto';
class App extends Component {
render() {
return (
);
}
}
AppRegistry.registerComponent('MyApp', () => App);
```
--------------------------------
### crypto.subtle.sign()
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Creates a digital signature for data using a private key. This is crucial for verifying the authenticity and integrity of data.
```APIDOC
## crypto.subtle.sign()
### Description
Creates a digital signature for data using a private key. Useful for authentication and data integrity verification.
### Method
`sign` (part of `crypto.subtle`)
### Parameters
- `algorithm` (object) - The algorithm to use for signing. For ECDSA, this includes `name: "ECDSA"` and `hash: { name: "SHA-256" }`.
- `key` (CryptoKey) - The private key to use for signing.
- `data` (BufferSource) - The data to sign.
### Request Example
```javascript
// Sign data with ECDSA
async function signData(data, privateKey) {
try {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const signature = await window.crypto.subtle.sign(
{
name: "ECDSA",
hash: { name: "SHA-256" }
},
privateKey,
encodedData
);
return new Uint8Array(signature);
} catch (error) {
console.error("Signing failed:", error);
throw error;
}
}
```
### Response
#### Success Response
- `signature` (ArrayBuffer or Uint8Array) - The generated digital signature.
#### Response Example
(The example shows the function call and return, not a direct response object)
```javascript
const signature = await signData(message, keyPair.privateKey);
console.log("Signature:", signature);
```
```
--------------------------------
### Decrypt and Import Key with crypto.subtle.unwrapKey() (JavaScript)
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Decrypts and imports a previously wrapped key in a single operation using `crypto.subtle.unwrapKey()`. This function is the counterpart to `wrapKey`. It requires the wrapped key, the unwrapping key, an initialization vector (IV), and details about the desired format and algorithm of the unwrapped key. It returns the unwrapped key object.
```javascript
async function unwrapStoredKey(wrappedKey, unwrappingKey, iv) {
try {
const unwrappedKey = await window.crypto.subtle.unwrapKey(
"jwk",
wrappedKey,
unwrappingKey,
{
name: "AES-GCM",
iv: iv
},
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
return unwrappedKey;
} catch (error) {
console.error("Key unwrapping failed:", error);
throw error;
}
}
// Complete wrap/unwrap workflow
async function wrapUnwrapExample() {
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const wrappingKey = await window.crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["wrapKey", "unwrapKey"]
);
const originalKey = await window.crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
const wrapped = await window.crypto.subtle.wrapKey(
"jwk",
originalKey,
wrappingKey,
{ name: "AES-GCM", iv: iv }
);
console.log("Wrapped:", new Uint8Array(wrapped));
const unwrapped = await unwrapStoredKey(wrapped, wrappingKey, iv);
console.log("Unwrapped key:", unwrapped);
// Verify both keys work the same
const testData = new TextEncoder().encode("test");
const testIv = window.crypto.getRandomValues(new Uint8Array(12));
const encrypted = await window.crypto.subtle.encrypt(
{ name: "AES-GCM", iv: testIv },
unwrapped,
testData
);
console.log("Successfully encrypted with unwrapped key");
}
```
--------------------------------
### Import Cryptographic Key (JavaScript)
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Imports a cryptographic key from external data. Supports formats like raw, jwk, pkcs8, and spki. Requires key usage and algorithm details. This function is essential for using pre-generated or externally stored keys.
```javascript
async function importPublicKey(jwkKey) {
try {
const publicKey = await window.crypto.subtle.importKey(
"jwk",
jwkKey,
{
name: "RSA-OAEP",
hash: "SHA-256"
},
true,
["encrypt"]
);
return publicKey;
} catch (error) {
console.error("Key import failed:", error);
throw error;
}
}
// Complete import/export example
async function importExportExample() {
// Generate and export key
const keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
},
true,
["encrypt", "decrypt"]
);
const exportedPublicKey = await window.crypto.subtle.exportKey(
"jwk",
keyPair.publicKey
);
console.log("Exported public key:", exportedPublicKey);
// Import the key back
const importedKey = await importPublicKey(exportedPublicKey);
console.log("Imported key:", importedKey);
}
```
--------------------------------
### Sign Data using ECDSA in JavaScript
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Creates a digital signature for input data using the ECDSA algorithm with a private key. The data is first encoded to UTF-8. The function returns the signature as a Uint8Array. Dependencies include the Web Crypto API. Input is data and a private key; output is the signature.
```javascript
async function signData(data, privateKey) {
try {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const signature = await window.crypto.subtle.sign(
{
name: "ECDSA",
hash: { name: "SHA-256" }
},
privateKey,
encodedData
);
return new Uint8Array(signature);
} catch (error) {
console.error("Signing failed:", error);
throw error;
}
}
```
--------------------------------
### crypto.subtle.encrypt()
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Encrypts data using a specified algorithm and key. Returns a Promise that resolves to an ArrayBuffer containing the encrypted data.
```APIDOC
## crypto.subtle.encrypt()
### Description
Encrypts data using a specified algorithm and key. Returns a Promise that resolves to an ArrayBuffer containing the encrypted data.
### Method
`POST` (Internally proxied)
### Endpoint
`/crypto/encrypt` (Internal)
### Parameters
#### Request Body
- **algorithm** (object) - Required - An object specifying the encryption algorithm and its parameters.
- **name** (string) - Required - The name of the algorithm (e.g., "AES-GCM").
- **iv** (Uint8Array) - Required - The initialization vector for the encryption.
- **key** (object) - Required - The cryptographic key to use for encryption.
- **data** (BufferSource) - Required - The data to encrypt.
### Request Example
```json
{
"algorithm": {
"name": "AES-GCM",
"iv": [ /* iv as Uint8Array */ ]
},
"key": { /* ... key object ... */ },
"data": [ /* data as BufferSource */ ]
}
```
### Response
#### Success Response (200)
- **ciphertext** (ArrayBuffer) - The encrypted data.
#### Response Example
```json
{
"ciphertext": [ /* encrypted data as ArrayBuffer */ ]
}
```
```
--------------------------------
### crypto.subtle.verify()
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Verifies a digital signature against data using a public key. It returns a boolean indicating whether the signature is valid for the given data and public key.
```APIDOC
## crypto.subtle.verify()
### Description
Verifies a digital signature against data using a public key. Returns a Promise that resolves to a boolean indicating validity.
### Method
`verify` (part of `crypto.subtle`)
### Parameters
- `algorithm` (object) - The algorithm used for signing. For ECDSA, this includes `name: "ECDSA"` and `hash: { name: "SHA-256" }`.
- `key` (CryptoKey) - The public key to use for verification.
- `signature` (BufferSource) - The signature to verify.
- `data` (BufferSource) - The original data that was signed.
### Request Example
```javascript
// Verify signature with ECDSA
async function verifySignature(data, signature, publicKey) {
try {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const isValid = await window.crypto.subtle.verify(
{
name: "ECDSA",
hash: { name: "SHA-256" }
},
publicKey,
signature,
encodedData
);
return isValid;
} catch (error) {
console.error("Verification failed:", error);
return false;
}
}
```
### Response
#### Success Response
- `isValid` (boolean) - `true` if the signature is valid, `false` otherwise.
#### Response Example
(The example shows the function call and return, not a direct response object)
```javascript
const isValid = await verifySignature(message, signature, keyPair.publicKey);
console.log("Signature valid:", isValid);
```
```
--------------------------------
### Generate Cryptographic Keys with SubtleCrypto API
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Generates new cryptographic keys or key pairs using `window.crypto.subtle.generateKey`. Supports symmetric keys (AES, HMAC) and asymmetric key pairs (RSA, ECDSA, ECDH). The function takes algorithm details and key usages as input, returning a Promise that resolves to the generated key or key pair.
```javascript
import PolyfillCrypto from 'react-native-webview-crypto';
// Generate RSA key pair for encryption
async function generateRSAKeyPair() {
try {
const keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
},
true,
["encrypt", "decrypt"]
);
console.log("Public key:", keyPair.publicKey);
console.log("Private key:", keyPair.privateKey);
return keyPair;
} catch (error) {
console.error("Key generation failed:", error);
throw error;
}
}
// Generate AES symmetric key
async function generateAESKey() {
try {
const key = await window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256
},
true,
["encrypt", "decrypt"]
);
return key;
} catch (error) {
console.error("AES key generation failed:", error);
throw error;
}
}
```
--------------------------------
### Verify Signature using ECDSA in JavaScript
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Verifies a digital signature against the original data using a public key and the ECDSA algorithm. The function returns a boolean indicating whether the signature is valid. Dependencies include the Web Crypto API. Input is data, signature, and public key; output is a boolean.
```javascript
async function verifySignature(data, signature, publicKey) {
try {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const isValid = await window.crypto.subtle.verify(
{
name: "ECDSA",
hash: { name: "SHA-256" }
},
publicKey,
signature,
encodedData
);
return isValid;
} catch (error) {
console.error("Verification failed:", error);
return false;
}
}
```
--------------------------------
### Encrypt Data with AES-GCM using SubtleCrypto API
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Encrypts plaintext data using the AES-GCM algorithm and a provided key. It requires the data, the encryption key, and generates a random Initialization Vector (IV). The function returns a Promise resolving to an object containing the ciphertext and the IV as ArrayBuffers.
```javascript
// Encrypt data with AES-GCM
async function encryptData(data, key) {
try {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const encrypted = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv
},
key,
encodedData
);
return {
ciphertext: new Uint8Array(encrypted),
iv: iv
};
} catch (error) {
console.error("Encryption failed:", error);
throw error;
}
}
// Usage example
async function exampleEncryption() {
const key = await window.crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
const result = await encryptData("Secret message", key);
console.log("Encrypted:", result.ciphertext);
console.log("IV:", result.iv);
}
```
--------------------------------
### Generate SHA-256 Hash in JavaScript
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Generates a SHA-256 cryptographic hash of the input data. The data is encoded to UTF-8 before hashing. The function returns the hash as a hexadecimal string. Dependencies include the Web Crypto API. Input is data; output is the SHA-256 hash string.
```javascript
async function hashData(data) {
try {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const hashBuffer = await window.crypto.subtle.digest(
"SHA-256",
encodedData
);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
} catch (error) {
console.error("Hashing failed:", error);
throw error;
}
}
```
--------------------------------
### Derive Key from Password (JavaScript)
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Derives a cryptographic key from a password using PBKDF2. This function takes a password and a salt, returning a derived AES-GCM key suitable for encryption and decryption. It requires the Web Crypto API and TextEncoder support.
```javascript
// Derive key from password using PBKDF2
async function deriveKeyFromPassword(password, salt) {
try {
const encoder = new TextEncoder();
const passwordBuffer = encoder.encode(password);
const baseKey = await window.crypto.subtle.importKey(
"raw",
passwordBuffer,
"PBKDF2",
false,
["deriveKey"]
);
const derivedKey = await window.crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: salt,
iterations: 100000,
hash: "SHA-256"
},
baseKey,
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
return derivedKey;
} catch (error) {
console.error("Key derivation failed:", error);
throw error;
}
}
// Usage example
async function keyDerivationExample() {
const password = "user-password-123";
const salt = window.crypto.getRandomValues(new Uint8Array(16));
const key = await deriveKeyFromPassword(password, salt);
console.log("Derived key:", key);
// Use the derived key for encryption
const data = "Sensitive data";
const encoder = new TextEncoder();
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const encrypted = await window.crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
key,
encoder.encode(data)
);
console.log("Encrypted with derived key:", new Uint8Array(encrypted));
}
```
--------------------------------
### Decrypt Data using AES-GCM in JavaScript
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Decrypts previously encrypted data using the AES-GCM algorithm with a provided key and initialization vector (IV). It decodes the decrypted buffer into a UTF-8 string. Dependencies include the Web Crypto API. Input is ciphertext, key, and IV; output is the decrypted string.
```javascript
async function decryptData(encryptedData, key, iv) {
try {
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv
},
key,
encryptedData
);
const decoder = new TextDecoder();
return decoder.decode(decrypted);
} catch (error) {
console.error("Decryption failed:", error);
throw error;
}
}
```
--------------------------------
### Export Cryptographic Key (JavaScript)
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Exports a cryptographic key into various formats like JWK or raw bytes. This is crucial for securely storing or transmitting keys. The function requires the key object and the desired export format.
```javascript
// Export key to JWK format
async function exportKeyAsJWK(key) {
try {
const exported = await window.crypto.subtle.exportKey("jwk", key);
return exported;
} catch (error) {
console.error("Key export failed:", error);
throw error;
}
}
// Export to raw format
async function exportKeyAsRaw(key) {
try {
const exported = await window.crypto.subtle.exportKey("raw", key);
return new Uint8Array(exported);
} catch (error) {
console.error("Key export failed:", error);
throw error;
}
}
// Usage example
async function keyExportExample() {
const key = await window.crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
const jwkKey = await exportKeyAsJWK(key);
console.log("JWK format:", JSON.stringify(jwkKey, null, 2));
const rawKey = await exportKeyAsRaw(key);
console.log("Raw format length:", rawKey.length);
}
```
--------------------------------
### Derive Bits from Password (JavaScript)
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Derives raw cryptographic bits from a password using PBKDF2. This is useful for generating shared secrets or additional key material. The function takes a password, salt, and the desired length of bits.
```javascript
// Derive bits from password
async function deriveBitsFromPassword(password, salt, length) {
try {
const encoder = new TextEncoder();
const passwordBuffer = encoder.encode(password);
const baseKey = await window.crypto.subtle.importKey(
"raw",
passwordBuffer,
"PBKDF2",
false,
["deriveBits"]
);
const bits = await window.crypto.subtle.deriveBits(
{
name: "PBKDF2",
salt: salt,
iterations: 100000,
hash: "SHA-256"
},
baseKey,
length
);
return new Uint8Array(bits);
} catch (error) {
console.error("Bit derivation failed:", error);
throw error;
}
}
// Usage example
async function deriveBitsExample() {
const password = "master-password";
const salt = window.crypto.getRandomValues(new Uint8Array(16));
const bits = await deriveBitsFromPassword(password, salt, 256);
console.log("Derived bits:", bits);
console.log("Length:", bits.length, "bytes");
}
```
--------------------------------
### crypto.subtle.generateKey()
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Generates a new cryptographic key or key pair for use with cryptographic operations. Supports symmetric keys (AES, HMAC) and asymmetric key pairs (RSA, ECDSA, ECDH).
```APIDOC
## crypto.subtle.generateKey()
### Description
Generates a new cryptographic key or key pair for use with cryptographic operations. Supports symmetric keys (AES, HMAC) and asymmetric key pairs (RSA, ECDSA, ECDH).
### Method
`POST` (Internally proxied)
### Endpoint
`/crypto/generateKey` (Internal)
### Parameters
#### Request Body
- **options** (object) - Required - An object containing algorithm-specific parameters and key properties.
- **name** (string) - Required - The name of the algorithm (e.g., "RSA-OAEP", "AES-GCM").
- **modulusLength** (number) - Optional - For RSA keys, the length of the modulus in bits.
- **publicExponent** (Uint8Array) - Optional - For RSA keys, the public exponent.
- **hash** (string) - Optional - For RSA keys, the name of the hash algorithm (e.g., "SHA-256").
- **length** (number) - Optional - For AES keys, the length of the key in bits (e.g., 128, 192, 256).
- **extractable** (boolean) - Required - Indicates whether the key can be exported.
- **keyUsages** (Array) - Required - An array of strings specifying the permitted uses of the key (e.g., ["encrypt", "decrypt"]).
### Request Example (RSA Key Pair)
```json
{
"options": {
"name": "RSA-OAEP",
"modulusLength": 2048,
"publicExponent": [1, 0, 1],
"hash": "SHA-256"
},
"extractable": true,
"keyUsages": ["encrypt", "decrypt"]
}
```
### Request Example (AES Key)
```json
{
"options": {
"name": "AES-GCM",
"length": 256
},
"extractable": true,
"keyUsages": ["encrypt", "decrypt"]
}
```
### Response
#### Success Response (200)
- **publicKey** (object) - The generated public key (for asymmetric keys).
- **privateKey** (object) - The generated private key (for asymmetric keys).
- **key** (object) - The generated symmetric key.
#### Response Example (RSA Key Pair)
```json
{
"publicKey": { /* ... public key details ... */ },
"privateKey": { /* ... private key details ... */ }
}
```
#### Response Example (AES Key)
```json
{
"key": { /* ... symmetric key details ... */ }
}
```
```
--------------------------------
### crypto.subtle.digest()
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Generates a cryptographic hash of data using various algorithms like SHA-256, SHA-384, or SHA-512. Hashing is fundamental for data integrity checks and password storage.
```APIDOC
## crypto.subtle.digest()
### Description
Generates a cryptographic hash of data using algorithms like SHA-256, SHA-384, or SHA-512.
### Method
`digest` (part of `crypto.subtle`)
### Parameters
- `algorithm` (string or object) - The hash algorithm to use (e.g., "SHA-256").
- `data` (BufferSource) - The data to hash.
### Request Example
```javascript
// Generate SHA-256 hash
async function hashData(data) {
try {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const hashBuffer = await window.crypto.subtle.digest(
"SHA-256",
encodedData
);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
} catch (error) {
console.error("Hashing failed:", error);
throw error;
}
}
```
### Response
#### Success Response
- `hash` (string) - The hexadecimal representation of the calculated hash.
#### Response Example
(The example shows the function call and return, not a direct response object)
```javascript
const hash = await hashData(data);
console.log("SHA-256 hash:", hash);
```
```
--------------------------------
### crypto.subtle.decrypt()
Source: https://context7.com/webview-crypto/react-native-webview-crypto/llms.txt
Decrypts previously encrypted data using the corresponding key and algorithm parameters. This function is essential for retrieving original data after it has been encrypted.
```APIDOC
## crypto.subtle.decrypt()
### Description
Decrypts previously encrypted data using the corresponding key and algorithm parameters.
### Method
`decrypt` (part of `crypto.subtle`)
### Parameters
- `algorithm` (object) - The algorithm to use for decryption. For AES-GCM, this includes `name: "AES-GCM"` and `iv: Uint8Array`.
- `key` (CryptoKey) - The key to use for decryption.
- `data` (BufferSource) - The data to decrypt.
### Request Example
```javascript
// Decrypt data with AES-GCM
async function decryptData(encryptedData, key, iv) {
try {
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv
},
key,
encryptedData
);
const decoder = new TextDecoder();
return decoder.decode(decrypted);
} catch (error) {
console.error("Decryption failed:", error);
throw error;
}
}
```
### Response
#### Success Response
- `decryptedData` (ArrayBuffer) - The decrypted data.
#### Response Example
(The example shows the function call and return, not a direct response object)
```javascript
const decryptedMessage = await decryptData(ciphertext, key, iv);
// decryptedMessage will contain the original plain text
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.