Do you need encryption because of the need to decrypt again later? If not, hashing is preferrable.
If Encryption is what you need, i suggest using a secret that's not a part of your source-code, ie. the content of a text-file located on the server outside of your webapplication. I've also have good experience by using the Certificate Store of the machine to store a X509Certificate and use that as the key for encrypting/decrypting. The following code shows how to use the Certificate Store
Encrypt a string
If Encryption is what you need, i suggest using a secret that's not a part of your source-code, ie. the content of a text-file located on the server outside of your webapplication. I've also have good experience by using the Certificate Store of the machine to store a X509Certificate and use that as the key for encrypting/decrypting. The following code shows how to use the Certificate Store
Encrypt a string
var inputBytes = Encoding.UTF8.GetBytes(string_to_encrypt);
var provider = GetCryptoServiceProvider();
var encrypter = provider.CreateEncryptor();
var encryptedBytes = encrypter.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
var encryptedString = Convert.ToBase64String(encryptedBytes);
And then when you need to decrypt.var provider = GetCryptoServiceProvider();
var decryptor = provider.CreateDecryptor();
var encryptedBytes = Convert.FromBase64String(encryptedString);
var decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
var originalString = Encoding.UTF8.GetString(decryptedBytes);
And the GetCryptoServiceProvider methodprivate static SymmetricAlgorithm GetCryptoServiceProvider()
{
var storeLocation = StoreLocation.LocalMachine;
var storeName = StoreName.My;
var store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
var thumbprint = "thumbprint_of_your_certificate";
var x509 = store.Certificates.Cast<X509Certificate2>().SingleOrDefault(cert => cert.Thumbprint == thumbprint);
if (x509 == null)
{
throw new InvalidDataException("No certificate with the specified thumbprint found");
}
var publicKey = SHA256.Create().ComputeHash(x509.PublicKey.EncodedKeyValue.RawData);
return new AesCryptoServiceProvider
{
Key = publicKey,
IV = Encoding.UTF8.GetBytes("HR$2pIjHR$2pIj12"),
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};
}