繁体   English   中英

在哪里存储c#应用程序的密钥

[英]Where to store secret key of the c# application

类似的问题如何在对称算法中管理密钥在 哪里存储要在SHA-1哈希中使用的密钥?

我的问题是一样的,但我想以不同的方式提出这个问题

我有C#应用程序。 我正在加密应用程序中的一些数据。 对于加密,我使用密钥或密码。 解密需要同样的事情。

在应用程序中存储/如何存储此密钥或密码的位置? 它很容易从反射中查看字符串密码。 我可能会使用一些组合来生成密码,但有些聪明人可以通过一些努力来猜测。

是否有任何安全的方法来存储或管理在应用程序中用于加密数据的密码?

我怀疑有任何保证安全的方式来存储密钥。 最终,您的程序必须能够访问密钥,并且一个破解者可以通过逆向工程轻松地解决这种情况,并将该字符串重定向到他们想要的任何地方。

您最好的选择是:

  • 尽可能地模糊密钥。 这使得访问“秘密密钥”变得更加困难,但却无法实现(见上文)。 而不是将其存储为字符串,使用函数生成它,或使用种子并通过函数传递它以获取秘密字符串。

  • 如果您的用例允许,请使用公钥/私钥对。 它只适用于您希望应用程序加密数据,将其发送到您的服务器,然后您想要解密它。 在这种情况下,您将公钥嵌入应用程序(如果破解者发现这一点并不重要),并将私钥保留给您自己或您的服务器。

如果您将密钥存储为应用程序设置,并加密应用程序设置,那么我认为您很节省。

您可以使用以下代码加密app.config的各个部分。

using System;
using System.Configuration;

public static class ConfigurationEncryptor {
    [Flags]
    public enum ConfigurationSectionType {
        ConnectionStrings = 1,
        ApplicationSettings = 2
    }

    /// <summary>
    /// Encrypts the given sections in the current configuration.
    /// </summary>
    /// <returns>True is the configuration file was encrypted</returns>
    public static bool Encrypt(ConfigurationSectionType section) {
        bool result = false;

        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        if (config == null)
            throw new Exception("Cannot open the configuration file.");

        if (section.HasFlag(ConfigurationSectionType.ConnectionStrings)) {
            result = result || EncryptSection(config, "connectionStrings");
        }

        if (section.HasFlag(ConfigurationSectionType.ApplicationSettings)) {
            result = result || EncryptSection(config, "appSettings");
        }

        return result;
    }

    /// <summary>
    /// Encrypts the specified section.
    /// </summary>
    /// <param name="config">The config.</param>
    /// <param name="section">The section.</param>
    private static bool EncryptSection(Configuration config, string section) {
        ConfigurationSection currentSection = config.GetSection(section);
        if (currentSection == null)
            throw new Exception("Cannot find " + section + " section in configuration file.");
        if (!currentSection.SectionInformation.IsProtected) {
            currentSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            config.Save();

            // Refresh configuration
            ConfigurationManager.RefreshSection(section);

            return true;
        }
        return false;
    }
}

并像这样使用它(例如在你的Main()方法中):

ConfigurationEncryptor.Encrypt(
    ConfigurationEncryptor.ConfigurationSectionType.ApplicationSettings |
    ConfigurationEncryptor.ConfigurationSectionType.ConnectionStrings
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM