Updated 13/02/2025
My team needed a simple way to encrypt and decrypt some data, We chose Advanced Encryption Standard (AES), being a symmetric algorithm, it would use the same key for encryption & decryption.
Basic Example
The high level steps are:
- Create the encryptor method,
00000000000000000000000000000001
should be treated as a secret andbyte[16]
is trash per the comments below
1 | public byte[] Encrypt(byte[] data) |
- Create the decryptor method
1 | public byte[] Decrypt(byte[] cipherText) |
- Test the code
1 | var originalText = "This is something Id like to Encrypt for network transport."; |
This will output
1 | OriginalText: |
Refactoring to a better design
- Pop the
Encrypt
andDecrypt
methods into a class, change theirkey,iv
to use the private members.
1 | public class AesEncryptionService(string key, string iv) |
- You can then instanciate the class and pass the
key
andiv
you want to use
1 | var key = "00000000-0000-0000-0000-000000000001"; |
Complete code is here https://github.com/carlpaton/EncryptDecryptDemo
But I want to Encrypt an object
Calm down, you just serialize it 🐒
The examples above encrypt and decrypt the text This is something Id like to Encrypt for network transport.
, you could have an object instance thats needed to be transported/persisted:
1 | var obj = new MyObj { Id = 1, Foo = "bar" }; |
So if you plug that into the code the output is:
1 | OriginalText: |