public static string Criptografar(string texto) { if(string.IsNullOrEmpty(texto)) return String.Empty; string outStr; RijndaelManaged aesAlg = null; try { var key = new Rfc2898DeriveBytes(Segredo, Complemento); aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8); var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (var msEncrypt = new MemoryStream()) { using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (var swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(texto); } } outStr = Convert.ToBase64String(msEncrypt.ToArray()); } } finally { if (aesAlg != null) aesAlg.Clear(); } return outStr; }
public static string Descriptografar(string codigo) { try { if (string.IsNullOrEmpty(codigo)) return String.Empty; string retorno; var chave = new Rfc2898DeriveBytes(Segredo, Complemento); var algoritimo = new RijndaelManaged(); algoritimo.Key = chave.GetBytes(algoritimo.KeySize / 8); algoritimo.IV = chave.GetBytes(algoritimo.BlockSize / 8); var descriptografor = algoritimo.CreateDecryptor(algoritimo.Key, algoritimo.IV); var bytes = Convert.FromBase64String(codigo); using (var memoryStream = new MemoryStream(bytes)) using (var cryptoStream = new CryptoStream(memoryStream, descriptografor, CryptoStreamMode.Read)) using (var streamReader = new StreamReader(cryptoStream)) retorno = streamReader.ReadToEnd(); algoritimo.Clear(); return retorno; } catch (Exception) { return "DEU PAU"; } }
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; // Set your salt here, change it to meet your flavor: // The salt bytes must be at least 8 bytes. byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); 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 static string Encrypt(string clearText) { byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_Pwd, _Salt); byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return Convert.ToBase64String(encryptedData); }
public static string Decrypt(string ciphertext, string key) { if (string.IsNullOrEmpty(ciphertext)) throw new ArgumentNullException("cipherText"); if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); var allTheBytes = Convert.FromBase64String(ciphertext); var saltBytes = allTheBytes.Take(_saltSize).ToArray(); var ciphertextBytes = allTheBytes.Skip(_saltSize).Take(allTheBytes.Length - _saltSize).ToArray(); using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, saltBytes)) { var keyBytes = keyDerivationFunction.GetBytes(32); var ivBytes = keyDerivationFunction.GetBytes(16); using (var aesManaged = new AesManaged()) using (var decryptor = aesManaged.CreateDecryptor(keyBytes, ivBytes)) using (var memoryStream = new MemoryStream(ciphertextBytes)) using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) using (var streamReader = new StreamReader(cryptoStream)) { return streamReader.ReadToEnd(); } } }
public string Encrypt(string clearText, string EncryptionKey) { byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); using (Aes encryptor = Aes.Create()) { System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKey, new byte[] { 73, 118, 97, 110, 32, 77, 101, 100, 118, 101, 100, 101, 118 }); 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(); } clearText = System.Convert.ToBase64String(ms.ToArray()); } } return(clearText); }
/// <summary> /// Cryptographic transformation /// </summary> /// <param name="password"></param> /// <param name="encrypt"></param> /// <returns></returns> private static ICryptoTransform GetTransform(bool Encrypt) { // Create an instance of the Rihndael class. RijndaelManaged Cipher = new System.Security.Cryptography.RijndaelManaged(); // Calculate salt to make it harder to guess key by using a dictionary attack. byte[] Salt = SaltFromPassword(); // Generate Secret Key from the password and salt. // Note: Set number of iterations to 10 in order for JavaScript example to work faster. Rfc2898DeriveBytes SecretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(Keys.KEY, Salt, 10); // Create a encryptor from the existing SecretKey bytes by using // 32 bytes (256 bits) for the secret key and // 16 bytes (128 bits) for the initialization vector (IV). byte[] SecretKeyBytes = SecretKey.GetBytes(32); byte[] InitializationVectorBytes = SecretKey.GetBytes(16); ICryptoTransform Cryptor = null; if (Encrypt) { Cryptor = Cipher.CreateEncryptor(SecretKeyBytes, InitializationVectorBytes); } else { Cryptor = Cipher.CreateDecryptor(SecretKeyBytes, InitializationVectorBytes); } return(Cryptor); }
/// <summary> /// Decrypts the specified string. /// </summary> /// <param name="cipherText">The string to be decrypted.</param> /// <param name="key">The key.</param> /// <returns></returns> public static string Decrypt(this string cipherText, string key) { byte[] cipherBytes = Convert.FromBase64String(cipherText); Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return Encoding.Unicode.GetString(decryptedData); }
/// <summary> /// Encrypts the specified string. /// </summary> /// <param name="clearText">The string to be encrypted.</param> /// <param name="key">The key.</param> /// <returns></returns> public static string Encrypt(this string clearText, string key) { byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return Convert.ToBase64String(encryptedData); }
public static void EncryptAndUpload(string file, string awsPath, string key) { if (bool.Parse(ConfigurationManager.AppSettings["ManagedEncryption"])) { Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, appKey); using (var aes = new AesCryptoServiceProvider()) { aes.Key = deriveBytes.GetBytes(aes.KeySize / 8); aes.IV = deriveBytes.GetBytes(aes.BlockSize / 8); using (var temp = new FileStream(file + "_encrypted", FileMode.Create)) { using (var stream = new CryptoStream(new FileStream(file, FileMode.Open), aes.CreateEncryptor(), CryptoStreamMode.Read)) { stream.CopyTo(temp); } } UploadFile(file + "_encrypted", awsPath); File.Delete(file + "_encrypted"); } } else UploadFile(file, awsPath); }
public void DecryptFile(string sourceFilename, string destinationFilename, string password) { AesManaged aes = new AesManaged(); aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; // NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides. Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); aes.Mode = CipherMode.CBC; ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV); using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write)) { try { using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { source.CopyTo(cryptoStream); } } catch (CryptographicException exception) { if (exception.Message == "Padding is invalid and cannot be removed.") throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception); else throw; } } } }
public static string Encrypt(string plainText, string key) { if(string.IsNullOrEmpty(plainText)) { throw new ArgumentNullException("plainText"); } if(string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } using(var keyDerivationFunction = new Rfc2898DeriveBytes(key, SALT_SIZE)) { byte[] saltBytes = keyDerivationFunction.Salt; byte[] keyBytes = keyDerivationFunction.GetBytes(32); byte[] ivBytes = keyDerivationFunction.GetBytes(16); using(var aesManaged = new AesManaged()) { aesManaged.KeySize = 256; using(var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes)) { MemoryStream memoryStream = null; CryptoStream cryptoStream = null; return WriteMemoryStream(plainText, ref saltBytes, encryptor, ref memoryStream, ref cryptoStream); } } } }
private static Aes CreateAes(ProgramOptions options, byte[] iv = null) { if (!options.EncryptionEnabled) return null; var salt = Convert.FromBase64String("hkuDTnecxj+oDytliJ69BQ=="); using (var kdf = new Rfc2898DeriveBytes(options.EncryptionPassword, salt)) { var aes = new AesCryptoServiceProvider(); var keyLen = aes.KeySize/8; if (iv != null) { aes.Key = kdf.GetBytes(keyLen); aes.IV = iv; return aes; } var ivLength = aes.BlockSize/8; var bytes = kdf.GetBytes(keyLen + ivLength); aes.Key = bytes.SubArray(0, keyLen); aes.IV = bytes.SubArray(keyLen, ivLength); return aes; } }
/// <summary> /// 解密 /// </summary> public static string AESDecrypt(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); // 用当前的 Key 属性和初始化向量 IV 创建对称解密器对象 System.Security.Cryptography.ICryptoTransform decryptTransform = aes.CreateDecryptor( ); // 解密后的输出流 System.IO.MemoryStream decryptStream = new System.IO.MemoryStream( ); // 将解密后的目标流(decryptStream)与解密转换(decryptTransform)相连接 System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream( decryptStream, decryptTransform, System.Security.Cryptography.CryptoStreamMode.Write); // 将一个字节序列写入当前 CryptoStream (完成解密的过程) decryptor.Write(encryptBytes, 0, encryptBytes.Length); decryptor.Close( ); // 将解密后所得到的流转换为字符串 byte[] decryptBytes = decryptStream.ToArray( ); string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); return(decryptedString); }
//http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt public string Encrypt(string data) { byte[] bytesToBeEncrypted = Encoding.ASCII.GetBytes(data); byte[] passwordBytes = Encoding.ASCII.GetBytes(_configManager.Get("encryptionPassword")); byte[] encryptedBytes = null; // Set your salt here, change it to meet your flavor: // The salt bytes must be at least 8 bytes. byte[] saltBytes = Encoding.ASCII.GetBytes(_configManager.Get("encryptionSalt")); using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); 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; return ASCIIEncoding.ASCII.GetString(encryptedBytes); }
public string Encrypt(string value) { string encryptedValue; using (var aes = AesManaged.Create()) { aes.KeySize = 256; aes.BlockSize = 128; var saltBytes = Encoding.UTF8.GetBytes(_encryptionContext.Salt); var password = new Rfc2898DeriveBytes(_encryptionContext.Key, saltBytes); var vectorBytes = password.GetBytes(aes.BlockSize / 8); using (var encryptor = aes.CreateEncryptor(password.GetBytes(aes.KeySize / 8), vectorBytes)) { using (var memoryStream = new MemoryStream()) { var lockObject = new Object(); lock (lockObject) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { var valueBytes = Encoding.UTF8.GetBytes(value); cryptoStream.Write(valueBytes, 0, valueBytes.Length); cryptoStream.FlushFinalBlock(); var encryptedBytes = memoryStream.ToArray(); encryptedValue = Convert.ToBase64String(encryptedBytes); } } } } } return encryptedValue; }
internal static void DecryptFile(string inputPath, string outputPath, string password) { var input = new FileStream(inputPath, FileMode.Open, FileAccess.Read); var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write); // Essentially, if you want to use RijndaelManaged as AES you need to make sure that: // 1.The block size is set to 128 bits // 2.You are not using CFB mode, or if you are the feedback size is also 128 bits var algorithm = new RijndaelManaged { KeySize = 256, BlockSize = 128 }; var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(Salt)); algorithm.Key = key.GetBytes(algorithm.KeySize / 8); algorithm.IV = key.GetBytes(algorithm.BlockSize / 8); try { using (var decryptedStream = new CryptoStream(output, algorithm.CreateDecryptor(), CryptoStreamMode.Write)) { CopyStream(input, decryptedStream); } } catch (CryptographicException) { throw new InvalidDataException("Please supply a correct password"); } catch (Exception ex) { throw new Exception(ex.Message); } input.Close(); output.Close(); }
private byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes) { byte[] decryptedBytes = null; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); 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.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length); cs.Close(); } decryptedBytes = ms.ToArray(); } } return decryptedBytes; }
public string Decrypt(string cipherText) { try { cipherText = cipherText.Replace(" ", "+"); string EncryptionKey = "MAKV2SPBNI99212"; byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new 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 (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } return cipherText; } catch { throw; } }
public static string Encrypt(string plainText, string key) { if (string.IsNullOrEmpty(plainText)) throw new ArgumentNullException("plainText"); if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, _saltSize)) { var saltBytes = keyDerivationFunction.Salt; var keyBytes = keyDerivationFunction.GetBytes(32); var ivBytes = keyDerivationFunction.GetBytes(16); using (var aesManaged = new AesManaged()) using (var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes)) using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) using (var streamWriter = new StreamWriter(cryptoStream)) streamWriter.Write(plainText); var cipherTextBytes = memoryStream.ToArray(); Array.Resize(ref saltBytes, saltBytes.Length + cipherTextBytes.Length); Array.Copy(cipherTextBytes, 0, saltBytes, _saltSize, cipherTextBytes.Length); return Convert.ToBase64String(saltBytes); } } }
public static string Encrypt(this string text) { if (string.IsNullOrEmpty(text)) { return null; } byte[] rawPlaintext = System.Text.Encoding.Unicode.GetBytes(text); byte[] cipherText = null; using (Aes aes = new AesManaged()) { aes.Padding = PaddingMode.PKCS7; aes.KeySize = AesKeySizeInBits; int KeyStrengthInBytes = aes.KeySize / 8; System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(Password, Salt, Rfc2898KeygenIterations); aes.Key = rfc2898.GetBytes(KeyStrengthInBytes); aes.IV = rfc2898.GetBytes(KeyStrengthInBytes); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(rawPlaintext, 0, rawPlaintext.Length); } cipherText = ms.ToArray(); } return ByteArrayToString(cipherText); } }
protected static byte[] encoded(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; byte[] saltBytes = new byte[] { 2, 15, 240, 232, 39, 204, 190, 33, 226, 206, 110, 107, 61, 25, 87, 196 }; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; AES.Padding = PaddingMode.Zeros; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); 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); } encryptedBytes = ms.ToArray(); } } return encryptedBytes; }
private static string Decrypt(byte[] cipher, string passPhrase, string salt, SymmetricAlgorithm algorithm) { var saltBytes = Encoding.UTF8.GetBytes(salt); algorithm.Padding = PaddingMode.None; using (algorithm) { using (var password = new Rfc2898DeriveBytes(passPhrase, saltBytes)) { algorithm.Key = password.GetBytes(algorithm.KeySize / 8); algorithm.IV = password.GetBytes(algorithm.BlockSize / 8); using (var memStream = new MemoryStream(cipher)) { using ( var cryptoStream = new CryptoStream(memStream, algorithm.CreateDecryptor(), CryptoStreamMode.Read)) { using (var sr = new StreamReader(cryptoStream)) { return sr.ReadToEnd(); } } } } } }
/// <summary> /// Decrypts the value <paramref name="toDecrypt"/> using the <paramref name="password"/>. /// </summary> /// <param name="password">The password.</param> /// <param name="toDecrypt">The value to decrypt.</param> /// <returns>Decrypted value</returns> public static string Decrypt(string password, string toDecrypt) { Rijndael rinedal = null; byte[] toDecBytes = Convert.FromBase64String(toDecrypt); try { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, GenerateSalt(password)); rinedal = Rijndael.Create(); rinedal.Padding = PaddingMode.ISO10126; ICryptoTransform tx = rinedal.CreateDecryptor(pdb.GetBytes(32), pdb.GetBytes(16)); byte[] decrypted = tx.TransformFinalBlock(toDecBytes, 0, toDecBytes.Length); return Encoding.Default.GetString(decrypted); } finally { if (rinedal != null) { rinedal.Clear(); } } }
public static string AES_Encrypt(string data, string keyData, string salt) { byte[] dataBytes = Convert.FromBase64String(data); byte[] keyBytes = Convert.FromBase64String(keyData); byte[] saltBytes = Convert.FromBase64String(salt); byte[] encryptedBytes = null; using (MemoryStream ms = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(keyBytes, saltBytes, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Padding = PaddingMode.PKCS7; AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(dataBytes, 0, dataBytes.Length); // cs.Close(); } encryptedBytes = ms.ToArray(); } } return Convert.ToBase64String(encryptedBytes); }
public string Decrypt(string cipherText, string encryptionKey) { byte[] cipherBytes = Convert.FromBase64String(cipherText); try { using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new 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 (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } } catch { cipherText = "problem decrypting"; } return cipherText; }
public static void DecryptAes(Stream inStream, Stream outStream, string password) { if (inStream == null) { throw new ArgumentNullException("inStream"); } if (outStream == null) { throw new ArgumentNullException("outStream"); } if (password == null) { throw new ArgumentNullException("password"); } // generate an encryption key with the shared secret and salt using (var key = new Rfc2898DeriveBytes(password, Salt)) { using (var aesAlg = new RijndaelManaged()) { aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8); using (var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)) { using (var csEncrypt = new CryptoStream(inStream, decryptor, CryptoStreamMode.Read)) { csEncrypt.CopyTo(outStream); } } } } }
/// <summary> /// Encrypts the plainText input using the given Key. /// A 128 bit random salt will be generated and prepended to the ciphertext before it is returned. /// </summary> /// <param name="plainText">The plain text to encrypt.</param> /// <param name="password">The plain text encryption key.</param> /// <returns>The salt and the ciphertext</returns> public static byte[] Encrypt(byte[] plainText, string password) { if (plainText == null || plainText.Length == 0) throw new ArgumentNullException("plainText"); if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password"); // Derive a new Salt, Key, and IV from the password using (var keyDerivationFunction = new Rfc2898DeriveBytes(password, SaltSize)) { var saltBytes = keyDerivationFunction.Salt; var keyBytes = keyDerivationFunction.GetBytes(32); var ivBytes = keyDerivationFunction.GetBytes(16); using (var aesManaged = new AesManaged()) using (var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes)) using (var memoryStream = new MemoryStream()) using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { using (var streamWriter = new BinaryWriter(cryptoStream)) { streamWriter.Write(plainText); } var cipherTextBytes = memoryStream.ToArray(); Array.Resize(ref saltBytes, saltBytes.Length + cipherTextBytes.Length); Array.Copy(cipherTextBytes, 0, saltBytes, SaltSize, cipherTextBytes.Length); return saltBytes; } } }
private AESCrypto() { var pdb = new Rfc2898DeriveBytes(aesPasswd, aesSalt); aes = new AesManaged(); aes.Key = pdb.GetBytes(aes.KeySize / 8); aes.IV = pdb.GetBytes(aes.BlockSize / 8); }
/// <summary> /// Decrypt a string /// </summary> /// <param name="input">Input string in base 64 format</param> /// <returns>Decrypted string</returns> public static string Decrypt(string input, string password) { byte[] encryptedBytes = Convert.FromBase64String(input); byte[] saltBytes = Encoding.UTF8.GetBytes(password); string decryptedString = string.Empty; using (var aes = new AesManaged()) { Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes); 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); using (ICryptoTransform decryptTransform = aes.CreateDecryptor()) { using (MemoryStream decryptedStream = new MemoryStream()) { CryptoStream decryptor = new CryptoStream(decryptedStream, decryptTransform, CryptoStreamMode.Write); decryptor.Write(encryptedBytes, 0, encryptedBytes.Length); decryptor.Flush(); decryptor.Close(); byte[] decryptBytes = decryptedStream.ToArray(); decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); } } } return decryptedString; }
/// <summary> /// Decrypts the ciphertext using the Key. /// </summary> /// <param name="ciphertext">The ciphertext to decrypt.</param> /// <param name="password">The plain text encryption key.</param> /// <returns>The decrypted text.</returns> public static byte[] Decrypt(byte[] cipherText, string password) { if (cipherText == null || cipherText.Length == 0) throw new ArgumentNullException("cipherText"); if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password"); // Extract the salt from our ciphertext var saltBytes = cipherText.Take(SaltSize).ToArray(); var ciphertextBytes = cipherText.Skip(SaltSize).ToArray(); using (var keyDerivationFunction = new Rfc2898DeriveBytes(password, saltBytes)) { // Derive the previous Key and IV from the password and salt var keyBytes = keyDerivationFunction.GetBytes(32); var ivBytes = keyDerivationFunction.GetBytes(16); using (var aesManaged = new AesManaged()) using (var decryptor = aesManaged.CreateDecryptor(keyBytes, ivBytes)) using (var memoryStream = new MemoryStream(ciphertextBytes)) using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) using (var outputStream = new StreamReader(cryptoStream)) using (var outMemoryStream = new MemoryStream()) { outputStream.BaseStream.CopyTo(outMemoryStream); return outMemoryStream.ToArray(); } } }
public static string AESRijndaelDecodifica(string textoSujo) { try { string FraseSeguranca = "VagnerFDP"; byte[] vetorTextoSujo = Convert.FromBase64String(textoSujo); using (Aes encryptor = Aes.Create()) { //RFC -> passar blocos de memória (16, 32 e 64) // passar a frase de segurança para a alocação e comparação dos valores contidos nos blocos Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(FraseSeguranca, new byte[] { 0x49, 0x72, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); // passo a frase de segurança convertida para o AES (Key) encryptor.Key = rdb.GetBytes(32); //alocação os blocos com as informações da key encryptor.IV = rdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(vetorTextoSujo, 0, vetorTextoSujo.Length); cs.Close(); } textoSujo = Encoding.Unicode.GetString(ms.ToArray()); } } } catch { return "Erro!"; } return textoSujo; }
/// <summary> /// Decrypts the ciphertext using the Key. /// </summary> /// <param name="ciphertext">The ciphertext to decrypt.</param> /// <param name="key">The plain text encryption key.</param> /// <returns>The decrypted text.</returns> public static string Decrypt(string ciphertext, string key) { if (string.IsNullOrEmpty(ciphertext)) throw new ArgumentNullException("cipherText"); if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); // Extract the salt from our ciphertext var allTheBytes = Convert.FromBase64String(ciphertext); var saltBytes = allTheBytes.Take(_saltSize).ToArray(); var ciphertextBytes = allTheBytes.Skip(_saltSize).Take(allTheBytes.Length - _saltSize).ToArray(); using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, saltBytes)) { // Derive the previous IV from the Key and Salt var keyBytes = keyDerivationFunction.GetBytes(32); var ivBytes = keyDerivationFunction.GetBytes(16); // Create a decrytor to perform the stream transform. // Create the streams used for decryption. // The default Cipher Mode is CBC and the Padding is PKCS7 which are both good using (var aesManaged = new AesManaged()) using (var decryptor = aesManaged.CreateDecryptor(keyBytes, ivBytes)) using (var memoryStream = new MemoryStream(ciphertextBytes)) using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) using (var streamReader = new StreamReader(cryptoStream)) { // Return the decrypted bytes from the decrypting stream. return streamReader.ReadToEnd(); } } }
private void PrepareAesObject(byte[] Salt, Aes aes) { aes.Padding = PaddingMode.PKCS7; aes.KeySize = AesKeySizeInBits; int KeyStrengthInBytes = aes.KeySize / 8; System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(Password, Salt, Rfc2898KeygenIterations); aes.Key = rfc2898.GetBytes(KeyStrengthInBytes); aes.IV = rfc2898.GetBytes(KeyStrengthInBytes); }
private void _GenerateCryptoBytes() { //Console.WriteLine(" provided password: '******'", _Password); System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(_Password, Salt, Rfc2898KeygenIterations); _keyBytes = rfc2898.GetBytes(_KeyStrengthInBytes); // 16 or 24 or 32 ??? _MacInitializationVector = rfc2898.GetBytes(_KeyStrengthInBytes); _generatedPv = rfc2898.GetBytes(2); _cryptoGenerated = true; }
void Initialize(string password) { PBKDF2 kdf = new PBKDF2(password, mySalt); // Then you have your algorithm // When you need a key: use: byte[] key = kdf.GetBytes(16); // for a 128-bit key (16*8=128) // You can specify how many bytes you need. Same for IV. byte[] iv = kdf.GetBytes(16); // 128 bits again. // And then call your constructor, etc. // ... }
public static byte[] encryptByte(byte[] data, byte[] password, byte[] salt = null, int iterations = DEFAULT_ITERATIONS) { if (salt == null) { salt = DEFAULT_SALT; } System.Security.Cryptography.Rfc2898DeriveBytes deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, iterations); byte[] key = deriveBytes.GetBytes(AES_KEY_SIZE_BYTE); byte[] iv = deriveBytes.GetBytes(AES_BLOCK_SIZE_BITE); using (ICryptoTransform encryptor = _aes.CreateEncryptor(key, iv)) { return(encryptor.TransformFinalBlock(data, 0, data.Length)); } }
public Context(string keyPrefix, int keySize = 256, int blockSize = 128) { TestData.TestVersion = 1; //keyとivはネイティブ側やランタイムで動的生成を行い //解析されずらくしてください。 byte[] salt = System.Text.Encoding.UTF8.GetBytes("ソルト生成"); var deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes("ILbSave", salt); var key = System.Convert.ToBase64String(deriveBytes.GetBytes(keySize / 8)); var iv = System.Convert.ToBase64String(deriveBytes.GetBytes(blockSize / 8)); Debug.Log($"key:{key},iv:{iv}"); Save = new SaveData <SaveKey>(iv, key, () => keyPrefix); }
public bool AddUser(string userPassword, UsersDTO user) { try { var userentity = user.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(userPassword, salt); pbkdf2.IterationCount = 1000; byte[] hash = pbkdf2.GetBytes(32); // Hashed and salted password userentity.Salt = salt; userentity.EncPassword = hash; operationalDataContext.Users.Add(userentity); return(operationalDataContext.SaveChanges() > 0); } catch (Exception ex) { return(false); } }
public static string UserSecretkey() { string user = "******"; string password = "******"; byte[] salt = { 65, 66, 67, 68, 69, 70, 71 }; string Haskey = ""; using (var derivedBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(user, salt, iterations: 49999)) { //salt = derivedBytes.Salt; //byte[] key = derivedBytes.GetBytes(16); // 128 bits key Haskey = Convert.ToBase64String(salt); } using (var derivedBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, iterations: 49999)) { // salt = derivedBytes.Salt; byte[] key = derivedBytes.GetBytes(16); // 128 bits key Haskey = Haskey + "-" + Convert.ToBase64String(key); } return(Haskey); }
public void Test_Pbkdf2() { byte[] password = new byte[256]; byte[] salt = new byte[256]; _random.NextBytes(password); _random.NextBytes(salt); using (var hmac = new System.Security.Cryptography.HMACSHA1()) { Pbkdf2 pbkdf2 = new Pbkdf2(hmac, password, salt, 1024); System.Security.Cryptography.Rfc2898DeriveBytes rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 1024); Assert.IsTrue(CollectionUtilities.Equals(pbkdf2.GetBytes(1024), rfc2898DeriveBytes.GetBytes(1024)), "Pbkdf2 #1"); } //_random.NextBytes(password); //_random.NextBytes(salt); //using (var hmac = new System.Security.Cryptography.HMACSHA256()) //{ // CryptoConfig.AddAlgorithm(typeof(SHA256Cng), // "SHA256", // "SHA256Cng", // "System.Security.Cryptography.SHA256", // "System.Security.Cryptography.SHA256Cng"); // hmac.HashName = "System.Security.Cryptography.SHA256"; // Pbkdf2 pbkdf2 = new Pbkdf2(hmac, password, salt, 1024); // var h = pbkdf2.GetBytes(10); //} }
/// <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(int keySize, out byte[] key, int blockSize, out byte[] iv) { //パスワードから共有キーと初期化ベクタを作成する //saltを決める byte[] salt = System.Text.Encoding.UTF8.GetBytes(SALT);//saltは必ず8byte以上 //Rfc2898DeriveBytesオブジェクトを作成する System.Security.Cryptography.Rfc2898DeriveBytes deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(PASS, 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); }
public 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); }
/// <inheritdoc /> protected internal override byte[] DeriveKeyMaterial(IKeyDerivationParameters parameters, int desiredKeySize) { // Right now we're assuming that KdfGenericBinary is directly usable as a salt // in RFC2898. When our KeyDerivationParametersFactory class supports // more parameter types than just BuildForPbkdf2, we might need to adjust this code // to handle each type of parameter. byte[] salt = parameters.KdfGenericBinary; #pragma warning disable CA5379 // Do Not Use Weak Key Derivation Function Algorithm switch (this.Algorithm) { case KeyDerivationAlgorithm.Pbkdf2Sha1: using (var deriveBytes = new Platform.Rfc2898DeriveBytes(this.Key, salt, parameters.IterationCount)) { return(deriveBytes.GetBytes(desiredKeySize)); } default: #if NETSTANDARD2_0 throw new NotImplementedByReferenceAssemblyException(); #else using (var deriveBytes = new Platform.Rfc2898DeriveBytes(this.Key, salt, parameters.IterationCount, GetHashAlgorithm(this.Algorithm))) { return(deriveBytes.GetBytes(desiredKeySize)); } #endif } #pragma warning restore CA5379 // Do Not Use Weak Key Derivation Function Algorithm }
private byte[] GenerateKey() { // return new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }; var rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(this.txtPassPhrase.Text, this.Salt, Int32.Parse(this.txtIterations.Text)); return(rfc2898.GetBytes(this.KeyLengthInBytes)); }
public void ExampleScript() { // Turn input string into a byte array. var input = System.Text.Encoding.Unicode.GetBytes("Plain Text"); // Create an instance of the Rijndael class. System.Security.Cryptography.RijndaelManaged cipher; cipher = new System.Security.Cryptography.RijndaelManaged(); // Calculate salt bytes to make it harder to guess key by using a dictionary attack. var password = System.Text.Encoding.UTF8.GetBytes("password"); var hmac = new System.Security.Cryptography.HMACSHA1(password); var salt = hmac.ComputeHash(password); // Generate Secret Key from the password and salt. // Note: Set number of iterations to 10 in order for JavaScript example to work faster. var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10); // Create a encryptor from the existing SecretKey bytes by using // 32 bytes (256 bits) for the secret key and // 16 bytes (128 bits) for the initialization vector (IV). var key = secretKey.GetBytes(32); var iv = secretKey.GetBytes(16); var cryptor = cipher.CreateEncryptor(key, iv); // Create new Input. var inputBuffer = new System.Byte[input.Length]; // Copy data bytes to input buffer. System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length); // Create a MemoryStream to hold the output bytes. var stream = new System.IO.MemoryStream(); // Create a CryptoStream through which we are going to be processing our data. var mode = System.Security.Cryptography.CryptoStreamMode.Write; var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode); // Start the crypting process. cryptoStream.Write(inputBuffer, 0, inputBuffer.Length); // Finish crypting. cryptoStream.FlushFinalBlock(); // Convert data from a memoryStream into a byte array. var outputBuffer = stream.ToArray(); // Close both streams. stream.Close(); //cryptoStream.Close(); // Convert encrypted data into a base64-encoded string. var base64String = System.Convert.ToBase64String(outputBuffer); // base64String = laFf3eKu9tzB2XksJjd8EVM3PA9O30wz0Y+X3nyelW4= }
/// <summary> /// 根据参数pwd、salt使用Rfc2898DeriveBytes算法生成Pwd的值(判断合法性时使用) /// </summary> /// <param name="pwd">明文的密码</param> /// <param name="salt">密文的salt</param> /// <param name="pwdhash">密文的salt</param> public static string GetPwdhash(string pwd, string salt) { string pwdHash = ""; System.Security.Cryptography.Rfc2898DeriveBytes db; db = new System.Security.Cryptography.Rfc2898DeriveBytes(pwd, System.Convert.FromBase64String(salt), 1000); return(pwdHash = System.Convert.ToBase64String(db.GetBytes(32))); }
byte[] Transform(byte[] dataBytes, byte[] passwordBytes, bool encrypt, bool fips) { /// <summary>Encrypt by using AES-256 algorithm.</summary> // Create an instance of the Rijndael class. var cipher = fips ? new System.Security.Cryptography.AesCryptoServiceProvider() as SymmetricAlgorithm : new System.Security.Cryptography.RijndaelManaged(); // Calculate salt to make it harder to guess key by using a dictionary attack. var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes); var salt = hmac.ComputeHash(passwordBytes); // Generate Secret Key from the password and salt. // Note: Set number of iterations to 10 in order for JavaScript example to work faster. var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10); // Create a encryptor from the existing SecretKey bytes by using // 32 bytes (256 bits) for the secret key and // 16 bytes (128 bits) for the initialization vector (IV). var key = secretKey.GetBytes(32); var iv = secretKey.GetBytes(16); // Get cryptor as System.Security.Cryptography.ICryptoTransform class. var cryptor = encrypt ? cipher.CreateEncryptor(key, iv) : cipher.CreateDecryptor(key, iv); // Create new Input. var inputBuffer = new byte[dataBytes.Length]; // Copy data bytes to input buffer. System.Buffer.BlockCopy(dataBytes, 0, inputBuffer, 0, inputBuffer.Length); // Create a MemoryStream to hold the output bytes. var stream = new System.IO.MemoryStream(); // Create a CryptoStream through which we are going to be processing our data. var mode = System.Security.Cryptography.CryptoStreamMode.Write; var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode); // Start the crypting process. cryptoStream.Write(inputBuffer, 0, inputBuffer.Length); // Finish crypting. cryptoStream.FlushFinalBlock(); // Convert data from a memoryStream into a byte array. var outputBuffer = stream.ToArray(); // Close both streams. stream.Close(); cryptoStream.Close(); return(outputBuffer); }
public static byte[] GetBytes(string key, int size) { var salt = Encoding.UTF8.GetBytes("does_not_matter"); using (var derivedBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(key, salt: salt, iterations: 50000, HashAlgorithmName.SHA256)) { return(derivedBytes.GetBytes(size)); } }
/// <summary> /// Use salt and password to create Key and IV. /// </summary> private void CreateKeyAndIv() { // Convert salt and passsword to bytes. SaltBytes = System.Text.Encoding.UTF8.GetBytes(SaltTextBox.Text); PassBytes = System.Text.Encoding.UTF8.GetBytes(PasswordTextBox.Text); // Generate Secret Key from the password and salt. System.Security.Cryptography.Rfc2898DeriveBytes secretKey; secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(PassBytes, SaltBytes, 5); // 32 bytes (256 bits) for the secret key and // 16 bytes (128 bits) for the initialization vector (IV). Key = secretKey.GetBytes(Cipher.KeySize / 8); IV = secretKey.GetBytes(Cipher.IV.Length); Cipher.Key = Key; Cipher.IV = IV; WriteLog("// Update Key and IV."); WriteLog("Key[" + Key.Length.ToString() + "]: " + System.BitConverter.ToString(Key).Replace("-", "")); WriteLog("IV[" + IV.Length.ToString() + "]: " + System.BitConverter.ToString(IV).Replace("-", "")); }
/// <summary> /// 使用Rfc2898DeriveBytes算法分别生成Salt和Pwd的值(新增时使用) /// </summary> /// <param name="pwd">明文的密码</param> /// <param name="salt">密文后的salt</param> /// <param name="pwdhash">密文后的pwd</param> public static void GetPwdhashAndSalt(string pwd, out string salt, out string pwdHash) { //salt = "MJvwQJ/T8gJ5cjen0pMBmTHXugdhuTuZ5DRyZMhs1zg="; System.Security.Cryptography.Rfc2898DeriveBytes db; db = new System.Security.Cryptography.Rfc2898DeriveBytes(pwd, 32, 1000); salt = System.Convert.ToBase64String(db.Salt); pwdHash = System.Convert.ToBase64String(db.GetBytes(32)); //如果需要添加用户,保存salt和散列侯的密码到数据存储设备 //如果需要验证用户,从数据存储设备中读取slat,使用salt来计算出密码的散列值,并且与保存在数据存储设备中的密文密码进行比较 }
private static byte[] Hi1(UsernamePasswordCredential credential, byte[] salt, int iterations) { var passwordDigest = AuthenticationHelper.MongoPasswordDigest(credential.Username, credential.Password); using (var deriveBytes = new Rfc2898DeriveBytes(passwordDigest, salt, iterations, HashAlgorithmName.SHA1)) { // 20 is the length of output of a sha-1 hmac return(deriveBytes.GetBytes(20)); } }
/// <summary> /// パスワードから共有キーと初期化ベクタを生成する /// </summary> /// <param name="password">基になるパスワード</param> /// <param name="keySize">共有キーのサイズ(ビット)</param> /// <param name="key">作成された共有キー</param> /// <param name="blockSize">初期化ベクタのサイズ(ビット)</param> /// <param name="iv">作成された初期化ベクタ</param> private void GenerateKeyFromPassword(string password, int keySize, out byte[] key, int blockSize, out byte[] iv) { //パスワードから共有キーと初期化ベクタを作成する //saltを決める // saltは必ず8バイト以上らしい byte[] salt = System.Text.Encoding.UTF8.GetBytes("abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmn"); //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); }
public static void decryptStream(Stream inStream, Stream outStream, byte[] password, byte[] salt = null, int iterations = DEFAULT_ITERATIONS) { if (salt == null) { salt = DEFAULT_SALT; } System.Security.Cryptography.Rfc2898DeriveBytes deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, iterations); byte[] key = deriveBytes.GetBytes(Crypto.AES_KEY_SIZE / 8); byte[] iv = deriveBytes.GetBytes(Crypto.AES_BLOCK_SIZE / 8); using (System.Security.Cryptography.ICryptoTransform decryptor = Crypto._aes.CreateDecryptor(key, iv)) { using (var cs = new System.Security.Cryptography.CryptoStream(outStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { inStream.CopyTo(cs); cs.FlushFinalBlock(); } } }
//パスワードから共有キーと初期化ベクタを生成する private static void GenerateKeyFromPassword(int keySize, out byte[] key, int blockSize, out byte[] iv) { //パスワードから共有キーと初期化ベクタを作成する //saltを決める byte[] salt = System.Text.Encoding.UTF8.GetBytes("saltは必ず8バイト以上"); //Rfc2898DeriveBytesオブジェクトを作成する string pass = "******"; System.Security.Cryptography.Rfc2898DeriveBytes deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(pass, salt); //反復処理回数を指定する デフォルトで1000回 deriveBytes.IterationCount = 1000; //共有キーと初期化ベクタを生成する key = deriveBytes.GetBytes(keySize / 8); iv = deriveBytes.GetBytes(blockSize / 8); }
public string generateKey(String password, byte[] saltBytes) { int iterations = 100; var rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, saltBytes, iterations); byte[] key = rfc2898.GetBytes(16); String keyB64 = Convert.ToBase64String(key); return(keyB64); }
/// <summary> /// AES算法加密数据(不变密) /// </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); 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); }
public static byte[] decryptByte(byte[] data, int from, int len, byte[] password, byte[] salt = null, int iterations = DEFAULT_ITERATIONS) { if (salt == null) { salt = DEFAULT_SALT; } System.Security.Cryptography.Rfc2898DeriveBytes deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, iterations); byte[] key = deriveBytes.GetBytes(AES_KEY_SIZE_BYTE); byte[] iv = deriveBytes.GetBytes(AES_BLOCK_SIZE_BITE); using (ICryptoTransform decryptor = _aes.CreateDecryptor(key, iv)) { try { return(decryptor.TransformFinalBlock(data, from, len)); } catch (CryptographicException) { return(null); } } }
public static byte[] EncKeyGeneration() { byte[] salt = new byte[] { 0x6e, 0x20, 0x76, 0x49, 0x61, 0x64, 0x65, 0x20, }; int iterations = 1024; var rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKeyMobileApp, salt, iterations); byte[] key = rfc2898.GetBytes(16); String keyB64 = Convert.ToBase64String(key); //System.Console.WriteLine("Key: " + keyB64); return(key); }
/// <inheritdoc /> public byte[] DeriveKeyMaterial(ICryptographicKey key, IKeyDerivationParameters parameters, int desiredKeySize) { // Right now we're assuming that KdfGenericBinary is directly usable as a salt // in RFC2898. When our KeyDerivationParametersFactory class supports // more parameter types than just BuildForPbkdf2, we might need to adjust this code // to handle each type of parameter. var keyMaterial = ((KeyDerivationCryptographicKey)key).Key; byte[] salt = parameters.KdfGenericBinary; var deriveBytes = new Platform.Rfc2898DeriveBytes(keyMaterial, salt, parameters.IterationCount); return(deriveBytes.GetBytes(desiredKeySize)); }