I am trying to implement a .net core version of our existing encryption mechanism. my existing encryption is implemented in the below way which is not compatible with .net core
byte[] bytesToBeDecrypted = Convert.FromBase64String(dataToDecrypt);
byte[] saltBytes = new byte[16];
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 256;
var key = new Rfc2898DeriveBytes(GetHashKeyWithSHA256(), saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
AES.Padding = PaddingMode.PKCS7;
using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
return UTF8Encoding.UTF8.GetString(ms.ToArray());
}
}
But there is no direct method to implement this into .net core so i have used AES but it is giving always a portion of expected output
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
byte[] saltBytes = new byte[16];
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(GetHashKeyWithSHA256(), saltBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
var engine = new RijndaelEngine(256);
var blockCipher = new CbcBlockCipher(engine);
var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
var keyParam = new KeyParameter(keyBytes);
var keyParamWithIV = new ParametersWithIV(keyParam, ivStringBytes, 0, 32);
cipher.Init(false, keyParamWithIV);
var comparisonBytes = new byte[cipher.GetOutputSize(cipherTextBytes.Length)];
var length = cipher.ProcessBytes(cipherTextBytes, comparisonBytes, 0);
cipher.DoFinal(comparisonBytes, length);
var nullIndex = comparisonBytes.Length - 1;
while (comparisonBytes[nullIndex] == (byte)0)
nullIndex--;
comparisonBytes = comparisonBytes.Take(nullIndex + 1).ToArray();
var result = Encoding.UTF8.GetString(comparisonBytes, 0, comparisonBytes.Length);
return result;
}
private static byte[] GetHashKeyWithSHA256()
{
string key = "2893562938q562bdx3whegujfgwehjgfewygfr3287t4238rb2332r7y234723byr54h";
byte[] passwordBytes = Encoding.UTF8.GetBytes(key);
return SHA256.Create().ComputeHash(passwordBytes);
}
Test Input : SxXrRvUEqYvRATVswgrJVQ9EtS6AHJVo6wV+mhQpW+t9a0GPDxvatC9JUYEJ5z/vrPD0MBxyW3dBfrlgec2LqA==
Appreciate if somebody helps me to identify the issue