I have code in C# but I need to pass in TypeScript. In C# I use this library using System.Security.Cryptography; and in TypeScript I use this library var CryptoJS = require("crypto-js"). I have the first part of the code (SHA256 encryptation) but I need the second part(Aes encryptation).
This is the C# Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
//now i have pass this function in typescript and the result is the same
public string Encrypt(string plainText, string password)
{
var bytesToBeEncrypted = Encoding.UTF8.GetBytes(plainText);
var passwordBytes = Encoding.UTF8.GetBytes(password);
// Hash the password with SHA256
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
var bytesEncrypted = SecurityEncrypt.Encrypt(bytesToBeEncrypted, passwordBytes);
return Convert.ToBase64String(bytesEncrypted);
}
//i need pass this function in typescript
private static byte[] Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
var saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.KeySize = 256;
AES.BlockSize = 128;
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
And is my typescript code, the function encryptdata() is the same that the first encryptdata() in C#. And the result is the same.
encryptdata(){
var CryptoJS = require("crypto-js");
let messageutf=CryptoJS.enc.Utf8.parse(this.message);
let encryputf=CryptoJS.enc.Utf8.parse(this.encryptKey);
var hashpassword=CryptoJS.SHA256(encryputf);
var hash = CryptoJS.SHA256(messageutf, hashpassword);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
return this._makeqr.makeQr(hashInBase64);
}
Thanks for your help.