Leveraging ASP.NET machineKey For Encrypting My Own Data

前端 未结 5 1753
天命终不由人
天命终不由人 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:22

    With .NET Framwork 4.5 you should use the new API:

    public class StringProtector
    {
    
        private const string Purpose = "Authentication Token";
    
        public string Protect(string unprotectedText)
        {
            var unprotectedBytes = Encoding.UTF8.GetBytes(unprotectedText);
            var protectedBytes = MachineKey.Protect(unprotectedBytes, Purpose);
            var protectedText = Convert.ToBase64String(protectedBytes);
            return protectedText;
        }
    
        public string Unprotect(string protectedText)
        {
            var protectedBytes = Convert.FromBase64String(protectedText);
            var unprotectedBytes = MachineKey.Unprotect(protectedBytes, Purpose);
            var unprotectedText = Encoding.UTF8.GetString(unprotectedBytes);
            return unprotectedText;
        }
    
    }
    

    Ideally the "Purpose" should be a known one time valid value to prevent forging.

提交回复
热议问题