c# - .NET中的密码加密/解密代码

标签 c# .net cryptography encryption

我想在 C# 中对密码进行简单的加密和解密。如何将密码以加密格式保存在数据库中,并通过解密恢复为原始格式?

最佳答案

给你。我在互联网上的某个地方找到了它。对我来说效果很好。

    /// <summary>
    /// Encrypts a given password and returns the encrypted data
    /// as a base64 string.
    /// </summary>
    /// <param name="plainText">An unencrypted string that needs
    /// to be secured.</param>
    /// <returns>A base64 encoded string that represents the encrypted
    /// binary data.
    /// </returns>
    /// <remarks>This solution is not really secure as we are
    /// keeping strings in memory. If runtime protection is essential,
    /// <see cref="SecureString"/> should be used.</remarks>
    /// <exception cref="ArgumentNullException">If <paramref name="plainText"/>
    /// is a null reference.</exception>
    public string Encrypt(string plainText)
    {
        if (plainText == null) throw new ArgumentNullException("plainText");

        //encrypt data
        var data = Encoding.Unicode.GetBytes(plainText);
        byte[] encrypted = ProtectedData.Protect(data, null, Scope);

        //return as base64 string
        return Convert.ToBase64String(encrypted);
    }

    /// <summary>
    /// Decrypts a given string.
    /// </summary>
    /// <param name="cipher">A base64 encoded string that was created
    /// through the <see cref="Encrypt(string)"/> or
    /// <see cref="Encrypt(SecureString)"/> extension methods.</param>
    /// <returns>The decrypted string.</returns>
    /// <remarks>Keep in mind that the decrypted string remains in memory
    /// and makes your application vulnerable per se. If runtime protection
    /// is essential, <see cref="SecureString"/> should be used.</remarks>
    /// <exception cref="ArgumentNullException">If <paramref name="cipher"/>
    /// is a null reference.</exception>
    public string Decrypt(string cipher)
    {
        if (cipher == null) throw new ArgumentNullException("cipher");

        //parse base64 string
        byte[] data = Convert.FromBase64String(cipher);

        //decrypt data
        byte[] decrypted = ProtectedData.Unprotect(data, null, Scope);
        return Encoding.Unicode.GetString(decrypted);
    }

关于c# - .NET中的密码加密/解密代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1678555/

相关文章:

c# - 直接在程序中打开图像

c# - 带空/空的数据注释 RegularExpressionAttribute

c# - 用户控件的控件是否应该由属性支持?

c# - 透明窗口层,可点击并始终保持在顶部

.net - 为 EventProcessorHost 实现 ILeaseManager

c# - 将 ASP.NET 网站连接到 SQL 数据库

c# - 在 WCF 数据服务 (3.5SP1) 的 ServiceOperation 中使用非原始类型

node.js - 如何在node.js中使用crypto.createSign和DiffieHellman私钥?

security - 我应该让我的登录应用程序加密登录安全 token 吗?

javascript - Crypto-js 本地端到 php 服务器端