简体   繁体   English

安全加密数据

[英]Safely encrypting data

I needed some data to be encrypted safely and I found this snippet of code to use.我需要对一些数据进行安全加密,我发现这段代码可以使用。 I have tested it and it appears unreadable to me but How should I store my encryption key so most people won't be able to access it?我已经对其进行了测试,但它对我来说似乎无法读取,但是我应该如何存储我的加密密钥,以便大多数人无法访问它?

public static string Encrypt(string clearText)
{
    string EncryptionKey = "encryptionKey";
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}
public static string Decrypt(string cipherText)
{
    string EncryptionKey = "encryptionKey";
    cipherText = cipherText.Replace(" ", "+");
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}

After much research and some tweaking to the code I finally came up with a secure encryption method.经过大量研究和对代码的一些调整,我终于想出了一种安全的加密方法。 I generated some secure random numbers and used them in the salt.我生成了一些安全的随机数并在盐中使用它们。 I combined the salt, device ID and, a static string to get a secure encryption key.我将盐、设备 ID 和 static 字符串组合在一起,以获得安全的加密密钥。

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

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