I am trying to implement AesManaged in my C# class library and being new to encryption wanted some mature guidance. I have been looking at this MSDN example and it encrypts string to binary and back decrypts binary back to string.
How can I adapt this to support string-to-string and binary-to-binary implementations?
- Some configuration data needs to be stored as encrypted strings in XML files and the registry.
- Some larger volatile data needs to be encrypted to a binary file.
Since this is a rush task, I thought it best not to rely on assumptions. Not knowing how Aes works, is my requirement as simple to address as getting Encoding.ASCII.GetString and Encoding.ASCII.GetBytes?
Yep, that’s basically all you “need” to do. Convert the string to a byte array and encrypt. The encrypted result won’t be a “friendly” string though. It’ll mostly be unreadable ASCII. If you’re storing the result in XML files, you might want to store the encrypted output as Base64, using ToBase64. When you read the values back in, you’ll want to convert from base64, and decrypt that.
Depending on the level of security you need, just using AES generally isn’t sufficient. AES will provide confidentiality (the message cannot be read), but not integrity (modifying the encrypted data). Using something like HMAC will tell you if someone has tampered with the data, even if they can’t read it.