我有以下代码与私有静态成员。这些私有静态成员是否线程安全?
所有这些类都表示它们在MSDN库中对于“public 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库的术语。 – 2012-02-20 17:39:12