Encrypt string with Blowfish in NodeJS
Asked Answered
S

1

5

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.

Snow answered 20/12, 2016 at 18:9 Comment(7)
What is the strange output you're getting?Denazify
This: /z9/n0FzBJQ=Snow
Gotcha. It's clearly related to the output you're looking for, so that looks like it might be some detail in the module you're using. If you're still stuck later when I have some time I'll look at the back-end code and see if there are any clues.Denazify
The problem is not in this module itself it's just that I need extra bytes (8) at the end of encrypted string. I just converted this code from a reverse engineering of an android app (basically java) for learning purposes and it uses some functions to complete the remaining bytes.Snow
I have almost same issue but different: #38352775Snow
First of all, the author of that library has no idea what he's doing. There is no reason to use code like that. As for your code: Blowfish has a block size of 8 bytes and your IV is 16 bytes, which probably means that the last 8 bytes are ignored.Garganey
There is absolutely no way that your Java code produces 16 bytes of output.Garganey
S
10

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==
Snow answered 24/12, 2016 at 12:34 Comment(1)
Disable setAutoPadding() only works is data length is multiple of the block size, in your case 16 / 8 = 2.Ratcliffe

© 2022 - 2024 — McMap. All rights reserved.