Skip to content

Commit

Permalink
Merge pull request selfmadecode#9 from selfmadecode/dev_raphael_aes
Browse files Browse the repository at this point in the history
merge raphael aes into dev
  • Loading branch information
selfmadecode authored Apr 15, 2023
2 parents 78aac96 + 469aaaf commit 1fab22a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
3 changes: 3 additions & 0 deletions Encrypt/AesEncryption/AesEncryption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ public class AesEncryption : BaseAesEncryption
public byte[] AesEncrypt(byte[] data, byte[] secretKey, byte[] iv)
=> EncryptAES(data, secretKey, iv);

public byte[] AesDecrypt(byte[] data, byte[] secretKey, byte[] iv)
=> DecryptAES(data, secretKey, iv);

public byte[] AesEncrypt(string data, string secretKey, string iv)
{
NullChecks(data, secretKey, iv);
Expand Down
30 changes: 26 additions & 4 deletions Encrypt/AesEncryption/BaseAesEncryption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,32 @@ public virtual byte[] EncryptAES(byte[] data, byte[] key, byte[] iv)
}
}

// Method to generate a random byte array of given length
// Used to get the IV
// Generate a random 16-byte IV for AES in CBC mode
public static byte[] GenerateRandomBytes(int length)
// Method to decrypt data using AES algorithm
public static byte[] DecryptAES(byte[] encryptedData, byte[] key, byte[] iv)
{
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (MemoryStream decryptedStream = new MemoryStream())
{
cryptoStream.CopyTo(decryptedStream);
return decryptedStream.ToArray();
}
}
}
}
}

// Method to generate a random byte array of given length
// Used to get the IV
// Generate a random 16-byte IV for AES in CBC mode
public static byte[] GenerateRandomBytes(int length)
{
byte[] randomBytes = new byte[length];
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
Expand Down

0 comments on commit 1fab22a

Please sign in to comment.