This might be a possible duplicate but I am unable to fix it. Below is my code in C# for tripleDES:
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
class MainClass {
public static void Main (string[] args) {
String encrypt="5241110000602040";
SymmetricAlgorithm sa= SymmetricAlgorithm.Create("TripleDES");
sa.Key= Convert.FromBase64String("FRSF1P3b6fHiW/DXrK8ZJks5KAiyNpP0");
sa.IV=Convert.FromBase64String("YFKA0QlomKY=");
byte[] iba=Encoding.ASCII.GetBytes(encrypt);
MemoryStream mS=new MemoryStream();
ICryptoTransform trans=sa.CreateEncryptor();
byte[] buf= new byte[2049];
CryptoStream cs=new CryptoStream(mS,trans,CryptoStreamMode.Write);
cs.Write(iba,0,iba.Length);
cs.FlushFinalBlock();
Console.WriteLine(Convert.ToBase64String(mS.ToArray()));
}
}
Encrypted value is
Nj7GeyrbJB93HZLplFZwq5HRjxnvZSvU
I want to achieve the same thing with crypto-js library of nodejs. Here is nodejs code of what I tried:
var CryptoJS = require("crypto-js");
var text = "5241110000602040";
var key = "FRSF1P3b6fHiW/DXrK8ZJks5KAiyNpP0";
var options = {
// mode: CryptoJS.mode.ECB,
// padding: CryptoJS.pad.Pkcs7,
iv: CryptoJS.enc.Hex.parse("YFKA0QlomKY=")
};
var textWordArray = CryptoJS.enc.Utf8.parse(text);
var keyHex = CryptoJS.enc.Hex.parse(key);
var encrypted = CryptoJS.TripleDES.encrypt(textWordArray, keyHex, options);
var base64String = encrypted.toString();
console.log('encrypted val: ' + base64String);
Expected output
Nj7GeyrbJB93HZLplFZwq5HRjxnvZSvU
Actual Output
NXSBe9YEiGs5p6VHkzezfdcb5o08bALB
Encrypted value in nodejs is different than C#. What am I doing wrong?
You differently decode key and iv.
In c# you use base64:
sa.Key= Convert.FromBase64String("FRSF1P3b6fHiW/DXrK8ZJks5KAiyNpP0");
sa.IV=Convert.FromBase64String("YFKA0QlomKY=");
in node.js hex:
iv: CryptoJS.enc.Hex.parse("YFKA0QlomKY=")
var key = "FRSF1P3b6fHiW/DXrK8ZJks5KAiyNpP0";
var keyHex = CryptoJS.enc.Hex.parse(key);
Try to use base64 in both cases.