0

I want to migrating an encryption function from Node.js to Rust and need guidance on ensuring the Rust implementation behaves the same way as the Node.js crypto.createCipher method. I want to make sure that encryption and decryption are interoperable between the two languages.

Node Code :

const crypto = require('crypto');

var encryption = function (doc) {
   let key = "QLFZQhdUmCgQa5cSBYlHFeqGYw0yPtWiqvCbdYIlQnq3jDMSaWnjR0FjeeyIU8rd";
   const cipher = crypto.createCipher("aes256",key);
   let encrypted = cipher.update(doc, 'utf8', 'hex');
   encrypted += cipher.final('hex');
   return encrypted;
};

Questions & Concerns:

  1. How to implement the same AES-256 encryption in Rust?
  2. Does crypto.createCipher('aes256', key) apply any implicit padding?

I tried implementing AES-256 decryption in Rust using the aes crate, but I get a key length mismatch error:

use aes::Aes256;
use aes::cipher::{KeyInit, generic_array::GenericArray};
use serde_json::{json, Value};

pub fn norm_aes_decryption(encrypted_data: String) -> Result<Value, String> {
let key = "QLFZQhdUmCgQa5cSBYlHFeqGYw0yPtWiqvCbdYIlQnq3jDMSaWnjR0FjeeyIU8rd";

let key_bytes = key.as_bytes();
let key = GenericArray::from_slice(key_bytes);
let cipher = Aes256::new(&key);

println!("{:?}", cipher);
Ok(json!({}))

}

Error Output: thread 'main' panicked at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/generic-array-0.14.7/src/lib.rs:572:9: assertion left == right failed left: 64 right: 32 note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

1
  • 1
    createCipher() is insecure and is no longer supported (as of v22, s. here). Porting is not recommended. If you still want it: createCipher() derives a 32 bytes key and a 16 bytes IV using the OpenSSL proprietary (and deprecated) key derivation function EVP_BytesToKey() with an iteration count of 1, the digest MD5 and without salt. So you need a library that exposes EVP_BytesToKey() or you have to implement it yourself. Commented Feb 5 at 13:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.