Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
4b02849
feat: add RsaEncryptionParameters to hold parameters for encryption
selfmadecode Feb 6, 2024
c10203a
feat: add RsaEncryptionResult
selfmadecode Feb 6, 2024
ea3b02c
feat: add IEncryptionData interface to hold related properties
selfmadecode Feb 6, 2024
b258e2c
feat: add base Rsa encryption class with method for data encryption a…
selfmadecode Feb 6, 2024
6a932ef
feat: comment out Public key from RsaEncryptionResult
selfmadecode Feb 6, 2024
bc1b546
feat: use try catch for encryption
selfmadecode Feb 6, 2024
668f633
feat: move rsa key generation method to KeyGenerator class
selfmadecode Feb 6, 2024
f2d1d7d
feat: rename algorithm class to rsa
selfmadecode Feb 7, 2024
c50d51e
feat: use byte[] to hold encrypted data
selfmadecode Feb 7, 2024
dcc1b7e
feat: comment out byte check
selfmadecode Feb 7, 2024
3f04900
feat: test rsa algorithms
selfmadecode Feb 8, 2024
c1e911e
feat: update rsa algorithm comments
selfmadecode Feb 8, 2024
2e1c458
faet: add rsa encryption result
selfmadecode Feb 9, 2024
38b7058
feat: add rsa usage class
selfmadecode Feb 18, 2024
4b71e03
modify RsaEncryptionParameters namespace
selfmadecode Feb 18, 2024
c1f8600
remove rsa usage from program class
selfmadecode Feb 18, 2024
f5d1e26
feat: update readme doc to reflect rsa implementation
selfmadecode Feb 18, 2024
66eafce
remove unused code from rsa class
selfmadecode Feb 18, 2024
9963463
mark rsa encryption class as internal
selfmadecode Feb 18, 2024
aab63fa
marke usage model as internal protected
selfmadecode Feb 18, 2024
96107e9
update doc location
selfmadecode Feb 18, 2024
3282f50
feat: update readme doc
selfmadecode Feb 18, 2024
fc89ae1
update rsa file location
selfmadecode Feb 18, 2024
4bac397
add using statement in doc
selfmadecode Feb 18, 2024
7487fda
chnage rsausage class namespace
selfmadecode Feb 18, 2024
de1b13d
update readme file
selfmadecode Feb 18, 2024
cc700d5
featL turned BaseAesEncryption class to static
selfmadecode Feb 19, 2024
3b2c538
featL turned Decrypting class and methods to static
selfmadecode Feb 19, 2024
965234d
featL turned Encrypting class and methods to static
selfmadecode Feb 19, 2024
8411c90
update program class to use static AES methods
selfmadecode Feb 20, 2024
5cf8ad8
update readme doc to reflect static method change
selfmadecode Feb 20, 2024
7b9506f
Merge pull request #44 from selfmadecode/dev_ralph_rsa
selfmadecode Feb 20, 2024
575b2ff
feat: change aes encryption and decryption class into partial class
selfmadecode Feb 22, 2024
a3630c9
feat: update readme doc to use newly created AES class and namespace …
selfmadecode Feb 22, 2024
d6d4e35
feat: update program class with namespace and class name change for a…
selfmadecode Feb 22, 2024
eb6bd33
update readme doc
selfmadecode Feb 22, 2024
de80fe6
Merge pull request #50 from selfmadecode/45-convert-aes-algorithms-me…
selfmadecode Feb 22, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 23 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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,
Expand All @@ -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}");
Expand All @@ -74,8 +71,7 @@ class Program

-------------------------------------------------------------------------------------------------------

using SafeCrypt.AESDecryption;
using SafeCrypt.AESEncryption;
using SafeCrypt.AES;
using SafeCrypt.Models;

class Program
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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:
Expand Down
90 changes: 90 additions & 0 deletions doc/Rsa.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace SafeCrypt.AesEncryption
{
public class BaseAesEncryption
public static class BaseAesEncryption
{
/// <summary>
/// Encrypts the provided data using the Advanced Encryption Standard (AES) algorithm.
Expand Down
18 changes: 9 additions & 9 deletions src/SafeCrypt.Lib/Encryption/AesEncryption/Decrypting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
/// <summary>
/// Asynchronously decrypts data from a hexadecimal string using the specified decryption parameters and cipher mode.
Expand All @@ -19,7 +19,7 @@ public class AesDecryption : BaseAesEncryption
/// The task result is a <see cref="DecryptionData"/> object containing the decrypted data, IV, and secret key.
/// If decryption fails, the <see cref="DecryptionData"/> object will contain error information.
/// </returns>
public async Task<DecryptionData> DecryptFromHexStringAsync(DecryptionParameters param, CipherMode mode = CipherMode.CBC)
public static async Task<DecryptionData> DecryptFromHexStringAsync(DecryptionParameters param, CipherMode mode = CipherMode.CBC)
{
var responseData = new DecryptionData();

Expand Down Expand Up @@ -55,7 +55,7 @@ public async Task<DecryptionData> DecryptFromHexStringAsync(DecryptionParameters
Data = param.DataToDecrypt.HexadecimalStringToByteArray()
};

var response = await DecryptAsync(byteEncryptionParameters, mode);
var response = await BaseAesEncryption.DecryptAsync(byteEncryptionParameters, mode);

return new DecryptionData
{
Expand All @@ -75,7 +75,7 @@ public async Task<DecryptionData> DecryptFromHexStringAsync(DecryptionParameters
/// The task result is a <see cref="DecryptionData"/> object containing the decrypted data, IV, and secret key.
/// If decryption fails, the <see cref="DecryptionData"/> object will contain error information.
/// </returns>
public async Task<DecryptionData> DecryptFromBase64StringAsync(DecryptionParameters param, CipherMode mode = CipherMode.CBC)
public static async Task<DecryptionData> DecryptFromBase64StringAsync(DecryptionParameters param, CipherMode mode = CipherMode.CBC)
{
var responseData = new DecryptionData();

Expand Down Expand Up @@ -103,7 +103,7 @@ public async Task<DecryptionData> DecryptFromBase64StringAsync(DecryptionParamet
Data = Convert.FromBase64String(param.DataToDecrypt)
};

var response = await DecryptAsync(byteDecryptionParameters, mode);
var response = await BaseAesEncryption.DecryptAsync(byteDecryptionParameters, mode);

return new DecryptionData
{
Expand All @@ -121,7 +121,7 @@ public async Task<DecryptionData> 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));
Expand All @@ -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);
Expand Down
18 changes: 9 additions & 9 deletions src/SafeCrypt.Lib/Encryption/AesEncryption/Encrypting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
/// <summary>
/// Asynchronously encrypts the provided data using the specified secret key and initialization vector (IV).
Expand All @@ -23,7 +23,7 @@ public class AesEncryption : BaseAesEncryption
/// <param name="secretKey">The secret key used for encryption.</param>
/// <param name="iv">The initialization vector used for encryption.</param>
/// <returns>The encrypted data as a byte array.</returns>
public async Task<EncryptionData> EncryptToHexStringAsync(EncryptionParameters param, CipherMode mode = CipherMode.CBC)
public static async Task<EncryptionData> EncryptToHexStringAsync(EncryptionParameters param, CipherMode mode = CipherMode.CBC)
{
var responseData = new EncryptionData();

Expand Down Expand Up @@ -52,7 +52,7 @@ public async Task<EncryptionData> EncryptToHexStringAsync(EncryptionParameters p
Data = param.DataToEncrypt.ConvertToHexString().HexadecimalStringToByteArray()
};

var response = await EncryptAsync(byteEncryptionParameters, mode);
var response = await BaseAesEncryption.EncryptAsync(byteEncryptionParameters, mode);

return new EncryptionData
{
Expand Down Expand Up @@ -84,7 +84,7 @@ public async Task<EncryptionData> EncryptToHexStringAsync(EncryptionParameters p
/// <exception cref="FormatException">
/// Thrown if the base64secretKey is not a valid Base64-encoded string.
/// </exception>
public async Task<EncryptionData> EncryptToBase64StringAsync(string dataToBeEncrypted, string base64secretKey, CipherMode mode = CipherMode.CBC)
public static async Task<EncryptionData> EncryptToBase64StringAsync(string dataToBeEncrypted, string base64secretKey, CipherMode mode = CipherMode.CBC)
{
// validate is base64
if (!Validators.IsBase64String(base64secretKey))
Expand All @@ -104,7 +104,7 @@ public async Task<EncryptionData> EncryptToBase64StringAsync(string dataToBeEncr
Data = dataToBeEncrypted.ConvertToHexString().HexadecimalStringToByteArray()
};

var response = await EncryptAsync(byteEncryptionParameters, mode);
var response = await BaseAesEncryption.EncryptAsync(byteEncryptionParameters, mode);

return new EncryptionData
{
Expand All @@ -114,7 +114,7 @@ public async Task<EncryptionData> EncryptToBase64StringAsync(string dataToBeEncr
};
}

private EncryptionData ValidateEncryptionParameters(EncryptionParameters param)
private static EncryptionData ValidateEncryptionParameters(EncryptionParameters param)
{
var responseData = new EncryptionData();

Expand All @@ -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));
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.ComponentModel.DataAnnotations;

namespace SafeCrypt.RsaEncryption
{
public sealed class RsaEncryptionParameters : IEncryptionData
{
/// <summary>
/// Gets or sets the public key for RSA encryption.
/// </summary>
[Required]
public string PublicKey { get; set; }

/// <summary>
/// Gets or sets the data to be encrypted using RSA.
/// </summary>
[Required]
public string DataToEncrypt { get; set; }
}

public sealed class RsaDecryptionParameters
{
/// <summary>
/// Gets or sets the public key for RSA encryption.
/// </summary>
[Required]
public string PrivateKey { get; set; }

/// <summary>
/// Gets or sets the data to be encrypted using RSA.
/// </summary>
[Required]
public byte[] DataToDecrypt { get; set; }
}
}
Loading