Home > front end >  How to encrypt with ruby in aes-128-ctr mode
How to encrypt with ruby in aes-128-ctr mode

Time:09-29

I have applied the the encryption algorithm in nodejs and now I need to decrypt the same using python how would I be able to do this.

The JS code is -

const crypto = require('crypto');
const data = "Hello there, help me to encrypt using ruby"
let iv = 'N13FF0F4ACC4097M'
let key = '312s389g2r5b54rd'
const cp = crypto.createCipheriv('aes-128-ctr', key, iv)
let enc = cp.update(data, 'utf-8', 'base64')   cp.final('base64')
console.log(enc)


#output = 401Auq5PXMVzcbTJXl5hgLRccO8RSKFnBo5jsQuzkUNwJKMmwWHPpJTZ

Here is code i used in ruby -

require 'base64'
require 'json'
require 'digest/md5'
require 'openssl'
# Required Output - 401Auq5PXMVzcbTJXl5hgLRccO8RSKFnBo5jsQuzkUNwJKMmwWHPpJTZ
data = "Hello there, help me to encrypt using ruby"
cipher = OpenSSL::Cipher.new('aes-128-ctr').encrypt
cipher.iv = 'N13FF0F4ACC4097M'
cipher.key = '312s389g2r5b54rd'
encrypted = cipher.update(data)   cipher.final
puts encrypted.unpack("H*")

output = e34d40baae4f5cc57371b4c95e5e6180b45c70ef1148a167068e63b10bb391437024a326c161cfa494d9

CodePudding user response:

So the following should work for you: (I used the structure from the comment rather than the Post)

JS:

var obj = [{"edmc":"78787041","house_no":"987654234","type":"0","abc_type":"AABB","bbcname":"Unknown","abc_nick_name":"notKnown", "allot":"1.00", "hhic":"BAC1235","address1":"abcdw","city":"abcde", "state":"UU", "pincode":"123456", "email":"[email protected]","phone":"1234567898"}]; 
btoa(JSON.stringify(obj)); 

Results in:

W3siZWRtYyI6Ijc4Nzg3MDQxIiwiaG91c2Vfbm8iOiI5ODc2NTQyMzQiLCJ0eXBlIjoiMCIsImFiY190eXBlIjoiQUFCQiIsImJiY25hbWUiOiJVbmtub3duIiwiYWJjX25pY2tfbmFtZSI6Im5vdEtub3duIiwiYWxsb3QiOiIxLjAwIiwiaGhpYyI6IkJBQzEyMzUiLCJhZGRyZXNzMSI6ImFiY2R3IiwiY2l0eSI6ImFiY2RlIiwic3RhdGUiOiJVVSIsInBpbmNvZGUiOiIxMjM0NTYiLCJlbWFpbCI6ImFuY2Nzc0BnbWFpbC5jb20iLCJwaG9uZSI6IjEyMzQ1Njc4OTgifV0=

Ruby

obj = [{"edmc":"78787041","house_no":"987654234","type":"0","abc_type":"AABB","bbcname":"Unknown","abc_nick_name":"notKnown", "allot":"1.00", "hhic":"BAC1235","address1":"abcdw","city":"abcde", "state":"UU", "pincode":"123456", "email":"[email protected]","phone":"1234567898"}]
Base64.strict_encode64(obj.to_json) 

Results in

W3siZWRtYyI6Ijc4Nzg3MDQxIiwiaG91c2Vfbm8iOiI5ODc2NTQyMzQiLCJ0eXBlIjoiMCIsImFiY190eXBlIjoiQUFCQiIsImJiY25hbWUiOiJVbmtub3duIiwiYWJjX25pY2tfbmFtZSI6Im5vdEtub3duIiwiYWxsb3QiOiIxLjAwIiwiaGhpYyI6IkJBQzEyMzUiLCJhZGRyZXNzMSI6ImFiY2R3IiwiY2l0eSI6ImFiY2RlIiwic3RhdGUiOiJVVSIsInBpbmNvZGUiOiIxMjM0NTYiLCJlbWFpbCI6ImFuY2Nzc0BnbWFpbC5jb20iLCJwaG9uZSI6IjEyMzQ1Njc4OTgifV0=
  • Related