Skip to main content
Version: v3+

AES-CBC

createCrypto

Create an AES-CBC symmetric encryption instance. Plaintext length must be a multiple of 16 bytes.

| algorithmId | Description | API_LEVEL | | ------------- | ---------------------------- | --------- | --- | | alg.AES_CBC | AES-CBC symmetric encryption | 3.0 | . |

Type

function createCrypto(algorithmId: typeof alg.AES_CBC, option: AESOptions): AESCrypto | undefined

Parameters

AESData

TypeDescription
number[]|ArrayBuffer|Uint8ArrayData to process

AESOptions

PropertyTypeRequiredDefaultValueDescription
key_bit_lengthnumberY-Key length in bits; AES-CBC uses 128
key_encryptboolean|numberN-Whether the key is encrypted again by the hardware key
private_keyAESDataN-Existing private key; use it instead of generating a new key

AESCrypto

AES-CBC symmetric encryption instance.

Methods

createChiper

Create or return the AES private key; returns undefined on failure

createChiper(): AESKeyResult | undefined
AESKeyResult
PropertyTypeDescription
private_key_lengthnumberPrivate key length
private_keyArrayBufferPrivate key data

encrypt

Encrypt data whose length is a multiple of 16 bytes

encrypt(data: createCrypto.AESData): AESCipherResult | undefined
AESCipherResult
PropertyTypeDescription
dataArrayBufferEncrypted data
lengthnumberData length

decrypt

Decrypt AES-CBC data

decrypt(data: createCrypto.AESData): AESCipherResult | undefined
AESCipherResult
PropertyTypeDescription
dataArrayBufferDecrypted data
lengthnumberData length

Example

import { alg, createCrypto } from '@zos/crypto'

const plainData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])

const aes = createCrypto(alg.AES_CBC, {
key_bit_length: 128,
key_encrypt: 1,
})
if (!aes) throw new Error('Failed to create AES-CBC instance')

const keyInfo = aes.createChiper()
if (!keyInfo) throw new Error('Failed to create AES key')

const encrypted = aes.encrypt(plainData)
if (!encrypted) throw new Error('Failed to encrypt data')

const decrypted = aes.decrypt(encrypted.data)
if (!decrypted) throw new Error('Failed to decrypt data')
console.log(new Uint8Array(decrypted.data))

// Create another AES-CBC instance with an existing private key
const existingKey = new Uint8Array(keyInfo.private_key)
const aesWithExistingKey = createCrypto(alg.AES_CBC, {
key_bit_length: 128,
private_key: existingKey,
key_encrypt: 1,
})
if (!aesWithExistingKey) throw new Error('Failed to reuse AES key')

const encryptedAgain = aesWithExistingKey.encrypt(plainData)
const decryptedAgain = encryptedAgain ? aesWithExistingKey.decrypt(encryptedAgain.data) : undefined