问题
I'm currently working on a BackupManager sending an email to me after having processed all tasks. This email shall contain a log of what have been done.
The problem is, that my e-mail SMTP server (gmail) only allows encrypted connections using SSL. I know how to establish such a connection, but as the program runs from 2 to 8 am or at at a similar time, I don't want to have to enter the password every time. However, I also don't want to save the password as plain text on the hard drive. So I'm looking for a method to save the password encrypted and decrypt it later without prompting or stuff like that.
Thank you for help,
Turakar
回答1:
I've used the answer suggsted by Tomer Klein using ProtectedData. Just use ProtectedData.Protect(data, salt, scope)
to protect your password in bytes and ProtectedData.Unprotect(data, salt, scope)
to unprotect it. Remember to delete your password from memory once you are done, otherwise an attacker could retrieve it from there.
回答2:
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;
}
来源:https://stackoverflow.com/questions/28393750/secure-email-without-prompting-for-password