abcrypt_wasm/
encrypt.rs

1// SPDX-FileCopyrightText: 2022 Shun Sakai
2//
3// SPDX-License-Identifier: Apache-2.0 OR MIT
4
5//! Encrypts to the abcrypt encrypted data format.
6
7use abcrypt::{
8    Error,
9    argon2::{Algorithm, Params},
10};
11use wasm_bindgen::{JsError, prelude::wasm_bindgen};
12
13/// Encrypts `plaintext` and into a newly allocated `Uint8Array`.
14///
15/// This uses the recommended Argon2 parameters according to the OWASP Password
16/// Storage Cheat Sheet. This also uses Argon2id as the Argon2 type and version
17/// 0x13 as the Argon2 version.
18///
19/// # Errors
20///
21/// Returns an error if the Argon2 context is invalid.
22#[wasm_bindgen]
23pub fn encrypt(plaintext: &[u8], passphrase: &[u8]) -> Result<Vec<u8>, JsError> {
24    abcrypt::encrypt(plaintext, passphrase).map_err(JsError::from)
25}
26
27#[allow(clippy::module_name_repetitions)]
28/// Encrypts `plaintext` with the specified Argon2 parameters and into a newly
29/// allocated `Uint8Array`.
30///
31/// This uses Argon2id as the Argon2 type and version 0x13 as the Argon2
32/// version.
33///
34/// # Errors
35///
36/// Returns an error if any of the following are true:
37///
38/// - The Argon2 parameters are invalid.
39/// - The Argon2 context is invalid.
40#[wasm_bindgen(js_name = encryptWithParams)]
41pub fn encrypt_with_params(
42    plaintext: &[u8],
43    passphrase: &[u8],
44    memory_cost: u32,
45    time_cost: u32,
46    parallelism: u32,
47) -> Result<Vec<u8>, JsError> {
48    let params = Params::new(memory_cost, time_cost, parallelism, None)?;
49    abcrypt::encrypt_with_params(plaintext, passphrase, params).map_err(JsError::from)
50}
51
52#[allow(clippy::module_name_repetitions)]
53/// Encrypts `plaintext` with the specified Argon2 type, Argon2 version and
54/// Argon2 parameters and into a newly allocated `Uint8Array`.
55///
56/// # Errors
57///
58/// Returns an error if any of the following are true:
59///
60/// - The Argon2 type is invalid.
61/// - The Argon2 version is invalid.
62/// - The Argon2 parameters are invalid.
63/// - The Argon2 context is invalid.
64#[wasm_bindgen(js_name = encryptWithContext)]
65pub fn encrypt_with_context(
66    plaintext: &[u8],
67    passphrase: &[u8],
68    argon2_type: u32,
69    argon2_version: u32,
70    memory_cost: u32,
71    time_cost: u32,
72    parallelism: u32,
73) -> Result<Vec<u8>, JsError> {
74    let argon2_type = match argon2_type {
75        0 => Ok(Algorithm::Argon2d),
76        1 => Ok(Algorithm::Argon2i),
77        2 => Ok(Algorithm::Argon2id),
78        t => Err(Error::InvalidArgon2Type(t)),
79    }?;
80    let argon2_version = argon2_version.try_into()?;
81    let params = Params::new(memory_cost, time_cost, parallelism, None)?;
82    abcrypt::encrypt_with_context(plaintext, passphrase, argon2_type, argon2_version, params)
83        .map_err(JsError::from)
84}