public static string Encrypt(string plainText, string encryptionKey) { //string EncryptionKey = "tahaahat"; if (plainText == null) { return(string.Empty); } byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(plainText); using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create()) { System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.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 (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); } plainText = HttpServerUtility.UrlTokenEncode(ms.ToArray()); } } return(plainText); }
public static void KriptoFile(string dosyalar, string password = "******", string uzanti = ".uzanti") { System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(password, @byte); System.IO.FileStream fs = new System.IO.FileStream(dosyalar + uzanti, System.IO.FileMode.Create); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(fs, rm.CreateEncryptor(rfc.GetBytes(32), rfc.GetBytes(16)), System.Security.Cryptography.CryptoStreamMode.Write); System.IO.FileStream fs2 = new System.IO.FileStream(dosyalar, System.IO.FileMode.Open, System.IO.FileAccess.Read); int temp; temp = fs2.ReadByte(); while (temp != -1) { cs.WriteByte((byte)temp); temp = fs2.ReadByte(); } //Close işlemleri , silmeyin. Mümkünse hiç bi' yeri ellemeyin. cs.Close(); fs.Close(); fs2.Close(); System.IO.File.Delete(dosyalar); //Bu biraz farklı , ilk önce dosyaların kopyasını oluşturup şifreler. Daha sonra siler. }
/// <summary> /// Computes the PBKDF2-SHA1 hash of a password. /// </summary> /// <param name="password">The password to hash.</param> /// <param name="salt">The salt.</param> /// <param name="iterations">The PBKDF2 iteration count.</param> /// <param name="outputBytes">The length of the hash to generate, in bytes.</param> /// <returns>A hash of the password.</returns> private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes) { var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt); pbkdf2.IterationCount = iterations; return(pbkdf2.GetBytes(outputBytes)); }
public static string HashPassword(string password) //Takes a string and creates hash of the string { //STEP 1 Create the salt value with a cryptographic PRNG: byte[] salt; new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(salt = new byte[16]); //STEP 2 Create the Rfc2898DeriveBytes and get the hash value: var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10000); //Note: Depending on the performance requirements of your specific application, the value '10000' can be reduced. // A minimum value should be around 1000. byte[] hash = pbkdf2.GetBytes(20); //STEP 3 Combine the salt and password bytes for later use: byte[] hashBytes = new byte[36]; System.Array.Copy(salt, 0, hashBytes, 0, 16); System.Array.Copy(hash, 0, hashBytes, 16, 20); //STEP 4 Turn the combined salt+hash into a string for storage string savedPasswordHash = System.Convert.ToBase64String(hashBytes); //STEP 5 Return hashed password (It will be 48 characters long) return(savedPasswordHash); }
public void Authenticate(string user, string base64HMAC, byte[] nonce, System.IO.MemoryStream stream) { using (SC.Utility.Lock l = new SC.Utility.Lock(secLock, SC.Utility.Lock.LockType.ForReading)) { if (!users.ContainsKey(user)) { Logger.Error("Someone tried to login with username " + user); throw new System.Security.SecurityException("Invalid authentication. Check your username and password."); } string password = users[user].Password; byte[] key = new System.Security.Cryptography.Rfc2898DeriveBytes(password, nonce, 997).GetBytes(64); System.Security.Cryptography.HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(key); string computedBase64HMAC = Convert.ToBase64String(hmac.ComputeHash(stream.ToArray())); stream.Seek(0, System.IO.SeekOrigin.Begin); if (base64HMAC == computedBase64HMAC) { if (users[user].LastConnect < DateTime.Now - new TimeSpan(0, 10, 0)) { Logger.Info("User " + user + " authenticated."); } users[user].SetUserConnected(); System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(user), new string[] { USER_ROLE }); } else { Logger.Error("User " + user + " failed to authenticate."); throw new System.Security.SecurityException("Invalid authentication. Check your username and password."); } } }
/// <summary> /// Encripcion Byte /// </summary> /// <param name="clearData">Datos en limpio.</param> /// <param name="Password">Clave.</param> /// <returns>Arreglo de byte's.</returns> private static byte[] Encrypt(byte[] clearData, string Password) { byte[] tmpBytes = { 73, 118 }; System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(Password, tmpBytes); return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16)); }
private void LoadSecureParameters(byte[] key, byte[] encIv, byte[] encSalt) { this.algo.IV = encIv; this.salt = encSalt; System.Security.Cryptography.Rfc2898DeriveBytes pwDeriveAlg = new System.Security.Cryptography.Rfc2898DeriveBytes(key, salt, 2000); this.algo.Key = pwDeriveAlg.GetBytes(32); }
public string Hash(string pass, string saltASCII = null, bool saveUsedSalt = false) {//# byte[] saltBytes = null; //is new salt needed or other is provided if (saltASCII == null || saltASCII.Length != this.salt64Length) { saltBytes = NewSalt(); if (saveUsedSalt) { this.salt = Convert.ToBase64String(saltBytes); } } else { saltBytes = Convert.FromBase64String(saltASCII); if (saveUsedSalt) { this.salt = saltASCII; } } var derived = new System.Security.Cryptography.Rfc2898DeriveBytes(pass, saltBytes, 30000); //100 000 takes about 3 sec var derived64 = Convert.ToBase64String(derived.GetBytes(this.derivedLength)); var salt64 = Convert.ToBase64String(saltBytes); /*return $"{derived64} (len: {derived64.Length})\n" + * $"{salt64} (len: {salt64.Length})";*/ return(derived64); }
/// <summary> /// Verify the user - entered password against a stored password /// </summary> /// <returns></returns> public static bool VerifyPassword(string passwordFromDb, string enteredPassword) { if (enteredPassword == null || passwordFromDb == null) { return(false); } //Fetch the stored value string savedPasswordHash = passwordFromDb; //Extract the bytes byte[] hashBytes = Convert.FromBase64String(savedPasswordHash); //Get the salt byte[] salt = new byte[16]; Array.Copy(hashBytes, 0, salt, 0, 16); //Compute the hash on the password the user entered var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(enteredPassword, salt, 10000); byte[] hash = pbkdf2.GetBytes(20); //Compare the results for (int i = 0; i < 20; i++) { if (hashBytes[i + 16] != hash[i]) { return(false); } } return(true); }
// Encrypt bytes into bytes using a password. // Uses Encrypt(byte[], byte[], byte[]) public static byte[] Encrypt(byte[] clearData, string sPassword) { //System.Security.Cryptography.PasswordDeriveBytes pdb = null; System.Security.Cryptography.Rfc2898DeriveBytes pdb2 = null; try { // We need to turn the password into Key and IV. // We are using salt to make it harder to guess our key // using a dictionary attack - // trying to guess a password by enumerating all possible words. //pdb = new System.Security.Cryptography.PasswordDeriveBytes(sPassword, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); pdb2 = new System.Security.Cryptography.Rfc2898DeriveBytes(sPassword, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); // Now get the key/IV and do the encryption using the function // that accepts byte arrays. // Using PasswordDeriveBytes object we are first getting // 32 bytes for the Key // (the default Rijndael key length is 256bit = 32bytes) // and then 16 bytes for the IV. // IV should always be the block size, which is by default // 16 bytes (128 bit) for Rijndael. // If you are using DES/TripleDES/RC2 the block size is 8 // bytes and so should be the IV size. // You can also read KeySize/BlockSize properties off the // algorithm to find out the sizes. //return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16)); return(Encrypt(clearData, pdb2.GetBytes(32), pdb2.GetBytes(16))); } catch (Exception ex) { Logger.Error(ex); return(null); } }
private static string ComputeHash(string password, byte[] salt, int iterationCount, int hashSize) { var hasher = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, iterationCount); var bytes = hasher.GetBytes(hashSize); var strHash = Vita.Common.HexUtil.ByteArrayToHex(bytes); return strHash; }
private void init() { this.mode = new SicBlockCipher(new AesFastEngine()); // si las claves de encriptación no han sido inicializadas, las calculamos y las almacenamos en los valores estáticos. if (ClavesTokenizador.EncriptIV == null) { byte[] _salt = Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["Seguridad.Sal"]); System.Security.Cryptography.RijndaelManaged aesAlg = null; try { // Calculamos los valores de las claves de encriptación para ser usadas en el algoritmo System.Security.Cryptography.Rfc2898DeriveBytes key = new System.Security.Cryptography.Rfc2898DeriveBytes(ConfigurationManager.AppSettings["Seguridad.Secreto"], _salt); aesAlg = new System.Security.Cryptography.RijndaelManaged(); this.key = key.GetBytes(aesAlg.KeySize / 8); this.iv = key.GetBytes(aesAlg.BlockSize / 8); // Asignamos las variables de claves de ecnriptación a memoria ClavesTokenizador.EncriptKey = this.key; ClavesTokenizador.EncriptKey = this.iv; } catch { }; } else { // Obtenemos las variables de las claves del tokenizador de memoria this.key = ClavesTokenizador.EncriptKey; this.iv = ClavesTokenizador.EncriptIV; } }
public static string Encrypt(string input, string pwdValue) { try { byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input); byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue); // AesManaged - 高级加密标准(AES) 对称算法的管理类 System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged(); // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数) // 通过 密码 和 salt 派生密钥 System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; aes.Key = rfc.GetBytes(aes.KeySize / 8); aes.IV = rfc.GetBytes(aes.BlockSize / 8); // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象 System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor(); // 加密后的输出流 System.IO.MemoryStream encryptStream = new System.IO.MemoryStream(); // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接 System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream(encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write); // 将一个字节序列写入当前 CryptoStream (完成加密的过程) encryptor.Write(data, 0, data.Length); encryptor.Close(); // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串 string encryptedString = Convert.ToBase64String(encryptStream.ToArray()); return(encryptedString); } catch { } return(input); }
public bool AddNewUser(string password, PublicUserDTO userDto) { try { var userentity = userDto.ToPublicUser();// userDto.ToUser(); var salt = new Byte[32]; using (var provider = new System.Security.Cryptography.RNGCryptoServiceProvider()) { provider.GetBytes(salt); // Generated salt } var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt); pbkdf2.IterationCount = 1000; byte[] hash = pbkdf2.GetBytes(32); // Hashed and salted password userentity.Salt = salt; userentity.Password = hash; userentity.IssueDate = DateTime.Now; _dBContext.PublicUsers.Add(userentity); return(_dBContext.SaveChanges() > 0); } catch (Exception ex) { return(false); } }
private static byte[] Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; var saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (System.IO.MemoryStream ms = new MemoryStream()) { using (System.Security.Cryptography.RijndaelManaged AES = new RijndaelManaged()) { var key = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.KeySize = 256; AES.BlockSize = 128; AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); cs.Close(); } encryptedBytes = ms.ToArray(); } } return(encryptedBytes); }
public string EncryptPassword(string clearText) { string encryptedText = ""; string EncryptionKey = "Xavier"; byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create()) { System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.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 (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); } encryptedText = Convert.ToBase64String(ms.ToArray()); } } return(encryptedText); }
private string Decrypt(string cipher, string type) { string EncryptionKey; byte[] cipherBytes; EncryptionKey = string.Format(this.Core.GetAttribute("DecryptKey"), type); cipherBytes = Convert.FromBase64String(cipher); using (System.Security.Cryptography.Rijndael encryptor = System.Security.Cryptography.Rijndael.Create()) { System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKey, Convert.FromBase64String(this.Core.GetAttribute("DecryptSalt"))); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipher = System.Text.Encoding.Unicode.GetString(ms.ToArray()); } } return(cipher); }
public static bool AreEqual(string salt, string hashed, string plain) { using (System.Security.Cryptography.Rfc2898DeriveBytes generator = new System.Security.Cryptography.Rfc2898DeriveBytes(plain, Convert.FromBase64String(salt))) { generator.IterationCount = IterationCount; return(generator.GetBytes(32).SequenceEqual(Convert.FromBase64String(hashed))); } }
private static string ComputeHash(string password, byte[] salt, int iterationCount, int hashSize) { var hasher = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, iterationCount); var bytes = hasher.GetBytes(hashSize); var strHash = Vita.Common.HexUtil.ByteArrayToHex(bytes); return(strHash); }
public static bool AreEqual(string hashedPassword, string salt, string plainPassword) { using (var rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(plainPassword, Convert.FromBase64String(salt))) { rfc.IterationCount = MaxIterations; return(rfc.GetBytes(PwdSize).SequenceEqual(Convert.FromBase64String(hashedPassword))); } }
public byte[] PasswordBasedKey(int keyLength, string password, byte[] saltBytes, int iterationCount) { using (System.Security.Cryptography.Rfc2898DeriveBytes pbk = new System.Security.Cryptography.Rfc2898DeriveBytes( password, saltBytes, iterationCount)) { return(pbk.GetBytes(keyLength)); } }
/// <summary> /// Hashes user password /// </summary> /// <param name="password">Password</param> /// <returns>Hash string</returns> public static string GetPasswordHash(string salt, string password) { var saltBytes = System.Text.Encoding.ASCII.GetBytes(salt); using (var rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, saltBytes, 1000)) { return(System.Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(128))); } }
public static byte[] createPasswordKey(string password, byte[] salt) { //TODO: change hash algorithm... var iterations = 10000; // Choose a value that will perform well given your hardware. var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, iterations); var hash = pbkdf2.GetBytes(32); // Get 32 bytes for the hash return hash; }
private static async System.Threading.Tasks.Task <ResultType> TaskMain(Fee.Crypt.OnCryptTask_CallBackInterface a_callback_interface, byte[] a_binary, int a_index, int a_length, string a_pass, string a_salt, Fee.TaskW.CancelToken a_cancel) #endif { ResultType t_ret; { t_ret.binary = null; t_ret.errorstring = null; } try{ //RijndaelManaged System.Security.Cryptography.RijndaelManaged t_rijndael = new System.Security.Cryptography.RijndaelManaged(); t_rijndael.KeySize = 256; t_rijndael.BlockSize = 128; t_rijndael.Mode = System.Security.Cryptography.CipherMode.CBC; { byte[] t_salt = System.Text.Encoding.UTF8.GetBytes(a_salt); System.Security.Cryptography.Rfc2898DeriveBytes t_derivebyte = new System.Security.Cryptography.Rfc2898DeriveBytes(a_pass, t_salt); t_derivebyte.IterationCount = 1000; t_rijndael.Key = t_derivebyte.GetBytes(t_rijndael.KeySize / 8); t_rijndael.IV = t_derivebyte.GetBytes(t_rijndael.BlockSize / 8); Tool.Log("Key", System.BitConverter.ToString(t_rijndael.Key)); Tool.Log("IV", System.BitConverter.ToString(t_rijndael.IV)); } //TransformFinalBlock using (System.Security.Cryptography.ICryptoTransform t_decryptor = t_rijndael.CreateDecryptor()){ t_ret.binary = t_decryptor.TransformFinalBlock(a_binary, a_index, a_length); } }catch (System.Exception t_exception) { t_ret.binary = null; t_ret.errorstring = "Task_DecryptPass : "******"Task_DecryptPass : Cancel"; a_cancel.ThrowIfCancellationRequested(); } if (t_ret.binary == null) { if (t_ret.errorstring == null) { t_ret.errorstring = "Task_DecryptPass : null"; } } return(t_ret); }
public void InitializeSecureParameters(byte[] key) { // init rijndael IV this.algo.GenerateIV(); salt = new byte[saltSize]; rngAlgo.GetBytes(salt); System.Security.Cryptography.Rfc2898DeriveBytes pwDeriveAlg = new System.Security.Cryptography.Rfc2898DeriveBytes(key, salt, 2000); this.algo.Key = pwDeriveAlg.GetBytes(32); this.key = key; }
/// <summary> /// Encriptar texto /// </summary> /// <param name="clearText">Texto a encriptar.</param> /// <param name="Password">Password con el cual encriptar el texto.</param> /// <returns>Cadena con el texto encriptado</returns> public static string Encrypt(string clearText, string Password) { byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); byte[] tmpBytes = { 64, 36, 16, 18, 25, 119, 21, 40 }; System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(Password, tmpBytes); byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return System.Convert.ToBase64String(encryptedData); }
/// <summary> /// Creates the CryptoServiceProvider based on the PBKDF2. /// </summary> /// <param name="inPBKDF2">Input PBKDF2</param> /// <returns>CSP</returns> private System.Security.Cryptography.AesCryptoServiceProvider createCSP(System.Security.Cryptography.Rfc2898DeriveBytes inPBKDF2) { inPBKDF2.Reset(); csp = new System.Security.Cryptography.AesCryptoServiceProvider(); csp.Mode = this.cipherMode; csp.Padding = this.paddingMode; csp.Key = inPBKDF2.GetBytes(csp.KeySize / 8); csp.IV = inPBKDF2.GetBytes(csp.BlockSize / 8); return(csp); }
// Decrypt a file into another file using a password. public static void Decrypt(string sInputFilepath, string sOutputFilepath, string sPassword) { System.IO.FileStream fsIn = null; System.IO.FileStream fsOut = null; //System.Security.Cryptography.PasswordDeriveBytes pdb = null; System.Security.Cryptography.Rfc2898DeriveBytes pdb2 = null; System.Security.Cryptography.Rijndael alg = null; System.Security.Cryptography.CryptoStream cs = null; try { // First we are going to open the file streams. fsIn = new System.IO.FileStream(sInputFilepath, System.IO.FileMode.Open, System.IO.FileAccess.Read); fsOut = new System.IO.FileStream(sOutputFilepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); // Then we are going to derive a Key and an IV from the Password and create an algorithm. //pdb = new System.Security.Cryptography.PasswordDeriveBytes(sPassword, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); pdb2 = new System.Security.Cryptography.Rfc2898DeriveBytes(sPassword, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); alg = System.Security.Cryptography.Rijndael.Create(); //alg.Key = pdb.GetBytes(32); alg.Key = pdb2.GetBytes(32); //alg.IV = pdb.GetBytes(16); alg.IV = pdb2.GetBytes(16); // Now create a crypto stream through which we are going to be pumping data. // Our fileOut is going to be receiving the Decrypted bytes. cs = new System.Security.Cryptography.CryptoStream(fsOut, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write); // Now will will initialize a buffer and will be processing the input file in chunks. // This is done to avoid reading the whole file (which can be huge) into memory. int iBufferLen = 4096; byte[] buffer = new byte[iBufferLen]; int iRead; do { // read a chunk of data from the input file. iRead = fsIn.Read(buffer, 0, iBufferLen); // Decrypt it. cs.Write(buffer, 0, iRead); } while (iRead != 0); } catch (Exception ex) { Logger?.Error(ex); } finally { // close everything. if (cs != null) { cs.Close(); cs = null; } // this will also close the unrelying fsOut stream if (fsIn != null) { fsIn.Close(); fsIn = null; } } }
public async Task <AccessToken> Create(Guid userId) { var encryptor = new System.Security.Cryptography.Rfc2898DeriveBytes(Guid.NewGuid().ToString(), Guid.NewGuid().ToByteArray()); var value = Convert.ToBase64String(encryptor.GetBytes(500)); var token = new Token(value, userId); await db.Tokens.AddAsync(token); await db.SaveChangesAsync(); return(ToAccessToken(token)); }
public static string HashPassword(string plainPassword, out string salt) { byte[] rawSalt; salt = GenerateSalt(SaltSize, out rawSalt); using (var rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(plainPassword, rawSalt)) { rfc.IterationCount = MaxIterations; return(Convert.ToBase64String(rfc.GetBytes(PwdSize))); } }
private static byte[] GetPbkdf2Bytes(string password, byte[] salt, int iterations, int outputBytes) { byte[] hashBytes = null; using (System.Security.Cryptography.Rfc2898DeriveBytes pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt)) { pbkdf2.IterationCount = iterations; hashBytes = pbkdf2.GetBytes(outputBytes); } // End Using pbkdf2 return(hashBytes); }
/// <summary> /// This method initializes the Aes used to encrypt or decrypt the dataset. /// </summary> /// <param name="username">Username to use for the encryption</param> /// <param name="password">Password to use for the encryption</param> /// <returns>New instance of Aes</returns> private static System.Security.Cryptography.Aes InitAes(string username, string password) { System.Security.Cryptography.Aes aes = new System.Security.Cryptography.AesManaged(); System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, System.Text.Encoding.Unicode.GetBytes(username)); aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7; aes.KeySize = 128; aes.Key = rfc2898.GetBytes(16); aes.IV = rfc2898.GetBytes(16); return(aes); }
public static string Generate(string plainPassword, out string salt) { byte[] passwordPayload; using (System.Security.Cryptography.Rfc2898DeriveBytes generator = new System.Security.Cryptography.Rfc2898DeriveBytes(plainPassword, 32)) { generator.IterationCount = IterationCount; salt = Convert.ToBase64String(generator.Salt); passwordPayload = generator.GetBytes(32); } return(Convert.ToBase64String(passwordPayload)); }
/// <summary> /// 根据给定的字符串对其进行加密 /// </summary> /// <param name="input">需要加密的字符串</param> /// <returns>加密后的字符串</returns> public static string Encrypt(string input) { // 盐值 string saltValue = "saltValue"; // 密码值 string pwdValue = "pwdValue"; byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input); byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue); // AesManaged - 高级加密标准(AES) 对称算法的管理类 System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged(); // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数) // 通过 密码 和 salt 派生密钥 System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt); /**/ /* * AesManaged.BlockSize - 加密操作的块大小(单位:bit) * AesManaged.LegalBlockSizes - 对称算法支持的块大小(单位:bit) * AesManaged.KeySize - 对称算法的密钥大小(单位:bit) * AesManaged.LegalKeySizes - 对称算法支持的密钥大小(单位:bit) * AesManaged.Key - 对称算法的密钥 * AesManaged.IV - 对称算法的密钥大小 * Rfc2898DeriveBytes.GetBytes(int 需要生成的伪随机密钥字节数) - 生成密钥 */ aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; aes.Key = rfc.GetBytes(aes.KeySize / 8); aes.IV = rfc.GetBytes(aes.BlockSize / 8); // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象 System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor(); // 加密后的输出流 System.IO.MemoryStream encryptStream = new System.IO.MemoryStream(); // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接 System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream (encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write); // 将一个字节序列写入当前 CryptoStream (完成加密的过程) encryptor.Write(data, 0, data.Length); encryptor.Close(); // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串 string encryptedString = Convert.ToBase64String(encryptStream.ToArray()); return encryptedString; }
static ClientConfig() { Aes = CryptoProviderFactory.Instance.CreateSymmetric(SdmSymmetricAlgorithm.AES); Aes.KeySize = 256; var salt = new byte[] { 0x10, 0x77, 0x16, 0x18, 0xf7, 0x6a, 0x8d, 0x0f }; var tsm = new Rfc2898DeriveBytes("octoc@t", salt); var keySize = Aes.KeySize / 8; Aes.Key = tsm.GetBytes(keySize); var blockSize = Aes.IV.Length; Aes.IV = tsm.GetBytes(blockSize); }
public string createHashedPassword(string pwd) { var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); byte[] salt = new byte[8]; rng.GetBytes(salt); // Create an 8 byte salt var iterations = 1000; // Choose a value that will perform well given your hardware. var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(pwd, salt, iterations); var hash = pbkdf2.GetBytes(60); // Get 60 bytes for the hash var str = System.Text.Encoding.Default.GetString(hash); Console.WriteLine(str); return hash.ToString(); }
/// <summary> /// パスワードから共有キーと初期化ベクタを生成する /// </summary> /// <param name="password">基になるパスワード</param> /// <param name="keySize">共有キーのサイズ(ビット)</param> /// <param name="key">作成された共有キー</param> /// <param name="blockSize">初期化ベクタのサイズ(ビット)</param> /// <param name="iv">作成された初期化ベクタ</param> private static void GenerateKeyFromPassword(string password, int keySize, out byte[] key, int blockSize, out byte[] iv) { //パスワードから共有キーと初期化ベクタを作成する //salt byte[] salt = System.Text.Encoding.UTF8.GetBytes("ProjectBy宮城県工業高等学校"); //Rfc2898DeriveBytesオブジェクトを作成する System.Security.Cryptography.Rfc2898DeriveBytes deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt); //1000回の反復処理回数 deriveBytes.IterationCount = 1000; //共有キーと初期化ベクタを生成する key = deriveBytes.GetBytes(keySize / 8); iv = deriveBytes.GetBytes(blockSize / 8); }
private void Initialize() { System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, RFC2898_ITERATIONS); KeyBytes = rfc2898.GetBytes(KeySizeInBytes); // 16 or 24 or 32 ??? IvBytes = rfc2898.GetBytes(KeySizeInBytes); generatedVerifyValue = rfc2898.GetBytes(2); short verify = BitConverter.ToInt16(passwordVerifyValue, 0); if (password != null) { short generated = BitConverter.ToInt16(generatedVerifyValue, 0); if (verify != generated) throw new InvalidFormatException("bad password"); } }
/// <summary> /// パスワードから共有キーと初期化ベクタを生成する /// </summary> /// <param name="password">基になるパスワード</param> /// <param name="keySize">共有キーのサイズ(ビット)</param> /// <param name="key">作成された共有キー</param> /// <param name="blockSize">初期化ベクタのサイズ(ビット)</param> /// <param name="iv">作成された初期化ベクタ</param> private static void GenerateKeyFromPassword(string password, int keySize, out byte[] key, int blockSize, out byte[] iv) { //パスワードから共有キーと初期化ベクタを作成する //saltを決める byte[] salt = System.Text.Encoding.UTF8.GetBytes("saltは必ず8バイト以上"); //Rfc2898DeriveBytesオブジェクトを作成する System.Security.Cryptography.Rfc2898DeriveBytes deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt); //.NET Framework 1.1以下の時は、PasswordDeriveBytesを使用する //System.Security.Cryptography.PasswordDeriveBytes deriveBytes = // new System.Security.Cryptography.PasswordDeriveBytes(password, salt); //反復処理回数を指定する デフォルトで1000回 deriveBytes.IterationCount = 1000; //共有キーと初期化ベクタを生成する key = deriveBytes.GetBytes(keySize / 8); iv = deriveBytes.GetBytes(blockSize / 8); }
/// <summary> /// /// </summary> /// <param name="input"></param> /// <returns></returns> public static string Decrypt(string input) { byte[] encryptBytes = Convert.FromBase64String(input); byte[] salt = Encoding.UTF8.GetBytes(saltValue); System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged(); System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; aes.Key = rfc.GetBytes(aes.KeySize / 8); aes.IV = rfc.GetBytes(aes.BlockSize / 8); System.Security.Cryptography.ICryptoTransform transform = aes.CreateDecryptor(); System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream (stream, transform, System.Security.Cryptography.CryptoStreamMode.Write); decryptor.Write(encryptBytes, 0, encryptBytes.Length); decryptor.Close(); byte[] decryptBytes = stream.ToArray(); return UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); }
/// <summary> /// /// </summary> /// <param name="input"></param> /// <returns></returns> public static string Encrypt(string input) { byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input); byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue); System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged(); System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; aes.Key = rfc.GetBytes(aes.KeySize / 8); aes.IV = rfc.GetBytes(aes.BlockSize / 8); System.Security.Cryptography.ICryptoTransform encrypt = aes.CreateEncryptor(); System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream (stream, encrypt, System.Security.Cryptography.CryptoStreamMode.Write); encryptor.Write(data, 0, data.Length); encryptor.Close(); return Convert.ToBase64String(stream.ToArray()); }
/// <summary> /// generates RFC2898 PBKDF2 secure key used for PhotoShop Communication /// </summary> /// <param name="password"> /// password to encode, /// should be composed of ascii visible characters ([\x20-\x7E]) /// </param> /// <returns> /// byte array containing generated RFC2898 PBKDF2 secure key. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// thrown when password argument contains characters /// except ascii visible characters ([\x20-\x7E]) /// </exception> public static byte[] DerivePBKDF2Key( this string password) { // password should be ascii visible characters ([\x20-\x7E]) if (false == password.IsPhotoShopPBKDF2AcceptableString()) { throw new ArgumentOutOfRangeException( "password", "password should be composed of " + "ascii visible characters ([\x20-\x7E])."); } var passwordBytes = Encoding.ASCII.GetBytes(password); // salt value assumes ascii encoding var saltBytes = Encoding.ASCII.GetBytes(PhotoShopConstants.SALT); // generate pbkdf2 key var pbkdf2KeyGenerator = new System.Security.Cryptography.Rfc2898DeriveBytes( passwordBytes, saltBytes, PhotoShopConstants.ITERATION_COUNT); // get key byte arrays with given key-length return pbkdf2KeyGenerator.GetBytes(PhotoShopConstants.KEY_LENGTH); }
bool ProcessEncryptionPwd() { System.Security.Cryptography.Rfc2898DeriveBytes pbkdf2 = null; if (tbEncryptionPwd.Text == "[UNCHANGED]") // Password hasn't changed from when the package was loaded return true; if (string.IsNullOrEmpty(tbEncryptionPwd.Text)) return true; // Nothing to do really if (!string.IsNullOrEmpty(virtPackage.GetProperty("EncryptionPwdKey")) && !string.IsNullOrEmpty(virtPackage.GetProperty("EncryptionPwdHash")) && !string.IsNullOrEmpty(virtPackage.GetProperty("EncryptionPwdSalt")) && !string.IsNullOrEmpty(virtPackage.GetProperty("EncryptionPwdIV"))) { // EncryptionPwd* properties are already set. Only need to re-generate them if password has changed (different from EncryptionPwdHash) string pwdSaltStr = virtPackage.GetProperty("EncryptionPwdSalt"); var pwdSalt = Utils.HexUndump(pwdSaltStr); // Check if password is unchanged // PBKDF2 first time on entered password pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(tbEncryptionPwd.Text, pwdSalt, Pbkdf2Iterations); var enteredPwdHash = pbkdf2.GetBytes(KeySizeBytes); // PBKDF2 second time on entered password pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(enteredPwdHash, pwdSalt, Pbkdf2Iterations); enteredPwdHash = pbkdf2.GetBytes(KeySizeBytes); var savedPwdHash = Utils.HexUndump(virtPackage.GetProperty("EncryptionPwdHash")); bool equals = true; for (int i = 0; i < enteredPwdHash.Length; i++) { if (enteredPwdHash[i] != savedPwdHash[i]) equals = false; } if (equals) return true; // Password hasn't changed } bool Ret = true; var rngCsp = new System.Security.Cryptography.RNGCryptoServiceProvider(); // Steps for password-based key: // 1. Generate a long key (this is just a randomly generated amount of bytes in hex, you can use 128 bytes). // Use this key to encrypt your file with AES (meaning you use it as a password) byte[] randomKey = new byte[KeySizeBytes]; // Our AES algorithm uses a 128-bit key (16 bytes) rngCsp.GetBytes(randomKey); // <-- The key with which files will be encrypted / decrypted // 2. Encrypt the key itself with AES using your password (which is a bit shorter but easier to remember. // Now AES requires this again to be either 128, 192 or 256 bits of length so you need to make your // password of that length. Hence you can just use PBKDF2 (or scrypt or bcrypt) to create a fixed key // length from your password. DO NOT STORE THIS. byte[] salt = new byte[SaltSize]; rngCsp.GetBytes(salt); // Transform user password into a key that we can encrypt randomKey with pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(Encoding.ASCII.GetBytes(tbEncryptionPwd.Text), salt, Pbkdf2Iterations); var keyEncryptionKey = pbkdf2.GetBytes(KeySizeBytes); // tbEncryptionPwd.Text -> Key. This key will be used for encrypting randomKey. var keyEncryptor = new System.Security.Cryptography.RijndaelManaged(); keyEncryptor.BlockSize = 128; keyEncryptor.Mode = System.Security.Cryptography.CipherMode.CFB; keyEncryptor.Padding = System.Security.Cryptography.PaddingMode.None; keyEncryptor.Key = keyEncryptionKey; keyEncryptor.GenerateIV(); var encryptor = keyEncryptor.CreateEncryptor(keyEncryptor.Key, keyEncryptor.IV); var msEncrypt = new MemoryStream(); using (var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { using (var swEncrypt = new BinaryWriter(csEncrypt)) { byte[] toWrite = randomKey;//Encoding.ASCII.GetBytes("1234567890123456"); swEncrypt.Write(toWrite); } } var encryptedKey = msEncrypt.ToArray(); // <-- randomKey encrypted with AES, whose key = PBKDF2(tbEncryptionPwd.Text) // 3. Keep a hash of your hashed password using PBKDF2 (or bcrypt or scrypt). This will allow you to check // if the password is correct before trying to decrypt your encrypted key: // hash(hash(password)) --> can be stored // hash(password) --> should not be stored pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(keyEncryptionKey, salt, Pbkdf2Iterations); // Iterations slow down hashing (which helps against brute-force) var keyEncryptionKeyHashed = pbkdf2.GetBytes(KeySizeBytes); // Second PBKDF2 hash // Store Ret &= virtPackage.SetProperty("EncryptionPwdKey", Utils.HexDump(encryptedKey)); // Encryption key, in encrypted form Ret &= virtPackage.SetProperty("EncryptionPwdHash", Utils.HexDump(keyEncryptionKeyHashed)); // Password hash, for user password validation Ret &= virtPackage.SetProperty("EncryptionPwdSalt", Utils.HexDump(salt)); // Salt used for both PBKDF2 password hashes (first and second) Ret &= virtPackage.SetProperty("EncryptionPwdIV", Utils.HexDump(keyEncryptor.IV)); // IV used for encrypting the key with AES return Ret; }
/// <summary> /// Initializa os objetos necessários para realizar criptografia e descriptografia. /// </summary> private void Initialize() { System.Security.Cryptography.RijndaelManaged v_rijndael; System.Security.Cryptography.Rfc2898DeriveBytes v_passwordbytes; byte[] v_initvectorbytes; byte[] v_keybytes; v_rijndael = new System.Security.Cryptography.RijndaelManaged(); v_rijndael.Mode = System.Security.Cryptography.CipherMode.CBC; v_initvectorbytes = System.Text.Encoding.ASCII.GetBytes(this.v_initvector); v_passwordbytes = new System.Security.Cryptography.Rfc2898DeriveBytes(this.v_password, v_initvectorbytes, 1); v_keybytes = v_passwordbytes.GetBytes(this.v_keysize / 8); this.v_encryptor = v_rijndael.CreateEncryptor(v_keybytes, v_initvectorbytes); this.v_decryptor = v_rijndael.CreateDecryptor(v_keybytes, v_initvectorbytes); }
static byte[] GetSecureHash(string password, byte[] salt) { var rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt); return rfc.GetBytes(64); }
/// <summary> /// パスワードから共有キー/初期化ベクタを生成 /// </summary> /// <param name="password">パスワード</param> /// <param name="keySize">共有キーサイズ(ビット)</param> /// <param name="key">共有キー</param> /// <param name="blockSize">初期化ベクタサイズ(ビット)</param> /// <param name="iv">初期化ベクタ</param> /// <param name="iterationCnt">反復処理回数</param> private void GenerateKeyFromPassword(string password, int keySize, out byte[] key, int blockSize, out byte[] iv, int iterationCnt) { // パスワードから共有キーと初期化ベクタを作成(salt決定) byte[] salt = System.Text.Encoding.UTF8.GetBytes("u+-J$ejeP/+%5lDe9_oVk#Q4p/cchi3C"); // Rfc2898DeriveBytesオブジェクト作成 System.Security.Cryptography.Rfc2898DeriveBytes deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt); // 反復処理回数 deriveBytes.IterationCount = iterationCnt; // 共有キー/初期化ベクタを生成 key = deriveBytes.GetBytes(keySize / 8); iv = deriveBytes.GetBytes(blockSize / 8); }
public static bool isPasswordValid(string c_sPassword, byte [] c_baSalt, byte [] c_baPasswordKey) { //TODO: change hash algorithm... var iterations = 10000; // Choose a value that will perform well given your hardware. var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(c_sPassword, c_baSalt, iterations); var hash = pbkdf2.GetBytes(32); // Get 32 bytes for the hash if (hash == c_baPasswordKey) { return true; } return false; }
public void Authenticate(string user, string base64HMAC, byte[] nonce, System.IO.MemoryStream stream) { using (SC.Utility.Lock l = new SC.Utility.Lock(secLock, SC.Utility.Lock.LockType.ForReading)) { if (!users.ContainsKey(user)) { Logger.Error("Someone tried to login with username " + user); throw new System.Security.SecurityException("Invalid authentication. Check your username and password."); } string password = users[user].Password; byte[] key = new System.Security.Cryptography.Rfc2898DeriveBytes(password, nonce, 997).GetBytes(64); System.Security.Cryptography.HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(key); string computedBase64HMAC = Convert.ToBase64String(hmac.ComputeHash(stream.ToArray())); stream.Seek(0, System.IO.SeekOrigin.Begin); if (base64HMAC == computedBase64HMAC) { if (users[user].LastConnect < DateTime.Now - new TimeSpan(0, 10, 0)) Logger.Info("User " + user + " authenticated."); users[user].SetUserConnected(); System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(user), new string[] { USER_ROLE }); } else { Logger.Error("User " + user + " failed to authenticate."); throw new System.Security.SecurityException("Invalid authentication. Check your username and password."); } } }