I am trying to transpose a c# code to a javascript using cryptojs and in the c# code it uses TripleDESCryptoServiceProvider. I can get everything exactly the values of C# in my javascript code except for the encrypting part. I get a different result on the encryption. Please see my code on c# and javascript.
C# public static string EncryptTxt(string key, string msg, CipherMode mode, Int16 KeyOffSet) { SHA512CryptoServiceProvider sha = new SHA512CryptoServiceProvider(); byte[] newKey = new byte[23];
using (var tdes = new TripleDESCryptoServiceProvider())
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(key));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
byte[] keybyte = sha.ComputeHash(Encoding.UTF8.GetBytes(key));
byte[] newKeyx = new byte[24];
Array.Copy(keybyte, KeyOffSet, newKeyx, 0, newKeyx.Length);
TDESAlgorithm.Key = newKeyx;
TDESAlgorithm.Mode = mode;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(msg);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
javascript
encryptText = () => {
debugger;
const msg = 'Autosweep2Go1:juan:201910181809:12345678';
let key = crypto.enc.Utf8.parse('xxx');
key = crypto.MD5(key);
key.words.push(key.words[0], key.words[1]);
const iv = crypto.enc.Utf8.parse('xxx');
// MD5CryptoServiceProvider
const hashProvider = crypto.MD5(iv);
const TDESKey = this.wordArrayToByteArray(hashProvider, 8);
const keybyte = this.wordArrayToByteArray(crypto.SHA512(iv), 16);
const newKeyx = new Uint8Array(24);
const newkeybyte = keybyte.slice(10, 34);
// Object.assign(newKeyx, newkeybyte);
const TDESAlgorithmKey = newkeybyte;
const DataToEncrypt = this.wordArrayToByteArray(crypto.enc.Utf8.parse(msg), 40);
const dteLength = DataToEncrypt.length;
const encrypted = crypto.TripleDES.encrypt(crypto.enc.Utf8.parse(msg),
crypto.enc.Utf8.parse(newkeybyte),
{
mode: crypto.mode.ECB,
padding: crypto.pad.Pkcs7,
});
const result = this.wordArrayToByteArray(encrypted.ciphertext, dteLength);
const x = this.wordArrayToByteArray(crypto.enc.Utf8.parse(encrypted.toString()), dteLength);
console.log(encrypted);
return encrypted;
}
C# Result
Javasctipt Result
Can you please show me how to do this right. I really appreciate it!