Files
FACULTATE-HEALTHCARE_MANAGER/backend/Infrastructure/Services/Encryption/EncryptionService.cs
T
2024-05-30 15:40:13 +03:00

63 lines
2.0 KiB
C#

using System.Security.Cryptography;
using System.Text;
using Application.Services.Encryption;
using Microsoft.Extensions.Configuration;
namespace Infrastructure.Services.Encryption;
public class EncryptionService : IEncryptionService
{
private readonly byte[] _medicalRecordsKey;
public EncryptionService(IConfiguration configuration)
{
var keyString = configuration["MedicalRecordsKey"];
_medicalRecordsKey = Convert.FromBase64String(keyString); // Ensure the key is correctly formatted and of proper length.
}
public string? Sha256Algorithm(string? password)
{
if (password == null) return null;
using var sha256 = SHA256.Create();
var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
return Convert.ToBase64String(bytes);
}
public byte[] EncryptDocument(byte[] data)
{
using var aesAlg = Aes.Create();
aesAlg.Key = _medicalRecordsKey;
aesAlg.GenerateIV();
using var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using var msEncrypt = new MemoryStream();
// Writing the IV directly to the start of the stream
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (var cryptoStream = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
}
return msEncrypt.ToArray();
}
public byte[] DecryptDocument(byte[] data)
{
using var aesAlg = Aes.Create();
aesAlg.Key = _medicalRecordsKey;
// Extract the IV from the beginning of the data array
var iv = new byte[aesAlg.BlockSize / 8];
Array.Copy(data, 0, iv, 0, iv.Length);
aesAlg.IV = iv;
using var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, iv);
using var msDecrypt = new MemoryStream();
using var cryptoStream = new CryptoStream(new MemoryStream(data, iv.Length, data.Length - iv.Length),
decryptor, CryptoStreamMode.Read);
cryptoStream.CopyTo(msDecrypt);
return msDecrypt.ToArray();
}
}