Skip to content

Commit

Permalink
Merge pull request selfmadecode#6 from selfmadecode/dev
Browse files Browse the repository at this point in the history
Merged dev into master
  • Loading branch information
selfmadecode authored Apr 10, 2023
2 parents 45752d1 + e3607ec commit 84d8cac
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Encrypt/AesEncryption/BaseAesEncryption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,18 @@ public virtual byte[] EncryptAES(byte[] data, byte[] key, byte[] iv)
throw;
}
}

// 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())
{
rng.GetBytes(randomBytes);
}
return randomBytes;
}
}
}
34 changes: 34 additions & 0 deletions Encrypt/AesEncryption/Encrypt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,25 @@ public byte[] AesEncrypt(string data, string secretKey, string iv)
return EncryptAES(aesData, aesKey, aesIv);
}

public AesData AesEncrypt(string data, string secretKey)
{
NullChecks(data, secretKey);

var aesIv = GenerateRandomBytes(16);
var aesKey = Encoding.UTF8.GetBytes(secretKey);
var aesData = data.HexadecimalStringToByteArray();

var response = EncryptAES(aesData, aesKey, aesIv);

var responseData = new AesData
{
Data = response,
Iv = aesIv
};

return responseData;
}

public string AesEncryptByteToHexString(byte[] data, byte[] secretKey, byte[] iv)
{
var cipherText = EncryptAES(data, secretKey, iv);
Expand Down Expand Up @@ -53,9 +72,24 @@ private void NullChecks(string data, string secretKey, string iv)
throw new ArgumentNullException("IV");
}

private void NullChecks(string data, string secretKey)
{
if (data == null || data.Length <= 0)
throw new ArgumentNullException("plainText");

if (secretKey == null || secretKey.Length <= 0)
throw new ArgumentNullException("Key");
}

//public byte[] AesEncrypt(byte[] data, byte[] key, byte[] iv, ReturnType returnType)
//{

//}
}

public class AesData
{
public byte[] Data { get; set; }
public byte[] Iv { get; set; }
}
}

0 comments on commit 84d8cac

Please sign in to comment.