在不提示密码的情况下保护电子邮件

时间:2015-02-08 12:08:52

标签: c# security email passwords

我正在处理BackupManager在处理完所有任务后向我发送电子邮件。该电子邮件应包含已完成的日志。

问题是,我的电子邮件SMTP服务器(gmail)仅允许使用SSL的加密连接。我知道如何建立这样的连接,但由于程序从早上2点到早上8点或在类似的时间运行,我不想每次都输入密码。但是,我也不想将密码保存为硬盘驱动器上的纯文本。所以我正在寻找一种方法来保存加密的密码并在以后解密它而不会提示或类似的东西。

感谢您的帮助,

Turakar

2 个答案:

答案 0 :(得分:0)

private string Encrypt(string clearText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    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;
}
 
private string Decrypt(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    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;
}

答案 1 :(得分:0)

我使用了Tomer Klein使用ProtectedData提出的答案。只需使用ProtectedData.Protect(data, salt, scope)以字节为单位保护您的密码,并使用ProtectedData.Unprotect(data, salt, scope)取消保护。完成后,请记住从内存中删除密码,否则攻击者可以从那里检索密码。