Leveraging ASP.NET machineKey For Encrypting My Own Data

前端 未结 5 1795
天命终不由人
天命终不由人 2021-01-30 02:00

I have some data I want to encrypt in an ASP.NET MVC application to prevent users from tampering with it. I can use the Cryptography classes to do the actual encryption/decrypt

5条回答
  •  温柔的废话
    2021-01-30 02:06

    The new MachineKey class in ASP.NET 4.0 does exactly what you want.

    For example:

    public static class StringEncryptor {
        public static string Encrypt(string plaintextValue) {
            var plaintextBytes = Encoding.UTF8.GetBytes(plaintextValue);
            return MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);
        }
    
        public static string Decrypt(string encryptedValue) {
            try {
                var decryptedBytes = MachineKey.Decode(encryptedValue, MachineKeyProtection.All);
                return Encoding.UTF8.GetString(decryptedBytes);
            }
            catch {
                return null;
            }
        }
    }
    

    UPDATE: As mentioned here, be careful how you use this or you could allow someone to forge a forms authentication token.

提交回复
热议问题