Skip to content

Commit e05f28d

Browse files
authored
Merge pull request #20 from selfmadecode/dev_raphael_aes
feat: add code comments for encryption aes decryption and include code clean up for better maintainability
2 parents 7114bdf + 7fa16f6 commit e05f28d

9 files changed

Lines changed: 334 additions & 59 deletions

File tree

SafeCrypt.csproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,8 @@
44
<TargetFramework>netstandard2.0</TargetFramework>
55
</PropertyGroup>
66

7+
<ItemGroup>
8+
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
9+
</ItemGroup>
10+
711
</Project>

src/Encryption/AesEncryption/BaseAesEncryption.cs

Lines changed: 68 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,52 @@
1-
using System;
1+
using SafeCrypt.src.Encryption.AesEncryption.Models;
2+
using System;
23
using System.IO;
34
using System.Security.Cryptography;
45

56
namespace SafeCrypt.src.Encrypt.AesEncryption
67
{
78
public class BaseAesEncryption
89
{
9-
// Method to encrypt data using AES algorithm
10-
public virtual byte[] EncryptAES(byte[] data, byte[] key, byte[] iv)
10+
/// <summary>
11+
/// Encrypts the provided data using the Advanced Encryption Standard (AES) algorithm.
12+
/// </summary>
13+
/// <param name="param.Data">The data to be encrypted.</param>
14+
/// <param name="param.SecretKey">The secret key used for encryption.</param>
15+
/// <param name="param.IV">The initialization vector used for encryption.</param>
16+
/// <returns>The encrypted data as a byte array.</returns>
17+
/// <remarks>
18+
/// The method uses the AES algorithm to encrypt the input data with the provided key and initialization vector.
19+
/// </remarks>
20+
/// <exception cref="ArgumentNullException">
21+
/// Thrown if the input data, key, or initialization vector is null.
22+
/// </exception>
23+
/// <exception cref="Exception">
24+
/// Thrown for general encryption-related exceptions.
25+
/// </exception>
26+
public virtual byte[] EncryptAES(ByteEncryptionParameters param)
1127
{
1228
try
1329
{
30+
// Create an instance of the AES algorithm
1431
using (Aes aes = Aes.Create())
1532
{
16-
aes.Key = key;
17-
aes.IV = iv;
33+
// Set the key and initialization vector
34+
aes.Key = param.SecretKey;
35+
aes.IV = param.IV;
36+
// Create an encryptor using the key and initialization vector
1837
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
38+
39+
// Use a MemoryStream to store the encrypted data
1940
using (MemoryStream memoryStream = new MemoryStream())
2041
{
42+
// Use a CryptoStream to perform the encryption
2143
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
2244
{
23-
cryptoStream.Write(data, 0, data.Length);
45+
// Write the data to be encrypted to the CryptoStream
46+
cryptoStream.Write(param.Data, 0, param.Data.Length);
2447
cryptoStream.FlushFinalBlock();
2548

49+
// Return the encrypted data as a byte array
2650
return memoryStream.ToArray();
2751
}
2852
}
@@ -34,20 +58,41 @@ public virtual byte[] EncryptAES(byte[] data, byte[] key, byte[] iv)
3458
}
3559
}
3660

37-
// Method to decrypt data using AES algorithm
61+
/// <summary>
62+
/// Decrypts the provided encrypted data using the Advanced Encryption Standard (AES) algorithm.
63+
/// </summary>
64+
/// <param name="encryptedData">The data to be decrypted.</param>
65+
/// <param name="key">The secret key used for decryption.</param>
66+
/// <param name="iv">The initialization vector used for decryption.</param>
67+
/// <returns>The decrypted data as a byte array.</returns>
68+
/// <remarks>
69+
/// The method uses the AES algorithm to decrypt the input encrypted data with the provided key and initialization vector.
70+
/// </remarks>
71+
/// <exception cref="ArgumentNullException">
72+
/// Thrown if the input encrypted data, key, or initialization vector is null.
73+
/// </exception>
3874
public static byte[] DecryptAES(byte[] encryptedData, byte[] key, byte[] iv)
3975
{
76+
// Create an instance of the AES algorithm
4077
using (Aes aes = Aes.Create())
4178
{
79+
// Set the key and initialization vector
4280
aes.Key = key;
4381
aes.IV = iv;
82+
83+
// Create a decryptor using the key and initialization vector
4484
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
85+
86+
// Use a MemoryStream to read the encrypted data
4587
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
4688
{
89+
// Use a CryptoStream to perform the decryption
4790
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
4891
{
92+
// Use a MemoryStream to store the decrypted data
4993
using (MemoryStream decryptedStream = new MemoryStream())
5094
{
95+
// Copy the decrypted data from the CryptoStream to the MemoryStream
5196
cryptoStream.CopyTo(decryptedStream);
5297
return decryptedStream.ToArray();
5398
}
@@ -56,10 +101,22 @@ public static byte[] DecryptAES(byte[] encryptedData, byte[] key, byte[] iv)
56101
}
57102
}
58103

59-
// Method to generate a random byte array of given length
60-
// Used to get the IV
61-
// Generate a random 16-byte IV for AES in CBC mode
62-
public static byte[] GenerateRandomBytes(int length)
104+
105+
/// <summary>
106+
/// Generates an array of random bytes using a cryptographically secure random number generator.
107+
/// </summary>
108+
/// <param name="length">The length of the byte array to generate.</param>
109+
/// <returns>An array of random bytes or the IV key</returns>
110+
/// <remarks>
111+
/// The method uses a cryptographically secure random number generator (RNGCryptoServiceProvider) to generate
112+
/// a byte array with the specified length, providing a high level of randomness suitable for cryptographic use.
113+
/// </remarks>
114+
/// <param name="length">The desired length of the generated byte array.</param>
115+
/// <returns>An array of random bytes with the specified length.</returns>
116+
/// <exception cref="ArgumentException">
117+
/// Thrown if the specified length is less than or equal to zero.
118+
/// </exception>
119+
public static byte[] GenerateRandomIVKeyAsBytes(int length)
63120
{
64121
byte[] randomBytes = new byte[length];
65122
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())

src/Encryption/AesEncryption/Decrypting.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
using SafeCrypt.src.Encrypt.AesEncryption;
22
using SafeCrypt.src.Helpers;
33
using System;
4-
using System.Collections.Generic;
5-
using System.Text;
64

75
namespace SafeCrypt.src.Encryption.AesEncryption
86
{

src/Encryption/AesEncryption/Encrypting.cs

Lines changed: 125 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,87 @@
11
using System;
22
using System.Text;
3-
using System.Security.Cryptography;
43
using SafeCrypt.src.Helpers;
54
using SafeCrypt.src.Encryption.AesEncryption.Models;
65

76
namespace SafeCrypt.src.Encrypt.AesEncryption
87
{
98
public class Encrypting : BaseAesEncryption
109
{
11-
public byte[] Encrypt(byte[] data, byte[] secretKey, byte[] iv)
12-
=> EncryptAES(data, secretKey, iv);
10+
/// <summary>
11+
/// Encrypts the provided data using the specified secret key and initialization vector (IV).
12+
/// </summary>
13+
/// <param name="parameters">The encryption parameters.</param>
14+
/// <returns>The encrypted data as a byte array.</returns>
15+
/// <remarks>
16+
/// This method serves as a wrapper around the underlying AES encryption logic provided by the
17+
/// <see cref="EncryptAES"/> method. It simplifies the encryption process by exposing a more
18+
/// user-friendly interface, accepting data, secret key, and initialization vector as parameters.
19+
/// </remarks>
20+
/// <param name="data">The data to be encrypted.</param>
21+
/// <param name="secretKey">The secret key used for encryption.</param>
22+
/// <param name="iv">The initialization vector used for encryption.</param>
23+
/// <returns>The encrypted data as a byte array.</returns>
24+
public byte[] Encrypt(ByteEncryptionParameters param)
25+
{
26+
Validators.ValidateNotNull(param);
27+
28+
// Delegate the encryption to the underlying AES encryption method
29+
return EncryptAES(param);
30+
}
1331

1432

15-
public byte[] Encrypt(string data, string secretKey, string iv)
33+
public byte[] Encrypt(StringEncryptionParameters param)
1634
{
17-
NullChecks(data, secretKey, iv);
35+
Validators.ValidateNotNull(param);
1836

19-
var aesKey = secretKey.ConvertKeysToBytes();
20-
var aesIv = iv.ConvertKeysToBytes();
37+
var byteEncryptionParameters = new ByteEncryptionParameters
38+
{
39+
SecretKey = param.SecretKey.ConvertKeysToBytes(),
40+
IV = param.IV.ConvertKeysToBytes(),
41+
Data = param.Data.HexadecimalStringToByteArray()
42+
};
2143

22-
var aesData = data.HexadecimalStringToByteArray();
23-
return EncryptAES(aesData, aesKey, aesIv);
44+
return EncryptAES(byteEncryptionParameters);
2445
}
2546

26-
27-
28-
public AesEncryptionData Encrypt(string data, string secretKey)
47+
/// <summary>
48+
/// Encrypts the provided string data using the Advanced Encryption Standard (AES) algorithm.
49+
/// </summary>
50+
/// <param name="data">The string data to be encrypted.</param>
51+
/// <param name="secretKey">The secret key used for encryption.</param>
52+
/// <returns>An <see cref="AesEncrypted"/> object containing the encrypted data and initialization vector (IV).</returns>
53+
/// <remarks>
54+
/// This method encrypts the input string data using the specified secret key and a randomly generated initialization
55+
/// vector (IV) for AES encryption in Cipher Block Chaining (CBC) mode. The resulting encrypted data and IV are encapsulated
56+
/// in an <see cref="AesEncrypted"/> object, which is then returned.
57+
/// </remarks>
58+
/// <param name="data">The string data to be encrypted.</param>
59+
/// <param name="secretKey">The secret key used for encryption.</param>
60+
/// <returns>An <see cref="AesEncrypted"/> object containing the encrypted data and initialization vector (IV).</returns>
61+
/// <exception cref="ArgumentNullException">
62+
/// Thrown if the input data or secret key is null.
63+
/// </exception>
64+
public EncryptionData Encrypt(string data, string secretKey)
2965
{
3066
NullChecks(data, secretKey);
3167

32-
var aesIv = GenerateRandomBytes(16);
68+
// Generate a random 16-byte IV for AES in CBC mode
69+
var aesIv = GenerateRandomIVKeyAsBytes(16);
3370

34-
var aesKey = Encoding.UTF8.GetBytes(secretKey);
35-
var aesData = data.HexadecimalStringToByteArray();
71+
//var aesKey = Encoding.UTF8.GetBytes(secretKey);
72+
//var aesData = data.HexadecimalStringToByteArray();
3673

37-
var response = EncryptAES(aesData, aesKey, aesIv);
74+
var byteEncryptionParameters = new ByteEncryptionParameters
75+
{
76+
SecretKey = Encoding.UTF8.GetBytes(secretKey),
77+
IV = aesIv,
78+
Data = data.HexadecimalStringToByteArray()
79+
};
3880

39-
var responseData = new AesEncryptionData
81+
//var response = EncryptAES(aesData, aesKey, aesIv);
82+
var response = EncryptAES(byteEncryptionParameters);
83+
84+
var responseData = new EncryptionData
4085
{
4186
Data = response,
4287
Iv = aesIv
@@ -45,43 +90,90 @@ public AesEncryptionData Encrypt(string data, string secretKey)
4590
return responseData;
4691
}
4792

48-
public string EncryptByteToHexString(byte[] data, byte[] secretKey, byte[] iv)
93+
/// <summary>
94+
/// Encrypts the provided byte data using the Advanced Encryption Standard (AES) algorithm
95+
/// and returns the encrypted data as a hexadecimal string.
96+
/// </summary>
97+
/// <param name="param">The parameters containing the byte data, secret key, and initialization vector (IV).</param>
98+
/// <returns>The encrypted data represented as a hexadecimal string.</returns>
99+
/// <remarks>
100+
/// This method encrypts the input byte data using the specified secret key and initialization vector (IV)
101+
/// using the AES algorithm. The resulting encrypted data is then converted to a hexadecimal string before being
102+
/// returned. The encryption parameters are encapsulated in a <see cref="ByteEncryptionParameters"/> object.
103+
/// </remarks>
104+
/// <param name="param">The parameters containing the byte data, secret key, and initialization vector (IV).</param>
105+
/// <returns>The encrypted data represented as a hexadecimal string.</returns>
106+
/// <exception cref="ArgumentNullException">
107+
/// Thrown if the input parameters or byte data is null.
108+
/// </exception>
109+
public string EncryptByteToHexString(ByteEncryptionParameters param)
49110
{
50-
var cipherText = EncryptAES(data, secretKey, iv);
111+
Validators.ValidateNotNull(param);
112+
113+
var cipherText = EncryptAES(param);
51114

115+
// Convert the encrypted data to a hexadecimal string
52116
return cipherText.ByteArrayToHexString();
53117
}
54118

55-
public string EncryptByteToBase64String(byte[] data, byte[] secretKey, byte[] iv)
119+
/// <summary>
120+
/// Encrypts the provided byte data using the Advanced Encryption Standard (AES) algorithm
121+
/// and returns the encrypted data as a Base64-encoded string.
122+
/// </summary>
123+
/// <param name="param">The parameters containing the byte data, secret key, and initialization vector (IV).</param>
124+
/// <returns>The encrypted data represented as a Base64-encoded string.</returns>
125+
/// <remarks>
126+
/// This method encrypts the input byte data using the specified secret key and initialization vector (IV)
127+
/// using the AES algorithm. The resulting encrypted data is then converted to a Base64-encoded string before
128+
/// being returned. The encryption parameters are encapsulated in a <see cref="ByteEncryptionParameters"/> object.
129+
/// </remarks>
130+
/// <param name="param">The parameters containing the byte data, secret key, and initialization vector (IV).</param>
131+
/// <returns>The encrypted data represented as a Base64-encoded string.</returns>
132+
/// <exception cref="ArgumentNullException">
133+
/// Thrown if the input parameters or byte data is null.
134+
/// </exception>
135+
public string EncryptByteToBase64String(ByteEncryptionParameters param)
56136
{
57-
var cipherText = EncryptAES(data, secretKey, iv);
137+
Validators.ValidateNotNull(param);
138+
139+
var cipherText = EncryptAES(param);
58140

59141
return Convert.ToBase64String(cipherText);
60142
}
61143

62-
public string EncryptByteToString(byte[] data, byte[] secretKey, byte[] iv)
144+
/// <summary>
145+
/// Encrypts the provided byte data using the Advanced Encryption Standard (AES) algorithm
146+
/// and returns the encrypted data as a string using UTF-8 encoding.
147+
/// </summary>
148+
/// <param name="param">The parameters containing the byte data, secret key, and initialization vector (IV).</param>
149+
/// <returns>The encrypted data represented as a string using UTF-8 encoding.</returns>
150+
/// <remarks>
151+
/// This method encrypts the input byte data using the specified secret key and initialization vector (IV)
152+
/// using the AES algorithm. The resulting encrypted data is then converted to a string using UTF-8
153+
/// encoding before being returned. The encryption parameters are encapsulated in a <see cref="ByteEncryptionParameters"/> object.
154+
/// </remarks>
155+
/// <param name="param">The parameters containing the byte data, secret key, and initialization vector (IV).</param>
156+
/// <returns>The encrypted data represented as a string using UTF-8 encoding.</returns>
157+
/// <exception cref="ArgumentNullException">
158+
/// Thrown if the input parameters or byte data is null.
159+
/// </exception>
160+
public string EncryptByteToString(ByteEncryptionParameters param)
63161
{
64-
var cipherText = EncryptAES(data, secretKey, iv);
162+
Validators.ValidateNotNull(param);
163+
164+
var cipherText = EncryptAES(param);
65165

66166
return cipherText.BytesToString();
67167
}
168+
68169

69-
// needs methods that would accept aes mode
70-
//public byte[] AesEncrypt(byte[] data, byte[] key, byte[] iv, ReturnType returnType)
71-
//{
72-
73-
//}
74-
75-
private void NullChecks(string data, string secretKey, string iv = "")
170+
private void NullChecks(string data, string secretKey)
76171
{
77172
if (data == null || data.Length <= 0)
78173
throw new ArgumentNullException(nameof(data));
79174

80175
if (secretKey == null || secretKey.Length <= 0)
81176
throw new ArgumentNullException(nameof(secretKey));
82-
83-
if (iv == null || iv.Length <= 0)
84-
throw new ArgumentNullException(nameof(iv));
85177
}
86178
}
87179

src/Encryption/AesEncryption/Models/AesEncryptionData.cs

Lines changed: 0 additions & 12 deletions
This file was deleted.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace SafeCrypt.src.Encryption.AesEncryption.Models
6+
{
7+
/// <summary>
8+
/// Represents the data and initialization vector (IV) used in encryption.
9+
/// </summary>
10+
public class EncryptionData
11+
{
12+
/// <summary>
13+
/// Gets or sets the data to be encrypted.
14+
/// </summary>
15+
public byte[] Data { get; set; }
16+
17+
/// <summary>
18+
/// Gets or sets the initialization vector (IV) used for encryption.
19+
/// </summary>
20+
public byte[] Iv { get; set; }
21+
}
22+
}

0 commit comments

Comments
 (0)