微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将字符串存储在第一次后不会更改的 c# 应用程序中

如何解决将字符串存储在第一次后不会更改的 c# 应用程序中

我有一个用 C# 开发的应用程序,我希望当用户第一次打开应用程序时,它将密钥、用户系统 mac 地址和系统 ip 存储在一个变量中,每当用户再次打开应用程序时,我都可以找到第一个输入的存储的数据。但我不想将它存储在他可以编辑的用户系统上。我们是否有任何选项可以在应用程序中自行完成。

解决方法

如果您检查 Microsoft Docs 的此链接,您可以使用 System.Security.Cryptography 来存储您的机密。例如:

public static void Main()
    {
        // Set the static UseMachineKeyStore property to use the machine key
        // store instead of the user profile key store.
        RSACryptoServiceProvider.UseMachineKeyStore = true;
        try
        {

            CspParameters cspParams = new CspParameters();
            //Name the container where the key are going to be stored. I sugest use the MAC address as a container name
            cspParams.KeyContainerName = "MyContainer";

            byte[] infoToStore;
            
            using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(cspParams))
            {
                //Store the key in the provider
                RSAalg.PersistKeyInCsp = true;
                //Encrypt the data you need to save
                infoToStore = RSAalg.EncryptValue(Encoding.UTF8.GetBytes("MAC:ADDRESS.....IP.ADRESS...... all info"));
            }
            //Save the data to a file,a BD or a Registry
            SaveToFile(infoToStore);

            byte[] decryted;
            //To decrypt the data
            using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(cspParams))
            {
               //Read the dat from file,Registry,etc.
                byte[] info = ReadFromFile();
                decryted = RSAalg.DecryptValue(info);
            }
            //Process de decrypted data as you needed
            Console.WriteLine(Encoding.UTF8.GetString(decryted));
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。