首页 文章

RSA加密,密钥存储

提问于
浏览
1

我正在编写一个使用第三方API的.NET应用程序 . 存储api凭证的最佳方法是什么?我正在考虑使用RSACryptoServiceProvider对它们进行加密,我的问题是:如果我使用RSA加密我的凭据,我必须在应用程序的某处使用私钥来解密凭据,这不意味着加密是基本上无关紧要?因为任何人都可以继续使用加密的凭据并使用我必须提供的密钥来解密凭据 .

处理私钥并与使用我的应用程序的任何人保持联系的最佳方法是什么?

如果我把它作为一个字符串存储在我 class 的某个地方,可以读取密钥吗?

2 回答

  • 1

    您将无法将其隐藏于已经有权访问您的计算机的确定攻击者以及您的Windows用户名和密码 .

    话虽这么说,ProtectedData class可能是使没有适当凭据的用户无法访问数据的最简单方法 .

  • 1

    是的,如果将密钥存储为简单字符串,则可以读取密钥 . 但是您可以使用SecureString类并最小化易失性访问 .

    此外,永远不要将SecureString的内容放入String:如果这样做,String将在堆中保持未加密状态,并且在垃圾收集后重复使用内存之前不会将其字符清零 .

    CLR通过C#的示例:

    public static class Program
    {
        public static void Main()
        {
            using (SecureString ss = new SecureString())
            {
                Console.Write("Please enter password: ");
                while (true)
                {
                    ConsoleKeyInfo cki = Console.ReadKey(true);
                    if (cki.Key == ConsoleKey.Enter) break;
                    // Append password characters into the SecureString
                    ss.AppendChar(cki.KeyChar);
                    Console.Write("*");
                }
                Console.WriteLine();
                // Password entered, display it for demonstration purposes
                DisplaySecureString(ss);
            }
            // After 'using', the SecureString is Disposed; no sensitive data in memory
        }
        // This method is unsafe because it accesses unmanaged memory
        private unsafe static void DisplaySecureString(SecureString ss)
        {
            Char* pc = null;
            try
            {
                // Decrypt the SecureString into an unmanaged memory buffer
                pc = (Char*)Marshal.SecureStringToCoTaskMemUnicode(ss);
                // Access the unmanaged memory buffer that
                // contains the decrypted SecureString
                for (Int32 index = 0; pc[index] != 0; index++)
                    Console.Write(pc[index]);
            }
            finally
            {
                // Make sure we zero and free the unmanaged memory buffer that contains
                // the decrypted SecureString characters
                if (pc != null)
                    Marshal.ZeroFreeCoTaskMemUnicode((IntPtr)pc);
            }
        }
    }
    

相关问题