我怎么能在我的应用程序加密的用户设置(如密码)? [英] How can I encrypt user settings (such as passwords) in my application?
问题描述
我要提供用户保存加密的个人数据的能力。这可能是微不足道的,也可能已经被问过,但我不能找到一个易于使用的方法来加密/解密密码的例子。
I want to provide the user the ability to save personal data encrypted. This might be trivial or might have been already asked, but I am not able to find an example of an easy to use way to encrypt/decrypt a password.
我真的不需要任何超魔牢不可破的密码。我只需要密码要像难以打破。
I really don't need any super-magic-unbreakable password. I just need the password to be like difficult to break.
我已经看到了一些MSDN和SO问题,但还没有发现什么用。
I've seen some msdn and SO questions but haven't found something to use.
推荐答案
大卫,我想的你的答案很漂亮,但我认为这将是niftier的扩展方法。这将允许这样的语法为:
David, I thought your answer was nifty, but I thought those would be niftier as extension methods. That would allow such syntax as:
string cypherText;
string clearText;
using (var secureString = "Some string to encrypt".ToSecureString())
{
cypherText = secureString.EncryptString();
}
using (var secureString = cypherText.DecryptString())
{
clearText = secureString.ToInsecureString();
}
下面是更新后的code:
Here's the updated code:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;
public static class SecureIt
{
private static readonly byte[] entropy = Encoding.Unicode.GetBytes("Salt Is Not A Password");
public static string EncryptString(this SecureString input)
{
if (input == null)
{
return null;
}
var encryptedData = ProtectedData.Protect(
Encoding.Unicode.GetBytes(input.ToInsecureString()),
entropy,
DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
public static SecureString DecryptString(this string encryptedData)
{
if (encryptedData == null)
{
return null;
}
try
{
var decryptedData = ProtectedData.Unprotect(
Convert.FromBase64String(encryptedData),
entropy,
DataProtectionScope.CurrentUser);
return Encoding.Unicode.GetString(decryptedData).ToSecureString();
}
catch
{
return new SecureString();
}
}
public static SecureString ToSecureString(this IEnumerable<char> input)
{
if (input == null)
{
return null;
}
var secure = new SecureString();
foreach (var c in input)
{
secure.AppendChar(c);
}
secure.MakeReadOnly();
return secure;
}
public static string ToInsecureString(this SecureString input)
{
if (input == null)
{
return null;
}
var ptr = Marshal.SecureStringToBSTR(input);
try
{
return Marshal.PtrToStringBSTR(ptr);
}
finally
{
Marshal.ZeroFreeBSTR(ptr);
}
}
}
这篇关于我怎么能在我的应用程序加密的用户设置(如密码)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!