Skip to content

06. AesProvider

David Shnayder edited this page Jun 3, 2024 · 2 revisions

AesProvider

AesProvider is a class that implements IDisposable and allows very easy usage of AES128 encryption and decryption.

Static Methods

string GeneratePassword(string password, int iterations = 991);

This generates a hashed password from a real password. This is useful for storing and verifying account credentials.

bool IsPasswordValid(string password, string hashedPassword);

This will verify a hashed password against a real password.

Instance Methods

Constructor:

public AesProvider(string strKey);

Unlike the base classes of the language, this takes a key in the format of a string, and does all the magic of handling length, padding and such by itself, so that you only need the key to encrypt or decrypt.

Remember that this class implements IDisposable, make sure to dispose of it properly or use the using keyword or block.

Methods:

// Encryption
string Encrypt(ReadOnlySpan<char> unencrypted);
string EncryptUrl(string url);
byte[] EncryptBytes(ReadOnlySpan<byte> unencrypted);
int EncryptBytes(ReadOnlySpan<byte> unencrypted, Span<byte> destination);
// Decryption
string Decrypt(string encrypted);
string DecryptUrl(string encryptedUrl);
byte[] DecryptBytes(ReadOnlySpan<byte> encrypted, bool throwOnError = false);
int DecryptBytes(ReadOnlySpan<byte> encrypted, Span<byte> destination, bool throwOnError = false);

These methods straight up encrypt or decrypt the string or byte[] input.

string EncryptUrl(string url);
string DecryptUrl(string encryptedUrl);

These methods handle cases where the encrypted is formatted in base64 so it can be used in urls and file-names and so on...

These methods are used for handling all the base needs of encryption and decryption.

For more advanced encryption or decryption you can use these:

ICryptoTransform CreateEncryptor();
ICryptoTransform CreateDecryptor();

These will create an ICryptoTransform using the key and everything from the AesProvider instance. You can use it to encrypt and decrypt using streams and many more advanced options.

ICryptoTransform is also implementing IDisposable make sure to handle it appropriately.

Clone this wiki locally