diff --git a/README.md b/README.md index 6965cd2..238a4b2 100644 --- a/README.md +++ b/README.md @@ -4,14 +4,14 @@ A C# library for encryption and decryption. ## Overview -The Encryption library provides a set of methods for encrypting and decrypting data using the Advanced Encryption Standard (AES) algorithm, and other algorithm. It is designed to be easy to use and can be integrated into C# applications that require secure data transmission or storage. - +The SafeCrypt library provides a set of methods for encrypting and decrypting data using various encryption algorithms, +including the Advanced Encryption Standard (AES) and RSA (Rivest�Shamir�Adleman). +It is designed to be easy to use and can be integrated into C# applications that require secure data transmission or storage. ## Table of Contents - [Installation](#installation) -- [Usage](#usage) -- [API Reference](#api-reference) -- [Examples](#examples) +- [AES Encryption and Decryption usage](#usage) +- [RSA Encryption and Decryption usage](#rsa) - [Contributing](#contributing) - [License](#license) @@ -34,28 +34,25 @@ To use the SafeCrypt library in your C# project, follow these steps: Now, you can reference the SafeCrypt library in your C# project. -## Basic Usage +## Usage -To use the library in your C# application, instantiate the `AesEncryption` or `AesDecryption` class and call the provided methods. Here's a simple example: +To use the AES encryption in your C# application, +instantiate the `AesEncryption` or `AesDecryption` class and call the provided methods. Here's a simple example: ```csharp -using SafeCrypt.AESDecryption; -using SafeCrypt.AESEncryption; +using SafeCrypt.AES; using SafeCrypt.Models; class Program { static async Task Main() { - var aesEncryptor = new AesEncryption(); - var encryptedData = await aesEncryptor.EncryptToBase64StringAsync("Hello, World!", "gdjdtsraewsuteastwerse==" + var encryptedData = await Aes.EncryptToBase64StringAsync("Hello, World!", "gdjdtsraewsuteastwerse==" Console.WriteLine($"Encrypted Data: {encryptedData.EncryptedData}"); Console.WriteLine($"Initialization Vector: {encryptedData.Iv}"); - - var aesDecryptor = new AesDecryption(); - + var parameterToDecrypt = new DecryptionParameters { DataToDecrypt = encryptedData.EncryptedData, @@ -64,7 +61,7 @@ class Program }; - var data = await aesDecryptor.DecryptFromBase64StringAsync(parameterToDecrypt) + var data = await Aes.DecryptFromBase64StringAsync(parameterToDecrypt) Console.WriteLine($"Decrypted Data: {data.DecryptedData}"); Console.WriteLine($"Initialization Vector: {data.Iv}"); @@ -74,8 +71,7 @@ class Program ------------------------------------------------------------------------------------------------------- -using SafeCrypt.AESDecryption; -using SafeCrypt.AESEncryption; +using SafeCrypt.AES; using SafeCrypt.Models; class Program @@ -94,9 +90,8 @@ class Program SecretKey = secret }; - var encryptor = new AesEncryption(); - var response = await encryptor.EncryptToBase64StringAsync(encryptionParam.DataToEncrypt, secret); + var response = await Aes.EncryptToBase64StringAsync(encryptionParam.DataToEncrypt, secret); Console.WriteLine(response.EncryptedData); Console.WriteLine(response.Iv); @@ -112,8 +107,7 @@ class Program }; - var decryptor = new AesDecryption(); - var decryptionData = await decryptor.DecryptFromBase64StringAsync(decryptorParam); + var decryptionData = await Aes.DecryptFromBase64StringAsync(decryptorParam); Console.WriteLine(decryptionData.DecryptedData); Console.WriteLine(decryptionData.Iv); @@ -122,6 +116,14 @@ class Program } ``` + +## Rsa +This library provides a straightforward implementation of RSA encryption and decryption in C# using the .NET `RSACryptoServiceProvider`. +It includes methods for generating RSA key pairs, encrypting data with a public key, and decrypting data with a private key. + +For more details on RSA Encryption, check the [Rsa.md](doc/Rsa.md) document. + + ## Contributing If you would like to contribute to the development of the SafeCrypt library, follow these steps: diff --git a/doc/Rsa.md b/doc/Rsa.md new file mode 100644 index 0000000..0d9a2d0 --- /dev/null +++ b/doc/Rsa.md @@ -0,0 +1,90 @@ +# RSA Encryption and Decryption + +## Overview + +This library provides a straightforward implementation of RSA encryption and decryption in C# using the .NET `RSACryptoServiceProvider`. +It includes methods for generating RSA key pairs, encrypting data with a public key, and decrypting data with a private key. + +## Table of Contents + +- [Usage](#usage) + - [Generate RSA Keys](#generate-rsa-keys) + - [Encrypt and Decrypt using RSA](#encrypt-and-decrypt-using-rsa) + +## Usage + +### Generate RSA Keys + +```csharp +using SafeCrypt.Helpers; +using SafeCrypt.RsaEncryption; + +var rsaKeyPair = KeyGenerators.GenerateRsaKeys(2048); + +string rsaPublicKey = rsaKeyPair.Item1; +string rsaPrivateKey = rsaKeyPair.Item2; + +Console.WriteLine($"Public Key: {rsaPublicKey}"); +Console.WriteLine($"Private Key: {rsaPrivateKey}"); +``` + +### Encrypt and Decrypt using RSA + +```csharp + using SafeCrypt.RsaEncryption; + + // Encrypt + string originalData = "Hello, RSA Encryption!"; + + var encryptionModel = new RsaEncryptionParameters + { + DataToEncrypt = originalData, + PublicKey = rsaPublicKey, + }; + + var encryptedData = await Rsa.EncryptAsync(encryptionModel); + + Console.WriteLine($"Original Data: {originalData}"); + Console.WriteLine("Encrypted Data: " + BitConverter.ToString(encryptedData.EncryptedData)); + + // Convert encrypted byte array to Base64 string + string encryptedDataConvertedString = Convert.ToBase64String(encryptedData.EncryptedData); + + // Convert string back to byte array for decryption + byte[] convertedBytes = Convert.FromBase64String(encryptedDataConvertedString); + + bool arraysAreEqual = StructuralComparisons.StructuralEqualityComparer.Equals(encryptedData.EncryptedData, convertedBytes); + Console.WriteLine("Original and converted byte arrays are equal: " + arraysAreEqual); // should return true + + + + // Decrypt + var decryptionModel = new RsaDecryptionParameters + { + DataToDecrypt = convertedBytes, // encryptedData.EncryptedData + PrivateKey = rsaPrivateKey, + }; + + var decryptedData = await Rsa.DecryptAsync(decryptionModel); + + // if Error occurs during encryption + if (decryptedData.Errors.Count > 0) + { + Console.WriteLine("Decryption Errors:"); + foreach (var error in decryptedData.Errors) + { + Console.WriteLine(error); + } + } + else + { + Console.WriteLine($"Decrypted Data: {decryptedData.DecryptedData}"); + } + +// Note: The return type from Rsa.EncryptAsync is `EncryptionResult`, and Rsa.DecryptAsync is `DecryptionResult`. +// Both models include a list of errors encountered during encryption/decryption. + +``` +## Contributing + +Contributions are welcome! Feel free to open issues, submit pull requests, or provide feedback. \ No newline at end of file diff --git a/src/SafeCrypt.Lib/Encryption/AesEncryption/BaseAesEncryption.cs b/src/SafeCrypt.Lib/Encryption/AesEncryption/BaseAesEncryption.cs index e4d1da7..46ff7d7 100644 --- a/src/SafeCrypt.Lib/Encryption/AesEncryption/BaseAesEncryption.cs +++ b/src/SafeCrypt.Lib/Encryption/AesEncryption/BaseAesEncryption.cs @@ -6,7 +6,7 @@ namespace SafeCrypt.AesEncryption { - public class BaseAesEncryption + public static class BaseAesEncryption { /// /// Encrypts the provided data using the Advanced Encryption Standard (AES) algorithm. diff --git a/src/SafeCrypt.Lib/Encryption/AesEncryption/Decrypting.cs b/src/SafeCrypt.Lib/Encryption/AesEncryption/Decrypting.cs index 62cf941..71aae3f 100644 --- a/src/SafeCrypt.Lib/Encryption/AesEncryption/Decrypting.cs +++ b/src/SafeCrypt.Lib/Encryption/AesEncryption/Decrypting.cs @@ -5,9 +5,9 @@ using System.Security.Cryptography; using System.Threading.Tasks; -namespace SafeCrypt.AESDecryption +namespace SafeCrypt.AES { - public class AesDecryption : BaseAesEncryption + public static partial class Aes { /// /// Asynchronously decrypts data from a hexadecimal string using the specified decryption parameters and cipher mode. @@ -19,7 +19,7 @@ public class AesDecryption : BaseAesEncryption /// The task result is a object containing the decrypted data, IV, and secret key. /// If decryption fails, the object will contain error information. /// - public async Task DecryptFromHexStringAsync(DecryptionParameters param, CipherMode mode = CipherMode.CBC) + public static async Task DecryptFromHexStringAsync(DecryptionParameters param, CipherMode mode = CipherMode.CBC) { var responseData = new DecryptionData(); @@ -55,7 +55,7 @@ public async Task DecryptFromHexStringAsync(DecryptionParameters Data = param.DataToDecrypt.HexadecimalStringToByteArray() }; - var response = await DecryptAsync(byteEncryptionParameters, mode); + var response = await BaseAesEncryption.DecryptAsync(byteEncryptionParameters, mode); return new DecryptionData { @@ -75,7 +75,7 @@ public async Task DecryptFromHexStringAsync(DecryptionParameters /// The task result is a object containing the decrypted data, IV, and secret key. /// If decryption fails, the object will contain error information. /// - public async Task DecryptFromBase64StringAsync(DecryptionParameters param, CipherMode mode = CipherMode.CBC) + public static async Task DecryptFromBase64StringAsync(DecryptionParameters param, CipherMode mode = CipherMode.CBC) { var responseData = new DecryptionData(); @@ -103,7 +103,7 @@ public async Task DecryptFromBase64StringAsync(DecryptionParamet Data = Convert.FromBase64String(param.DataToDecrypt) }; - var response = await DecryptAsync(byteDecryptionParameters, mode); + var response = await BaseAesEncryption.DecryptAsync(byteDecryptionParameters, mode); return new DecryptionData { @@ -121,7 +121,7 @@ public async Task DecryptFromBase64StringAsync(DecryptionParamet } - private void NullChecks(string data, string secretKey, string iv) + private static void NullChecks(string data, string secretKey, string iv) { if (data == null || data.Length <= 0) throw new ArgumentNullException(nameof(data)); @@ -133,13 +133,13 @@ private void NullChecks(string data, string secretKey, string iv) throw new ArgumentNullException(nameof(iv)); } - private (byte[], byte[]) ConvertKeysToBytesAndGetKeys(string secretKey, string iv) + private static (byte[], byte[]) ConvertKeysToBytesAndGetKeys(string secretKey, string iv) { return (secretKey.ConvertKeysToBytes(), iv.ConvertKeysToBytes()); } - private void AddError(DecryptionData responseData, string error) + private static void AddError(DecryptionData responseData, string error) { responseData.HasError = true; responseData.Errors.Add(error); diff --git a/src/SafeCrypt.Lib/Encryption/AesEncryption/Encrypting.cs b/src/SafeCrypt.Lib/Encryption/AesEncryption/Encrypting.cs index 75fa8ae..b68b94c 100644 --- a/src/SafeCrypt.Lib/Encryption/AesEncryption/Encrypting.cs +++ b/src/SafeCrypt.Lib/Encryption/AesEncryption/Encrypting.cs @@ -5,9 +5,9 @@ using System.Security.Cryptography; using System.Threading.Tasks; -namespace SafeCrypt.AESEncryption +namespace SafeCrypt.AES { - public class AesEncryption : BaseAesEncryption + public static partial class Aes { /// /// Asynchronously encrypts the provided data using the specified secret key and initialization vector (IV). @@ -23,7 +23,7 @@ public class AesEncryption : BaseAesEncryption /// The secret key used for encryption. /// The initialization vector used for encryption. /// The encrypted data as a byte array. - public async Task EncryptToHexStringAsync(EncryptionParameters param, CipherMode mode = CipherMode.CBC) + public static async Task EncryptToHexStringAsync(EncryptionParameters param, CipherMode mode = CipherMode.CBC) { var responseData = new EncryptionData(); @@ -52,7 +52,7 @@ public async Task EncryptToHexStringAsync(EncryptionParameters p Data = param.DataToEncrypt.ConvertToHexString().HexadecimalStringToByteArray() }; - var response = await EncryptAsync(byteEncryptionParameters, mode); + var response = await BaseAesEncryption.EncryptAsync(byteEncryptionParameters, mode); return new EncryptionData { @@ -84,7 +84,7 @@ public async Task EncryptToHexStringAsync(EncryptionParameters p /// /// Thrown if the base64secretKey is not a valid Base64-encoded string. /// - public async Task EncryptToBase64StringAsync(string dataToBeEncrypted, string base64secretKey, CipherMode mode = CipherMode.CBC) + public static async Task EncryptToBase64StringAsync(string dataToBeEncrypted, string base64secretKey, CipherMode mode = CipherMode.CBC) { // validate is base64 if (!Validators.IsBase64String(base64secretKey)) @@ -104,7 +104,7 @@ public async Task EncryptToBase64StringAsync(string dataToBeEncr Data = dataToBeEncrypted.ConvertToHexString().HexadecimalStringToByteArray() }; - var response = await EncryptAsync(byteEncryptionParameters, mode); + var response = await BaseAesEncryption.EncryptAsync(byteEncryptionParameters, mode); return new EncryptionData { @@ -114,7 +114,7 @@ public async Task EncryptToBase64StringAsync(string dataToBeEncr }; } - private EncryptionData ValidateEncryptionParameters(EncryptionParameters param) + private static EncryptionData ValidateEncryptionParameters(EncryptionParameters param) { var responseData = new EncryptionData(); @@ -134,7 +134,7 @@ private EncryptionData ValidateEncryptionParameters(EncryptionParameters param) return responseData; } - private void NullChecks(string data, string secretKey) + private static void NullChecks(string data, string secretKey) { if (data == null || data.Length <= 0) throw new ArgumentNullException(nameof(data)); @@ -143,7 +143,7 @@ private void NullChecks(string data, string secretKey) throw new ArgumentNullException(nameof(secretKey)); } - private void AddError(EncryptionData responseData, string error) + private static void AddError(EncryptionData responseData, string error) { responseData.HasError = true; responseData.Errors.Add(error); diff --git a/src/SafeCrypt.Lib/Encryption/RsaEncryption/Models/Encrypt/RsaEncryptionParameters.cs b/src/SafeCrypt.Lib/Encryption/RsaEncryption/Models/Encrypt/RsaEncryptionParameters.cs new file mode 100644 index 0000000..d688ff6 --- /dev/null +++ b/src/SafeCrypt.Lib/Encryption/RsaEncryption/Models/Encrypt/RsaEncryptionParameters.cs @@ -0,0 +1,34 @@ +using System.ComponentModel.DataAnnotations; + +namespace SafeCrypt.RsaEncryption +{ + public sealed class RsaEncryptionParameters : IEncryptionData + { + /// + /// Gets or sets the public key for RSA encryption. + /// + [Required] + public string PublicKey { get; set; } + + /// + /// Gets or sets the data to be encrypted using RSA. + /// + [Required] + public string DataToEncrypt { get; set; } + } + + public sealed class RsaDecryptionParameters + { + /// + /// Gets or sets the public key for RSA encryption. + /// + [Required] + public string PrivateKey { get; set; } + + /// + /// Gets or sets the data to be encrypted using RSA. + /// + [Required] + public byte[] DataToDecrypt { get; set; } + } +} diff --git a/src/SafeCrypt.Lib/Encryption/RsaEncryption/Models/RsaEncryptionResult.cs b/src/SafeCrypt.Lib/Encryption/RsaEncryption/Models/RsaEncryptionResult.cs new file mode 100644 index 0000000..95d21d8 --- /dev/null +++ b/src/SafeCrypt.Lib/Encryption/RsaEncryption/Models/RsaEncryptionResult.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace SafeCrypt.RsaEncryption.Models +{ + public class RsaEncryptionResult + { + /// + /// Gets or sets the encrypted data. + /// + public byte[] EncryptedData { get; set; } + + /// + /// Gets or sets the list of errors encountered during encryption. + /// + public List Errors { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public RsaEncryptionResult() + { + Errors = new List(); + } + } + + public class RsaDecryptionResult + { + /// + /// Gets or sets the encrypted data. + /// + public byte[] DecryptedData { get; set; } + + /// + /// Gets or sets the list of errors encountered during encryption. + /// + public List Errors { get; set; } + + ///// + ///// Gets or sets the public key used for encryption. + ///// + //public string PublicKey { get; set; } + + /// + /// Gets or sets the private key used for encryption. + /// + public string PrivateKey { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public RsaDecryptionResult() + { + Errors = new List(); + } + } + + public class EncryptionResult + { + /// + /// Gets or sets the list of errors encountered during encryption. + /// + public List Errors { get; set; } + + /// + /// Gets or sets the encrypted data. + /// + public byte[] EncryptedData { get; set; } + + public EncryptionResult() + { + Errors = new List(); + } + } + + public class DecryptionResult + { + /// + /// Gets or sets the list of errors encountered during encryption. + /// + public List Errors { get; set; } + + /// + /// Gets or sets the encrypted data. + /// + public string DecryptedData { get; set; } + + public DecryptionResult() + { + Errors = new List(); + } + } +} diff --git a/src/SafeCrypt.Lib/Encryption/RsaEncryption/Rsa.cs b/src/SafeCrypt.Lib/Encryption/RsaEncryption/Rsa.cs new file mode 100644 index 0000000..22963f4 --- /dev/null +++ b/src/SafeCrypt.Lib/Encryption/RsaEncryption/Rsa.cs @@ -0,0 +1,75 @@ +using System; +using System.Text; +using System.Threading.Tasks; +using SafeCrypt.RsaEncryption.Models; + +namespace SafeCrypt.RsaEncryption +{ + + + public static class Rsa + { + /// + /// Asynchronously encrypts the specified data using RSA encryption. + /// + /// The parameters for RSA encryption. + /// An containing the encrypted data, and errors (if any). + public static async Task EncryptAsync(RsaEncryptionParameters model) + { + var result = new EncryptionResult(); + + if(string.IsNullOrWhiteSpace(model.DataToEncrypt)) + { + result.Errors.Add($"Data cannot be null {nameof(model.DataToEncrypt)}"); + return result; + } + + if (string.IsNullOrWhiteSpace(model.PublicKey)) + { + result.Errors.Add($"PublicKey cannot be null {nameof(model.PublicKey)}"); + return result; + } + + // asynchronously perform RSA encryption + var data = await RsaEncryption.EncryptAsync(model.DataToEncrypt, model.PublicKey); + + if(data.Errors.Count > 0) + { + result.Errors.AddRange(data.Errors); + return result; + } + + result.EncryptedData = data.EncryptedData; + return result; + } + + public static async Task DecryptAsync(RsaDecryptionParameters model) + { + var result = new DecryptionResult(); + + if(model.DataToDecrypt == null) + { + result.Errors.Add($"DataToDecrypt cannot be null {nameof(model.DataToDecrypt)}"); + return result; + } + + if (string.IsNullOrWhiteSpace(model.PrivateKey)) + { + result.Errors.Add($"PrivateKey cannot be null {nameof(model.PrivateKey)}"); + return result; + } + + // asynchronously perform RSA encryption + var data = await RsaEncryption.DecryptAsync(model.DataToDecrypt, model.PrivateKey); + + if (data.Errors.Count > 0) + { + result.Errors.AddRange(data.Errors); + return result; + } + + result.DecryptedData = Encoding.UTF8.GetString(data.DecryptedData); + return result; + } + } +} diff --git a/src/SafeCrypt.Lib/Encryption/RsaEncryption/RsaEncryption.cs b/src/SafeCrypt.Lib/Encryption/RsaEncryption/RsaEncryption.cs new file mode 100644 index 0000000..a5cd195 --- /dev/null +++ b/src/SafeCrypt.Lib/Encryption/RsaEncryption/RsaEncryption.cs @@ -0,0 +1,89 @@ +using System.Security.Cryptography; +using System.Text; +using System; +using System.Threading.Tasks; +using SafeCrypt.RsaEncryption.Models; + +namespace SafeCrypt.RsaEncryption +{ + internal static class RsaEncryption + { + /// + /// Asynchronously encrypts the provided data using the RSA (Rivest–Shamir–Adleman) algorithm. + /// + /// The data to be encrypted. + /// The public key used for encryption. + /// + /// A task representing the asynchronous operation that, upon completion, + /// returns an containing the encrypted data. + /// + /// + /// This method uses the RSA algorithm to encrypt the input data with the provided public key. + /// The encryption is performed asynchronously using . + /// + /// The data to be encrypted. + /// The public key used for encryption. + /// + /// A task representing the asynchronous operation that, upon completion, + /// returns an containing the encrypted data. + /// + internal static async Task EncryptAsync(string data, string publicKey) + { + var result = new RsaEncryptionResult(); + + try + { + var encryptedData = await Task.Run(() => + { + using (var rsa = new RSACryptoServiceProvider()) + { + rsa.FromXmlString(publicKey); + byte[] dataBytes = Encoding.UTF8.GetBytes(data); + return rsa.Encrypt(dataBytes, false); + } + }); + + result.EncryptedData = encryptedData; + } + catch (Exception ex) + { + result.Errors.Add(ex.Message); + } + + return result; + } + + /// + /// Decrypts data using RSA private key. + /// + /// The encrypted data. + /// The RSA private key. + /// The decrypted data. + internal static async Task DecryptAsync(byte[] encryptedData, string privateKey) + { + var result = new RsaDecryptionResult(); + + try + { + var decryptedData = await Task.Run(() => + { + using (var rsa = new RSACryptoServiceProvider()) + { + rsa.FromXmlString(privateKey); + byte[] dataBytes = encryptedData; + return rsa.Decrypt(encryptedData, false); + } + }); + + result.DecryptedData = decryptedData; + + } + catch (Exception ex) + { + result.Errors.Add(ex.Message); + } + + return result; + } + } +} diff --git a/src/SafeCrypt.Lib/Helpers/KeyGenerators.cs b/src/SafeCrypt.Lib/Helpers/KeyGenerators.cs index 44a2c5a..3625465 100644 --- a/src/SafeCrypt.Lib/Helpers/KeyGenerators.cs +++ b/src/SafeCrypt.Lib/Helpers/KeyGenerators.cs @@ -67,5 +67,33 @@ public static string GenerateAesSecretKey(int keySize) return Convert.ToBase64String(aesAlg.Key); } } + + /// + /// Generates a pair of RSA public and private keys with the specified key size. + /// + /// The size of the key pair (e.g., 1024, 2048 bits). + /// + /// A containing the generated RSA public and private keys. + /// Item1 represents the public key, and Item2 represents the private key. + /// + /// + /// The generated keys are in XML format. The public key does not include the private key, + /// while the private key includes both public and private components. + /// + /// The size of the key pair (e.g., 1024, 2048 bits). + /// A tuple containing the generated RSA public and private keys. + /// + /// Thrown if an error occurs during key generation. + /// + public static Tuple GenerateRsaKeys(int keySize) + { + using (var rsa = new RSACryptoServiceProvider(keySize)) + { + string publicKey = rsa.ToXmlString(false); // Don't include private key + string privateKey = rsa.ToXmlString(true); // Include private key + + return new Tuple(publicKey, privateKey); + } + } } } diff --git a/src/SafeCrypt.Lib/Interface/IEncryptionData.cs b/src/SafeCrypt.Lib/Interface/IEncryptionData.cs new file mode 100644 index 0000000..b0418df --- /dev/null +++ b/src/SafeCrypt.Lib/Interface/IEncryptionData.cs @@ -0,0 +1,7 @@ +namespace SafeCrypt +{ + internal interface IEncryptionData + { + string DataToEncrypt { get; set; } + } +} diff --git a/src/SafeCrypt.Test/Program.cs b/src/SafeCrypt.Test/Program.cs index 812e804..9a69938 100644 --- a/src/SafeCrypt.Test/Program.cs +++ b/src/SafeCrypt.Test/Program.cs @@ -1,17 +1,15 @@ // See https://aka.ms/new-console-template for more information -using SafeCrypt.AESDecryption; -using SafeCrypt.AESEncryption; +using SafeCrypt.AES; using SafeCrypt.Models; var dataToEncrypt = "Data to Encrypt"; var secret = "hghjuytsdfraestwsgtere=="; // Encryption process -var encryptor = new AesEncryption(); // this method generates a random IV key for the encryption process // the IV is returned in the response with other properties -var response = await encryptor.EncryptToBase64StringAsync(dataToEncrypt, secret); +var response = await Aes.EncryptToBase64StringAsync(dataToEncrypt, secret); Console.WriteLine("............Encryption Started............"); @@ -28,13 +26,11 @@ DataToDecrypt = response.EncryptedData }; -var decryptor = new AesDecryption(); -var decryptionData = await decryptor.DecryptFromBase64StringAsync(decryptorParam); +var decryptionData = await Aes.DecryptFromBase64StringAsync(decryptorParam); Console.WriteLine("............Decryption Started............"); Console.WriteLine($"Decrypted data: {decryptionData.DecryptedData}"); Console.WriteLine($"IV key: {decryptionData.Iv}"); Console.WriteLine($"Secret key: {decryptionData.SecretKey}"); - -Console.WriteLine("Hello, World!"); +Console.ReadLine(); diff --git a/src/SafeCrypt.Test/Usage/RsaUsage.cs b/src/SafeCrypt.Test/Usage/RsaUsage.cs new file mode 100644 index 0000000..b9bb1ad --- /dev/null +++ b/src/SafeCrypt.Test/Usage/RsaUsage.cs @@ -0,0 +1,54 @@ +using SafeCrypt.Helpers; +using SafeCrypt.RsaEncryption; +using System.Collections; + +namespace SafeCrypt.App.Usage; + +internal class RsaUsage +{ + internal protected async void Usage() + { + // Example: Generate RSA keys + var rsaKeyPair = KeyGenerators.GenerateRsaKeys(2048); + + string rsaPublicKey = rsaKeyPair.Item1; + string rsaPrivateKey = rsaKeyPair.Item2; + + Console.WriteLine($"pubic key {rsaPublicKey}"); + Console.WriteLine($"private key {rsaPrivateKey}"); + + // Example: Encrypt and Decrypt using RSA + string originalData = "Hello, RSA Encryption!"; + + var enModel = new RsaEncryptionParameters + { + DataToEncrypt = originalData, + PublicKey = rsaPublicKey, + }; + + var encryptedData = await Rsa.EncryptAsync(enModel); + + Console.WriteLine($"Original Data: {originalData}"); + + Console.WriteLine("Original byte array: " + BitConverter.ToString(encryptedData.EncryptedData)); + string EncryptedDataconvertedString = Convert.ToBase64String(encryptedData.EncryptedData); + + byte[] convertedBytes = Convert.FromBase64String(EncryptedDataconvertedString); + + Console.WriteLine("Converted back to byte array: " + BitConverter.ToString(convertedBytes)); + bool arraysAreEqual = StructuralComparisons.StructuralEqualityComparer.Equals(encryptedData.EncryptedData, convertedBytes); + Console.WriteLine("Original and converted byte arrays are equal: " + arraysAreEqual); + + // Decrypting + var decryptionModel = new RsaDecryptionParameters + { + DataToDecrypt = convertedBytes, + PrivateKey = rsaPrivateKey + }; + + var decryptedData = await Rsa.DecryptAsync(decryptionModel); + Console.WriteLine($"{decryptedData.DecryptedData}"); + + Console.ReadLine(); + } +}