Decrypt code , from ruby to js - javascript

does anyone know how to translate below ruby script to javascript?
source = ENCRYPTED_STRING
cipher = OpenSSL::Cipher::Cipher.new('AES-128-ECB')
cipher.decrypt
cipher.key = ['SECRET'].pack('H*')
decoded = Base64.decode64(source)
decrypted = cipher.update(decoded) + cipher.final

I'm assuming you want to encrypt a string using "SECRET" as a passphrase.
Here's an example using crypto-js:
source = ENCRYPTED_STRING
var encrypted = CryptoJS.AES.encrypt(source, "SECRET");

http://yijiebuyi.com/blog/13e2ae33082ac12ba4946b033be04bb5.html
problem solved.
function decryption(data, key) {
var iv = "";
var clearEncoding = 'utf8';
var cipherEncoding = 'base64';
var cipherChunks = [];
var decipher = crypto.createDecipheriv('aes-128-ecb', key, iv);
decipher.setAutoPadding(true);
cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
cipherChunks.push(decipher.final(clearEncoding));
return cipherChunks.join('');
}

Related

Decrypt AES-generated hex from aes-js(Javascript) to pycryptodome(Python)

So im trying to decrypt a string I cryptographed with JS in Python. I used the aes-js library. I get this: caba6777379a00d12dcd0447015cd4dbcba649857866072d. This is my JS code:
var key = aesjs.utils.utf8.toBytes("ThisKeyIs16Bytes");
console.log(`Key (bytes): ${key}`);
var text = 'psst... this is a secret';
var textBytes = aesjs.utils.utf8.toBytes(text);
var aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(5));
var encryptedBytes = aesCtr.encrypt(textBytes);
var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(`Hex: ${key}`);
I've tried a few things in python, but this is what I currently have:
from Crypto.Cipher import AES
ciphered_data = bytearray.fromhex('caba6777379a00d12dcd0447015cd4dbcba649857866072d')
key = b'ThisKeyIs16Bytes'
cipher = AES.new(key, AES.MODE_CTR)
original_data = cipher.decrypt(ciphered_data)
print(original_data.decode("utf-8", errors="ignore"))
But I just recieve a mess.=*լ☻ve↕-:tQɊ#¶.
The CTR mode is used. In the Pyton code the initialization of the counter is missing, i.e. the definition of the correct start value, e.g.
...
cipher = AES.new(key, AES.MODE_CTR, nonce = b'', initial_value = 5)
...
or alternatively using a Counter object:
from Crypto.Util import Counter
...
counter = Counter.new(128, initial_value = 5)
cipher = AES.new(key, AES.MODE_CTR, counter = counter)
...
With one of these two changes the decryption works.

TripleDES encryption - c# and javascript differences

I have data encrypted in c#, and need to put together a demo of how to decrypt in javascript. (Note, this is just for a demo - we will not be putting keys into client side code!)
I cannot get the settings right using Crypto-js - I've tried lots of variations, but am getting nowhere.
I cannot change the c# code, so need to get the javascript to work the same way.
Current skeleton code is as follows -
C# (encrypt)
var EncryptionKey = Encoding.ASCII.GetBytes("14ggh11dd3fvv4n4aabb33a3");
var IV = Encoding.ASCII.GetBytes("312a44de");
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = EncryptionKey;
tdes.IV = IV;
byte[] buffer = Encoding.ASCII.GetBytes("test");
var ciphertext = Convert.ToBase64String(tdes.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
Console.WriteLine(HttpUtility.UrlEncode(ciphertext));
which generates the cipher VrB1Ih0Ll%2fQ%3d
javascript (decrypt)
function decryptByDESModeCBC(ciphertext) {
var key = '14ggh11dd3fvv4n4aabb33a3';
var iv = '312a44de'
ciphertext = decodeURIComponent(ciphertext);
var keyBytes = CryptoJS.enc.Utf8.parse(key);
var ivBytes = CryptoJS.enc.Utf8.parse(iv);
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
}, keyBytes, {
iv:ivBytes,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
function test()
{
console.log(decryptByDESModeCBC("VrB1Ih0Ll%2fQ%3d"));
}
Expected result is "test", but I am getting blank.
Any pointers would be great.
As answered by #Topaco in the comments
I needed to use CryptoJS.TripleDES instead of CryptoJS.DES

AES 128 Decryption: First char of CryptoJS.enc.Latin1 is malformed

I have a string which is encoded and need to decrypt it. I have used the Crypto JS and after certain research, I could reach to below solution.
data = "+JdTb5BOloxaBHQlTw6NPLNV9lZix1OwhR3HF3IRtu2pdg/TLkrTw6Xu4JpKFlxE+zgOZavj0UynSZ+ojxmDXRbUlfyOc4YAncJVMXr28/AtfxZkNQoHbPIo7WxcSdidNE2k+DHZFcNNKOzYnvL1oDN4ezecs8Vo7K6vC5ZFLPUylXsi5sPsGye+TBbauPX+/wXa3hWUJVMNk6HUghW7l4N5Ei7HnrxLkFSFnz+9YUKYbFMEgV6wd9debHrpyytVhA3x2+Eyn5KnQ7iNJKQsNw==";
key = "062ec23950a55b9f8b21b0f9d45ca853";
// Decode the base64 data so we can separate iv and crypt text.
var rawData = atob(data);
var iv = rawData.substring(0,32);
var crypttext = rawData.substring(32);
// Decrypt...
var plaintextArray = CryptoJS.AES.decrypt(
{ ciphertext: CryptoJS.enc.Latin1.parse(crypttext) },
CryptoJS.enc.Hex.parse(key),
{ iv: CryptoJS.enc.Latin1.parse(iv) }
);
var test = CryptoJS.enc.Latin1.stringify(plaintextArray);
console.log(test.toString())
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/aes.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
The output of the above is
8«ÊWÒϬR¶jÛWY#ESPONSE_TEXT>
<RESULT>OK</RESULT>
<RESULT_CODE>-1</RESULT_CODE>
<TERMINATION_STATUS>SUCCESS</TERMINATION_STATUS>
<COUNTER>2</COUNTER>
</RESPONSE>
Instead of
<RESPONSE_TEXT>
<RESULT>OK</RESULT>
<RESULT_CODE>-1</RESULT_CODE>
<TERMINATION_STATUS>SUCCESS</TERMINATION_STATUS>
<COUNTER>2</COUNTER>
</RESPONSE>
I am not able to find why 8«ÊWÒϬR¶jÛWY is been coming to the result. Kindly help to find the missing thread.
Use - CryptoJS.lib.WordArray.random(128/8) to generate iv
data = "+JdTb5BOloxaBHQlTw6NPH2KFaA1mUL2vEuOqHmteozJutLfH1fQrDn+OE8Y1LgoFNqTjpuELCLB1noWbQ9Dz2g6NcD2vPAd4okiYArXnz+YKhVaGcqw+FTThjTWadMD/KvpzZ7SlxBh7HpCbZ/KMmxsOOnuk2F8pVEV3pkJMUgxV36c/iN9C+aRHPt95XRKzfU5ISaoBIq+/9K4WzW6i8yI8r6sdyRDoRc2q/EXuvX5666vdP1yojm2yhaL+1EwgkkYRn+GLyYuzFN1yCi+OA==";
key = "062ec23950a55b9f8b21b0f9d45ca853";
// Decode the base64 data so we can separate iv and crypt text.
var rawData = atob(data);
var iv = CryptoJS.lib.WordArray.random(128/8);
var crypttext = rawData;
// Decrypt...
var plaintextArray = CryptoJS.AES.decrypt(
{
ciphertext: CryptoJS.enc.Latin1.parse(crypttext)
},
CryptoJS.enc.Hex.parse(key),
{
iv: CryptoJS.enc.Latin1.parse(iv),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}
);
var decrypted = CryptoJS.enc.Latin1.stringify(plaintextArray);
console.log(decrypted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
Fiddle - https://jsfiddle.net/guptasanchit90dev/p00fhmp4/

Porting C# AES Encryption to Javascript for Node.js

Looking for help to port below C# code into Node.js using crypto or equivalent module.
private string password="FlU4c8yQKLkYuFwsgyU4LFeIf7m3Qwy+poMBdULEMqw=";
private byte[] salt = Encoding.ASCII.GetBytes("##oEDA102ExChAnGe99#$#");
Aes encryptor = Aes.Create();
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, salt);
string pdbStr = Convert.ToBase64String(pdb.GetBytes(32));
Console.WriteLine(pdbStr);
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
Tried porting into javascript as below, but the resulted value are not the same.
var password = "FlU4c8yQKLkYuFwsgyU4LFeIf7m3Qwy+poMBdULEMqw=";
var salt = "##oEDA102ExChAnGe99#$#";
var pdbBytes = crypto.pbkdf2Sync(Buffer.from(password, 'base64'), new Buffer(salt, 'base64'), 1000, 32);
var pdbStr = new Buffer(pdbBytes).toString('base64')
console.log("pdbStr", pdbStr);
Console output:
C# - GZlqgdLbMQ753dTmx1nlJ6HgdabTjW1CeCSoIYkLM4E=
JS - tuDsZJEEwxyXP7RvuYVxGmDy20AvMJAqkLoXX78sEU8=
Any help is much appreciated. Thanks.
these codes parts are generating same the result.
but i did not get 'GZlqgdLbMQ753dTmx1nlJ6HgdabTjW1CeCSoIYkLM4E=' result from c#.
c#
byte[] password= Convert.FromBase64String("FlU4c8yQKLkYuFwsgyU4LFeIf7m3Qwy+poMBdULEMqw=");
byte[] salt = Encoding.ASCII.GetBytes("##oEDA102ExChAnGe99#$#");
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password,salt,1000);
string pdbStr =Convert.ToBase64String(pdb.GetBytes(32));
Console.WriteLine(pdbStr);
//outpu : RMqDMSV6d8uT2NicGM212r3KMFt7ZsOI2q8+0Rr0WZQ=
JS
var crypto = require("crypto");
var password = "FlU4c8yQKLkYuFwsgyU4LFeIf7m3Qwy+poMBdULEMqw=";
var salt = "##oEDA102ExChAnGe99#$#";
crypto.DEFAULT_ENCODING = 'base64';
var pdbBytes = crypto.pbkdf2Sync(new Buffer(password,'base64'), salt, 1000, 32,'sha1');
var pdbStr = new Buffer(pdbBytes).toString()
console.log("pdbStr", pdbStr);
//outpu : RMqDMSV6d8uT2NicGM212r3KMFt7ZsOI2q8+0Rr0WZQ=

Encrypt string with Blowfish in NodeJS

I need to encrypt a string but I almost get the output I desire, I read online that it has something to do with padding and iv_vector at the end to complete for the remaining 8 bytes to be same length as txtToEncrypt.
I'm using this library https://github.com/agorlov/javascript-blowfish
// function in Java that I need
// javax.crypto.Cipher.getInstance("Blowfish/CBC/NoPadding").doFinal("spamshog")
var iv_vector = "2278dc9wf_178703";
var txtToEncrypt = "spamshog";
var bf = new Blowfish("spamshog", "cbc");
var encrypted = bf.encrypt(txtToEncrypt, iv_vector);
console.log(bf.base64Encode(encrypted));
Actual output: /z9/n0FzBJQ=
What I need: /z9/n0FzBJRGS6nPXso5TQ==
If anyone has any clue please let me know. I searched all over Google all day.
Finally, here is how to encrypt a string in NodeJS with Blowfish
// Module crypto already included in NodeJS
var crypto = require('crypto');
var iv = "spamshog";
var key = "spamshog";
var text = "2278dc9wf_178703";
var decipher = crypto.createCipheriv('bf-cbc', key, iv);
decipher.setAutoPadding(false);
var encrypted = decipher.update(text, 'utf-8', "base64");
encrypted += decipher.final('base64');
console.log(encrypted);
Returns: /z9/n0FzBJRGS6nPXso5TQ==

Categories

Resources