You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求支持初始向量(IV)的React Native AES-128加密库

AES-128 Encryption in React Native (Matching Node.js's crypto.createCipheriv)

Hey Luis! I’ve got a few solid solutions for you to implement AES-128 encryption in React Native that aligns with the functionality you know from Node.js’s crypto.createCipheriv method. Let’s break them down:

1. Use react-native-crypto (Node.js Crypto Port)

This library is essentially a direct port of Node.js’s crypto module to React Native, so the API will feel identical to what you’re used to. It fully supports AES-128 in modes like CBC (just like createCipheriv).

Here’s a quick example of how to use it:

import crypto from 'react-native-crypto';

// Configure AES-128-CBC parameters
const algorithm = 'aes-128-cbc';
const key = Buffer.from('your-16-byte-secret-key', 'utf8'); // AES-128 requires a 16-byte key
const iv = crypto.randomBytes(16); // Generate a 16-byte initialization vector

// Encryption function matching Node.js pattern
function encryptText(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encryptedData = cipher.update(text, 'utf8', 'base64');
  encryptedData += cipher.final('base64');
  
  // Return encrypted data + IV (you'll need the IV for decryption)
  return {
    encrypted: encryptedData,
    iv: iv.toString('base64')
  };
}

2. Expo Users: expo-crypto

If you’re building with Expo, expo-crypto has built-in support for AES-128 encryption with a straightforward async API. While it’s not a 1:1 match to Node.js’s callback-based createCipheriv, it achieves the same result.

Example code:

import * as Crypto from 'expo-crypto';

async function encryptAES128(text, secretKey, iv) {
  // Convert inputs to Uint8Array (required by expo-crypto)
  const textBytes = new TextEncoder().encode(text);
  const keyBytes = new TextEncoder().encode(secretKey); // Must be 16 bytes for AES-128
  const ivBytes = new TextEncoder().encode(iv); // 16-byte IV

  const encryptedBytes = await Crypto.encryptAsync(
    Crypto.CipherAlgorithm.AES_128_CBC,
    textBytes,
    keyBytes,
    { iv: ivBytes }
  );

  // Convert encrypted bytes to base64 for easy storage/transmission
  return Crypto.bytesToBase64(encryptedBytes);
}

3. Check Your Existing react-native-aes Library First!

Wait a second—you mentioned react-native-aes only supports AES-256, but that might not be the case. Many AES libraries automatically switch between AES-128 and AES-256 based on the length of the key you provide:

  • 16-byte key → AES-128
  • 32-byte key → AES-256

Try passing a 16-byte key to the library’s encryption method—chances are it’ll use AES-128 without any extra configuration. That could save you from switching libraries entirely!


内容的提问来源于stack exchange,提问作者LuisPinto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:46:10