using System.Security.Cryptography;
using System.Text;
using Keepz_Aes_Encryption.models;
namespace Keepz_Aes_Encryption.utils
{
public static class EncryptionUtils
{
public static string EncryptUsingPublicKey(string data, string publicKey, bool usePkcsPadding = false)
{
string pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----";
using RSA rsa = RSA.Create();
rsa.ImportFromPem(pemPublicKey);
RSAEncryptionPadding padding = usePkcsPadding ? RSAEncryptionPadding.Pkcs1 : RSAEncryptionPadding.OaepSHA256;
byte[] dataBytes = rsa.Encrypt(Encoding.UTF8.GetBytes(data), padding);
return Convert.ToBase64String(dataBytes);
}
public static string DecryptUsingPrivateKey(string encryptedData, string privateKey, bool usePkcsPadding = false)
{
string pemPrivateKey = "-----BEGIN PRIVATE KEY-----\n" + privateKey + "\n-----END PRIVATE KEY-----";
using RSA rsa = RSA.Create();
rsa.ImportFromPem(pemPrivateKey);
RSAEncryptionPadding padding = usePkcsPadding ? RSAEncryptionPadding.Pkcs1 : RSAEncryptionPadding.OaepSHA256;
byte[] encryptedDataBytes = Convert.FromBase64String(encryptedData);
byte[] decryptedDataBytes = rsa.Decrypt(encryptedDataBytes, padding);
return Encoding.UTF8.GetString(decryptedDataBytes);
}
public static EncryptedResponse EncryptWithAes(string data, string publicKey, bool usePkcsPadding = false)
{
using Aes aes = Aes.Create();
aes.KeySize = 256;
aes.GenerateKey();
aes.GenerateIV();
byte[] encryptedDataBytes;
using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
encryptedDataBytes = encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length);
}
string encryptedDataBase64 = Convert.ToBase64String(encryptedDataBytes);
string aesProperties = Convert.ToBase64String(aes.Key) + "." + Convert.ToBase64String(aes.IV);
string encryptedAesProperties = EncryptUsingPublicKey(aesProperties, publicKey, usePkcsPadding);
return new EncryptedResponse(encryptedDataBase64, encryptedAesProperties, true);
}
public static string DecryptWithAes(string encryptedAesProperties, string encryptedData, string privateKey, bool usePkcsPadding = false)
{
string decryptedAesProperties = DecryptUsingPrivateKey(encryptedAesProperties, privateKey, usePkcsPadding);
string[] aesProps = decryptedAesProperties.Split('.');
byte[] aesIV = Convert.FromBase64String(aesProps[1]);
byte[] aesKey = Convert.FromBase64String(aesProps[0]);
using Aes aes = Aes.Create();
aes.Key = aesKey;
aes.IV = aesIV;
byte[] decryptedDataBytes;
using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
{
byte[] encryptedDataBytes = Convert.FromBase64String(encryptedData);
decryptedDataBytes = decryptor.TransformFinalBlock(encryptedDataBytes, 0, encryptedDataBytes.Length);
}
return Encoding.UTF8.GetString(decryptedDataBytes);
}
}
}