【发布时间】:2012-03-10 13:13:40
【问题描述】:
我有以下带有私有静态成员的代码。
所有这些类都表示它们在 MSDN 库中对于“公共 static”成员是线程安全的。
我的问题是这些成员在用作私有静态而不是 MSDN 库中所述的“公共静态”时是否是线程安全的。
public static class passwordManager
{
private static System.Security.Cryptography.SHA256 shaM = new System.Security.Cryptography.SHA256Managed();
private static System.Security.Cryptography.RandomNumberGenerator rand = new System.Security.Cryptography.RNGCryptoServiceProvider();
private static System.Text.Encoding enc = System.Text.Encoding.ASCII;
public static string produceSalt(int size)
{
byte[] by = new byte[size];
lock (rand)
{
rand.GetBytes(by);
}
return enc.GetString(by, 0, by.Length);
}
public static string encryptPassword(string password, string salt){
return enc.GetString(shaM.ComputeHash(enc.GetBytes(password + salt)));
}
public static bool isCorrectPassword(string inputPassword, string DBsalt, string DBpassword)
{
return encryptPassword(inputPassword, DBsalt) == DBpassword;
}
这可能完全取决于我自己使用的方法是否使用共享变量而不是所有方法实例变量...让您安心会有所帮助,但如果不是,我宁愿不必在此处锁定所有内容必要的。
我锁定随机数生成器的唯一原因是限制获得相同盐的可能性,但是在我的情况下,两个线程同时调用它的可能性非常低。
谢谢,
迈克
这现在应该是线程安全的。我试图节省对象实例化开销,但我想这和锁等待之间存在权衡。在高负载系统上,锁等待可能会大大超过实例化开销和内存使用量。
public static class passwordManager
{
private static System.Security.Cryptography.RandomNumberGenerator rand = new System.Security.Cryptography.RNGCryptoServiceProvider();
public static byte[] produceSalt(int size)
{
byte[] by = new byte[size];
lock (rand)
{
rand.GetBytes(by);
}
return by;
}
public static byte[] encryptPassword(string password, byte[] salt){
System.Security.Cryptography.SHA256 shaM = new System.Security.Cryptography.SHA256Managed();
System.Text.Encoding enc = new System.Text.UTF8Encoding();
return shaM.ComputeHash(concatArrays(enc.GetBytes(password), salt));
}
public static bool isCorrectPassword(string inputPassword, byte[] DBsalt, byte[] DBpassword)
{
return compare(encryptPassword(inputPassword, DBsalt), DBpassword);
}
}
【问题讨论】:
-
抱歉,我误解了 MSDN 库的术语。
标签: c# multithreading static private