本文整理汇总了C#中System.Security.Cryptography.RNGCryptoServiceProvider.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# RNGCryptoServiceProvider.Dispose方法的具体用法?C# RNGCryptoServiceProvider.Dispose怎么用?C# RNGCryptoServiceProvider.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.RNGCryptoServiceProvider
的用法示例。
在下文中一共展示了RNGCryptoServiceProvider.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetSalt
private string GetSalt()
{
RNGCryptoServiceProvider saltGen = null;
string salt = string.Empty;
try
{
saltGen = new RNGCryptoServiceProvider();
byte[] buffer = new byte[Constants.SALT_SIZE];
saltGen.GetBytes(buffer);
salt = Convert.ToBase64String(buffer);
}
catch (Exception e)
{
throw e;
}
finally
{
if (saltGen != null)
{
saltGen.Dispose();
saltGen = null;
}
}
return salt;
}
示例2: ComputeHash
public static string ComputeHash(string plaintext, Supported_HA hash, byte[] salt)
{
int minSaltLength = 4;
int maxSaltLenght = 6;
byte[] SaltBytes = null;
if(salt!=null)
{
SaltBytes = salt;
}
else
{
Random r = new Random();
int SaltLenght = r.Next(minSaltLength, maxSaltLenght);
SaltBytes = new byte[SaltLenght];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(SaltBytes);
rng.Dispose();
}
byte[] plaintData = ASCIIEncoding.UTF8.GetBytes(plaintext);
byte[] plainDataAndSalt = new byte[plaintData.Length + SaltBytes.Length];
for(int x=0; x<plaintData.Length;x++)
{
plainDataAndSalt[x] = plaintData[x];
}
for (int n = 0; n < SaltBytes.Length; n++)
plainDataAndSalt[plaintData.Length + n] = SaltBytes[n];
byte[] hashValue = null;
switch(hash)
{
case Supported_HA.SHA256:
SHA256Managed sha= new SHA256Managed();
hashValue= sha.ComputeHash(plainDataAndSalt);
sha.Dispose();
break;
case Supported_HA.SHA384:
SHA384Managed sha1 = new SHA384Managed();
hashValue = sha1.ComputeHash(plainDataAndSalt);
sha1.Dispose();
break;
case Supported_HA.SHA512:
SHA512Managed sha2 = new SHA512Managed();
hashValue = sha2.ComputeHash(plainDataAndSalt);
sha2.Dispose();
break;
}
byte[] resuflt = new byte[hashValue.Length + SaltBytes.Length];
for (int x = 0; x < hashValue.Length; x++)
resuflt[x] = hashValue[x];
for (int n = 0; n < SaltBytes.Length; n++)
resuflt[hashValue.Length + n] = SaltBytes[n];
return Convert.ToBase64String(resuflt);
}
示例3: CreateKey
/// <summary>
/// Generates a random key
/// </summary>
/// <param name="numberOfBytes">
/// length of the key in bytes
/// </param>
/// <returns>
/// The create key.
/// </returns>
public static string CreateKey(int numberOfBytes)
{
if (numberOfBytes < 1)
{
throw new ArgumentOutOfRangeException("numberOfBytes");
}
RNGCryptoServiceProvider rng = null;
try
{
rng = new RNGCryptoServiceProvider();
var buff = new byte[numberOfBytes];
rng.GetBytes(buff);
return buff.BytesToHexString();
}
finally
{
if (rng != null)
{
rng.Dispose();
}
}
}
示例4: Server
public Server()
{
this.name = String.Empty;
this.sqlHost = String.Empty;
this.sqlPort = 3306;
this.sqlUser = String.Empty;
this.sqlPassword = String.Empty;
this.sshHost = String.Empty;
this.sshPort = 22;
this.sshUser = String.Empty;
this.sshPassword = String.Empty;
this.useSSHTunnel = false;
RNGCryptoServiceProvider sqlRng = new RNGCryptoServiceProvider();
byte[] sqlBuffer = new byte[1024];
sqlRng.GetBytes(sqlBuffer);
this.sqlEntropy = BitConverter.ToString(sqlBuffer);
sqlRng.Dispose();
RNGCryptoServiceProvider sshRng = new RNGCryptoServiceProvider();
byte[] sshBuffer = new byte[1024];
sshRng.GetBytes(sshBuffer);
this.sshEntropy = BitConverter.ToString(sshBuffer);
sshRng.Dispose();
this._encryptedSqlPassword = String.Empty;
this._encryptedSshPassword = String.Empty;
}
示例5: GenerateRandomString
/// <summary>
/// Generate a random string of characters
/// </summary>
/// <param name="length">length of string</param>
/// <param name="type">type of string to be generated</param>
/// <returns></returns>
public static string GenerateRandomString(int length, StringType type)
{
switch (type)
{
case StringType.AlphaNumeric:
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
char[] chars = new char[length];
Random rd = new Random();
for (int i = 0; i < length; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
break;
case StringType.AlphaNumericSymbol:
//Generate a cryptographic random number.
var rng = new RNGCryptoServiceProvider();
var buff = new byte[length];
rng.GetBytes(buff);
rng.Dispose();
// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
break;
default:
throw new ArgumentException("Type not supported");
}
}
示例6: testRng
bool testRng(Session session)
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(session);
byte[] data1 = new byte[1024];
byte[] data2 = new byte[1024];
byte[] data3 = new byte[1024];
rng.GetBytes(data1);
rng.GetBytes(data2);
rng.Dispose();
rng = new RNGCryptoServiceProvider(session);
rng.GetBytes(data3);
rng.Dispose();
int same = 0;
for (int i = 0; i < data1.Length; i++)
{
if (data1[i] == data2[i] || data1[i] == data3[i] || data2[i] == data3[i]) same++;
}
return same < 32; // ~3% matching elements
}
示例7: CreateHash
/// <summary>
/// Creates a salted PBKDF2 hash of the password.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <returns>The hash of the password.</returns>
public static string CreateHash(string password)
{
// Generate a random salt
RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
byte[] salt = new byte[SALT_BYTE_SIZE];
csprng.GetBytes(salt);
// Hash the password and encode the parameters
byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
csprng.Dispose();
return PBKDF2_ITERATIONS + ":" +
Convert.ToBase64String(salt) + ":" +
Convert.ToBase64String(hash);
}
示例8: GenerateRandomNumber
public static int GenerateRandomNumber()
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Buffer storage.
byte[] data = new byte[4];
// Fill buffer.
rng.GetBytes(data);
// Convert to int 32.
int value = BitConverter.ToInt32(data, 0);
rng.Dispose();
return value;
}
示例9: WriteFile
/// <summary>
/// 產生指定大小的隨機byte數據檔案
/// </summary>
/// <param name="randomCount">byte數量</param>
public static void WriteFile(int randomCount,string fileName)
{
RandomNumberGenerator ranObj = new RNGCryptoServiceProvider();
byte[] randomData = new byte[randomCount];
string filePath = AppDomain.CurrentDomain.BaseDirectory + @"\" + fileName;
// 1. Byte Array產生Random數據
ranObj.GetBytes(randomData);
ranObj.Dispose();
// 2. 寫入字串並稍為改寫字串表達意義
StringBuilder ranStr = new StringBuilder();
foreach (byte b in randomData)
{
ranStr.Append(String.Format("0x{0:X2}, ", b));
}
// 3. 寫入檔案流中
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
sw.Write(ranStr.ToString(0, ranStr.Length - 2));//多兩個字串 => ", " 所以扣2
sw.Flush();
}
}
}
示例10: SaveLastUsedFields
private void SaveLastUsedFields()
{
Settings.Default.ShowBasicInfo = GetActiveUserControl().checkBoxShowBasicInfo.Checked;
Settings.Default.LockSmartScriptId = GetActiveUserControl().checkBoxLockEventId.Checked;
Settings.Default.ListActionLists = GetActiveUserControl().checkBoxListActionlistsOrEntries.Checked;
Settings.Default.AllowChangingEntryAndSourceType = GetActiveUserControl().checkBoxAllowChangingEntryAndSourceType.Checked;
Settings.Default.PhaseHighlighting = GetActiveUserControl().checkBoxUsePhaseColors.Checked;
Settings.Default.ShowTooltipsStaticly = GetActiveUserControl().checkBoxUseStaticTooltips.Checked;
string lastStaticInfoPerTab = String.Empty;
//entryorguid,sourceTypeIndex,entryorguid,sourceTypeIndex,entryorguid,sourceTypeIndex,....
foreach (UserControlSAI uc in userControls)
lastStaticInfoPerTab += uc.textBoxEntryOrGuid.Text + "-" + uc.comboBoxSourceType.SelectedIndex + ",";
Settings.Default.LastStaticInfoPerTab = lastStaticInfoPerTab;
if (formState == FormState.FormStateLogin)
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buffer = new byte[1024];
rng.GetBytes(buffer);
string salt = BitConverter.ToString(buffer);
rng.Dispose();
Settings.Default.Entropy = salt;
Settings.Default.Host = textBoxHost.Text;
Settings.Default.User = textBoxUsername.Text;
Settings.Default.Password = textBoxPassword.Text.Length == 0 ? String.Empty : textBoxPassword.Text.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
Settings.Default.Database = textBoxWorldDatabase.Text;
Settings.Default.Port = CustomConverter.ToUInt32(textBoxPort.Text);
Settings.Default.UseWorldDatabase = radioButtonConnectToMySql.Checked;
Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;
}
Settings.Default.Save();
}
示例11: SaveLastUsedFields
private void SaveLastUsedFields()
{
Settings.Default.LastEntryOrGuid = textBoxEntryOrGuid.Text;
Settings.Default.LastSourceType = comboBoxSourceType.SelectedIndex;
Settings.Default.ShowBasicInfo = checkBoxShowBasicInfo.Checked;
Settings.Default.LockSmartScriptId = checkBoxLockEventId.Checked;
Settings.Default.ListActionLists = checkBoxListActionlistsOrEntries.Checked;
Settings.Default.AllowChangingEntryAndSourceType = checkBoxAllowChangingEntryAndSourceType.Checked;
Settings.Default.PhaseHighlighting = checkBoxUsePhaseColors.Checked;
Settings.Default.ShowTooltipsPermanently = checkBoxUsePermanentTooltips.Checked;
if (formState == FormState.FormStateLogin)
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buffer = new byte[1024];
rng.GetBytes(buffer);
string salt = BitConverter.ToString(buffer);
rng.Dispose();
Settings.Default.Entropy = salt;
Settings.Default.Host = textBoxHost.Text;
Settings.Default.User = textBoxUsername.Text;
Settings.Default.Password = textBoxPassword.Text.Length == 0 ? String.Empty : textBoxPassword.Text.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
Settings.Default.Database = textBoxWorldDatabase.Text;
Settings.Default.Port = XConverter.ToUInt32(textBoxPort.Text);
Settings.Default.UseWorldDatabase = radioButtonConnectToMySql.Checked;
Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;
}
Settings.Default.Save();
}
示例12: GenerateRandomFileName
/// <summary>
/// 生成随机文件名
/// </summary>
/// <returns></returns>
public static string GenerateRandomFileName()
{
var key = new byte[10];
RNGCryptoServiceProvider rng = null;
try
{
rng = new RNGCryptoServiceProvider();
rng.GetBytes(key);
char[] rndCharArray = ToBase32StringSuitableForDirName(key).ToCharArray();
rndCharArray[8] = '.';
return new String(rndCharArray, 0, 12);
}
finally
{
if (rng != null)
rng.Dispose();
}
}
示例13: alterarSenhaUsuario
}//criarUsuario()
public static int alterarSenhaUsuario(Usuario usuario)
{
//SqlDataReader dr = null;
SqlConnection conn = null;
SqlCommand cmd = null;
SqlTransaction trans = null;
RNGCryptoServiceProvider rnd;
//String strSql = "UPDATE id_usuario from Usuario where email='" + novousuario.Email + "'";
try
{
conn = new SqlConnection(ConnString);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
rnd = new RNGCryptoServiceProvider();
byte[] salt = new byte[20];
rnd.GetBytes(salt);
rnd.Dispose();
String strSalt = byteArray2String(salt);
cmd.CommandText = "UPDATE Usuario set password = '";
cmd.CommandText += GetSHA1HashData(strSalt + usuario.Password) + "', salt='" + strSalt + "' where id_usuario = ";
cmd.CommandText += usuario.IdUsuario.ToString();
trans = conn.BeginTransaction();
cmd.Transaction = trans;
cmd.ExecuteNonQuery();
trans.Commit();
return 0;//sucesso
}
catch
{
//if (dr != null) dr.Close();
trans.Rollback();
return 1;//erro
}
finally
{
//if (dr != null) dr.Close();
if (conn != null) conn.Close();
}
}//alterarSenhaUsuario()
示例14: criarUsuario
public static EnumUserCreationResult criarUsuario(Usuario novousuario)
{
/*
id_usuario
apelido
email
password
salt
celular
*/
SqlDataReader dr = null;
SqlConnection conn = null;
SqlCommand cmd = null;
SqlTransaction trans = null;
RNGCryptoServiceProvider rnd;
String strSql = "SELECT id_usuario from Usuario where email='" + novousuario.Email + "'";
try
{
conn = new SqlConnection(ConnString);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = strSql;
trans = conn.BeginTransaction();
cmd.Transaction = trans;
dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
trans.Rollback();
return EnumUserCreationResult.EMAIL_JA_EXISTENTE;
}
dr.Close();
strSql = "SELECT id_usuario from Usuario where apelido='" + novousuario.Apelido + "'";
cmd.CommandText = strSql;
dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
trans.Rollback();
return EnumUserCreationResult.APELIDO_JA_EXISTENTE;
}
dr.Close();
strSql = "INSERT into Usuario(apelido, email, celular, password, salt, token) output Inserted.id_usuario VALUES ('";
strSql += Utils.limpaString(novousuario.Apelido) + "','" + Utils.limpaString(novousuario.Email) + "','";
strSql += Utils.limpaString(novousuario.Celular) + "'"; // +"',convert(binary(20),'";
rnd = new RNGCryptoServiceProvider();
byte[] salt = new byte[20];
rnd.GetBytes(salt);
rnd.Dispose();
String strSalt = byteArray2String(salt);
//strSql += GetSHA1HashData(strSalt + novousuario.Password) + "'), convert(binary(20),'" + strSalt + "'),'";
//strSql += GetSHA1HashData(novousuario.Password) + "'), convert(binary(20),'" + strSalt + "'),'";
strSql += ",'" + GetSHA1HashData(strSalt + novousuario.Password) + "'";
strSql += ",'" + strSalt + "'";
novousuario.Token = Guid.NewGuid();
strSql += ",'" + novousuario.Token.ToString() + "')";
cmd.CommandText = strSql;
dr = cmd.ExecuteReader();
if (dr.Read())
{
novousuario.IdUsuario = System.Convert.ToInt32(dr["id_usuario"]);
}
dr.Close();
trans.Commit();
return EnumUserCreationResult.SUCCESS;
}
catch
{
if (dr != null) dr.Close();
trans.Rollback();
return EnumUserCreationResult.UNKNOWN_ERROR;
}
finally
{
if (dr != null) dr.Close();
if (conn != null) conn.Close();
}
}//criarUsuario()
示例15: DefaultTest
/// <summary>
/// Simple test.
/// </summary>
/// <param name="wordSize">number of byte of the key</param>
/// <param name="testPrecision">percision of the test, error = 1/2^precision</param>
/// <returns>result of the test</returns>
public static bool DefaultTest(uint wordSize=128, uint testPrecision=20)
{
if (wordSize < 8 || testPrecision < 1)
{
System.Console.WriteLine("FiatShamirIdentification test invalid input\n");
return false;
}
uint iteration = 0;
bool choice;
BigInteger number;
bool result = true;
var generator = new RNGCryptoServiceProvider();
var priv = PrivateKey.NewKey(generator, wordSize);
var pub = priv.GetPublicKey();
Verifier verifier = pub.GetVerifier();
Proover proover = priv.GetProover(generator);
//test with key
while (iteration < testPrecision && result)
{
number = proover.Step1();
choice = verifier.Step1(ref number);
number = proover.Step2(choice);
verifier.Step2(number);
result = verifier.CheckState();
iteration++;
}
if (!result) //if not verified, fail
{
System.Console.WriteLine("FiatShamirIdentification test ERROR\n");
generator.Dispose();
return false;
}
//test without key
var genwrap = new GeneratorWrap(generator, wordSize);
var falseKey = new PrivateKey(genwrap.GetBig(), genwrap.GetBig(), wordSize);
proover = new Proover(falseKey, generator);
iteration = 0;
while (iteration < testPrecision && result)
{
number = proover.Step1();
choice = verifier.Step1(ref number);
number = proover.Step2(choice);
verifier.Step2(number);
result = verifier.CheckState();
iteration++;
}
if (result) //if verified, fail
{
System.Console.WriteLine("FiatShamirIdentification test ERROR\n");
generator.Dispose();
return false;
}
System.Console.WriteLine("FiatShamirIdentification test OK\n");
generator.Dispose();
return true;
}