Translate Ruby OpenSSL code to Node.js Crytpo

Job ID: 34118676

Budget: $30 – $250 CAD

I have Ruby code that needs to be translated to a Node.js Crypto. The Ruby code that is operating is:


Inputs: siteToken, unencryptedPayload will be strings objects that get passed onto the code.
Output: encoded as a string object

-----Ruby Code-----------
require 'digest'
require 'openssl'
require "base64"
require 'cgi'
require 'json'


cipher = OpenSSL::Cipher.new('aes-256-cbc')
cipher.encrypt
cipher.key = Digest::SHA256.digest(siteToken)
iv = cipher.random_iv
encrypted = cipher.update(JSON.generate(unencryptedPayload)) + cipher.final
encoded = CGI::escape(Base64.encode64(iv + encrypted))
puts encoded
----------------------


----Sample non-working Node.js crypt call for this job (that is partially complete)-----

const crypto = require('crypto');


// Defining algorithm
const algorithm = 'aes-256-cbc';

// Defining key
//'key' variable is defined and equal to siteToken in the OpenSSL version
//const key = siteToken;

// Defining iv
const iv = crypto.randomBytes(16);

// An encrypt function
function encrypt(text) {

// Creating Cipheriv with its parameter
let cipher = crypto.createCipheriv(
'aes-256-cbc', Buffer.from(key), iv);

// Updating text
let encrypted = cipher.update(text);

// Using concatenation
encrypted = Buffer.concat([encrypted, cipher.final()]);

// Returning iv and encrypted data
return { iv: iv.toString('hex'),
encryptedData: encrypted.toString('hex') };
}

// Displays output
var output = encrypt(unencryptedPayload);
-----------------------------------------------

I will be copying and pasting your code into a Workato script. Unfortunately, additional libraries cannot be added, besides the Node.js crypto function and any library calls that it supports. This is due today.