利用ASP​​.NET的machineKey加密我自己的数据 [英] Leveraging ASP.NET machineKey For Encrypting My Own Data

查看:353
本文介绍了利用ASP​​.NET的machineKey加密我自己的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据,我想在ASP.NET MVC应用程序,以prevent用户篡改数据加密。我可以使用加密类来完成实际的加密/解密,没问题的。主要的问题是搞清楚在哪里存储加密密钥和管理更改。

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/decryption, no problem there. The main problem is figuring out where to store the encryption key and managing changes to it.

由于ASP.NET已经保持对各种事物的machineKey(ViewData的加密等),我在想,如果有这让我加密/使用的machineKey解密自己数据的任何ASP.NET的功能呢?这样,我就不会去制定自己的密钥管理系统。

Since ASP.NET already maintains a machineKey for various things (ViewData encryption, etc), I was wondering if there were any ASP.NET functions which let me encrypt/decrypt my own data using the machineKey? This way I would not have to devise my own key management system.

推荐答案

新的在ASP.NET 4.0的machineKey 类不正是你想要的。

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

例如:

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;
        }
    }
}

更新:正如<一个href="http://blogs.msdn.com/b/webdev/archive/2012/10/22/cryptographic-improvements-in-asp-net-4-5-pt-1.aspx">here,小心你如何使用,或者你可以让别人伪造一个窗体身份验证令牌。

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

这篇关于利用ASP​​.NET的machineKey加密我自己的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆