public string EncryptString(string sourceString, string password) { //RijndaelManagedオブジェクトを作成 System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); //パスワードから共有キーと初期化ベクタを作成 byte[] key, iv; GenerateKeyFromPassword( password, rijndael.KeySize, out key, rijndael.BlockSize, out iv); rijndael.Key = key; rijndael.IV = iv; //文字列をバイト型配列に変換する byte[] strBytes = System.Text.Encoding.UTF8.GetBytes(sourceString); //対称暗号化オブジェクトの作成 System.Security.Cryptography.ICryptoTransform encryptor = rijndael.CreateEncryptor(); //バイト型配列を暗号化する byte[] encBytes = encryptor.TransformFinalBlock(strBytes, 0, strBytes.Length); //閉じる encryptor.Dispose(); //バイト型配列を文字列に変換して返す return(System.Convert.ToBase64String(encBytes)); }
public string Descriptografar(string criptografia) { string chave = "--"; // Cria objeto para criptografia AES System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); rijndael.Mode = System.Security.Cryptography.CipherMode.CBC; rijndael.KeySize = 128; byte[] chaveBytes; byte[] criptografiaBytes; byte[] mensagemBytes; string mensagem; // Transforma chave e mensagem em array de byts chaveBytes = Encoding.UTF8.GetBytes(chave); mensagemBytes = Convert.FromBase64String(criptografia); // Realiza criptografia System.Security.Cryptography.ICryptoTransform cryptor = rijndael.CreateDecryptor(chaveBytes, chaveBytes); criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length); cryptor.Dispose(); // Transforma criptografia em string mensagem = Encoding.UTF8.GetString(criptografiaBytes); return(mensagem); }
/// <summary> /// DES加密,向量随机生成 /// </summary> /// <param name="plaintext">明文</param> /// <returns></returns> public static string DesEncrypt(string plaintext) { //随机生成8位向量 string iv = GenerateRandom(); byte[] rgbKey = System.Text.Encoding.ASCII.GetBytes("SolinArt"); byte[] rgbIV = System.Text.Encoding.ASCII.GetBytes(iv); byte[] _data = System.Text.Encoding.UTF8.GetBytes(plaintext); System.Security.Cryptography.DESCryptoServiceProvider _des = new System.Security.Cryptography.DESCryptoServiceProvider(); System.Security.Cryptography.ICryptoTransform _encrypt = _des.CreateEncryptor(rgbKey, rgbIV); byte[] _result = _encrypt.TransformFinalBlock(_data, 0, _data.Length); _encrypt.Dispose(); _des.Clear(); string result = BitConverter.ToString(_result); result = iv + result.Replace("-", ""); //首尾各加16位共计32位的MD5校验码 #region 32位的MD5校验码 //string _md5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(result, "MD5"); string _md5 = Md5(result); result = string.Format("{0}{1}{2}" , _md5.Substring(0, 16) , result , _md5.Substring(16) ); #endregion return(result); }
public string Descriptografar(string criptografia) { // Cria objeto para criptografia System.Security.Cryptography.TripleDES des = System.Security.Cryptography.TripleDES.Create(); des.Mode = System.Security.Cryptography.CipherMode.CBC; des.KeySize = 192; byte[] chaveBytes; byte[] criptografiaBytes; byte[] mensagemBytes; string mensagem; // Transforma chave e mensagem em array de byts chaveBytes = Encoding.UTF8.GetBytes("chavede16digitos"); mensagemBytes = Convert.FromBase64String(criptografia); // Realiza criptografia System.Security.Cryptography.ICryptoTransform cryptor = des.CreateDecryptor(chaveBytes, chaveBytes); criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length); cryptor.Dispose(); // Transforma criptografia em string mensagem = Encoding.UTF8.GetString(criptografiaBytes); return(mensagem); }
/// <summary> /// 暗号化された文字列を復号化する /// </summary> /// <param name="sourceString">暗号化された文字列</param> /// <param name="password">暗号化に使用したパスワード</param> /// <returns>復号化された文字列</returns> public string DecryptString(string sourceString, string password) { //RijndaelManagedオブジェクトを作成 System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); //パスワードから共有キーと初期化ベクタを作成 byte[] key, iv; GenerateKeyFromPassword( password, rijndael.KeySize, out key, rijndael.BlockSize, out iv); rijndael.Key = key; rijndael.IV = iv; //文字列をバイト型配列に戻す byte[] strBytes = System.Convert.FromBase64String(sourceString); //対称暗号化オブジェクトの作成 System.Security.Cryptography.ICryptoTransform decryptor = rijndael.CreateDecryptor(); //バイト型配列を復号化する //復号化に失敗すると例外CryptographicExceptionが発生 byte[] decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length); //閉じる decryptor.Dispose(); //バイト型配列を文字列に戻して返す return(System.Text.Encoding.UTF8.GetString(decBytes)); }
protected virtual void Dispose(bool disposing) { if (disposing) { _cryptoTransform.Dispose(); } }
/// <summary> /// 文字列を暗号化する /// </summary> /// <param name="sourceString">暗号化する文字列</param> /// <returns>暗号化された文字列</returns> public static string EncryptString(string sourceString) { //文字列をバイト型配列に変換する byte[] strBytes = System.Text.Encoding.UTF8.GetBytes(sourceString); //対称暗号化オブジェクトの作成 System.Security.Cryptography.ICryptoTransform encryptor = rijndael.CreateEncryptor(); //バイト型配列を暗号化する byte[] encBytes = encryptor.TransformFinalBlock(strBytes, 0, strBytes.Length); //閉じる encryptor.Dispose(); //バイト型配列を文字列に変換して返す return(System.Convert.ToBase64String(encBytes)); }
/// <summary> /// DES解密 /// </summary> public static string DesDecrypt(string encrypted) { //小于40位时,不是有效的加密串 if (encrypted.Length <= 40) { return(""); } else if (encrypted.Length % 2 != 0) { return(""); //非偶数位不是有效的加密串 } //32位MD5校验码 string _md5 = encrypted.Substring(0, 16); _md5 += encrypted.Substring(encrypted.Length - 16); //移除MD5 encrypted = encrypted.Substring(16); encrypted = encrypted.Substring(0, encrypted.Length - 16); //进行MD5验证是否被修改 //if (_md5 != System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(encrypted, "MD5")) if (_md5 != Md5(encrypted)) { return(""); } //截取,移除前8位向量长度 string iv = encrypted.Substring(0, 8); //移除向量值 encrypted = encrypted.Substring(8); //32位整型转换器 System.ComponentModel.Int32Converter _int32 = new System.ComponentModel.Int32Converter(); //字符串转换成数组 byte[] _datas = new byte[encrypted.Length / 2]; for (int i = 0; i < _datas.Length; i++) { _datas[i] = Convert.ToByte(_int32.ConvertFromInvariantString("0x" + encrypted.Substring(i * 2, 2))); } byte[] rgbKey = System.Text.Encoding.ASCII.GetBytes("SolinArt"); byte[] rgbIV = System.Text.Encoding.ASCII.GetBytes(iv); System.Security.Cryptography.DESCryptoServiceProvider _des = new System.Security.Cryptography.DESCryptoServiceProvider(); System.Security.Cryptography.ICryptoTransform _encrypt = _des.CreateDecryptor(rgbKey, rgbIV); byte[] _result = _encrypt.TransformFinalBlock(_datas, 0, _datas.Length); _encrypt.Dispose(); _des.Clear(); return(System.Text.Encoding.UTF8.GetString(_result)); }
/// <summary> /// 暗号化された文字列を復号化する /// </summary> /// <param name="sourceString">暗号化された文字列</param> /// <returns>復号化された文字列</returns> public static string DecryptString(string sourceString) { //文字列をバイト型配列に戻す byte[] strBytes = System.Convert.FromBase64String(sourceString); //対称暗号化オブジェクトの作成 System.Security.Cryptography.ICryptoTransform decryptor = rijndael.CreateDecryptor(); //バイト型配列を復号化する //復号化に失敗すると例外CryptographicExceptionが発生 byte[] decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length); //閉じる decryptor.Dispose(); //バイト型配列を文字列に戻して返す return(System.Text.Encoding.UTF8.GetString(decBytes)); }
protected override void Dispose(bool disposing) { if (_cryptoStream != null) { _cryptoStream.Dispose(); _cryptoStream = null; } if (_cryptoTransform != null) { _cryptoTransform.Dispose(); _cryptoTransform = null; } base.Dispose(disposing); }
internal static string ToDescrypt(string chave, string criptografia) { System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); rijndael.Mode = System.Security.Cryptography.CipherMode.CBC; rijndael.KeySize = 128; byte[] chaveBytes; byte[] criptografiaBytes; byte[] mensagemBytes; string mensagem; chaveBytes = Encoding.UTF8.GetBytes(chave); mensagemBytes = Convert.FromBase64String(criptografia); System.Security.Cryptography.ICryptoTransform cryptor = rijndael.CreateDecryptor(chaveBytes, chaveBytes); criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length); cryptor.Dispose(); mensagem = Encoding.UTF8.GetString(criptografiaBytes); return(mensagem); }
internal static string ToCrypt(string chave, string mensagem) { System.Security.Cryptography.DES des = System.Security.Cryptography.DES.Create(); des.Mode = System.Security.Cryptography.CipherMode.CBC; des.KeySize = 64; byte[] chaveBytes; byte[] criptografiaBytes; byte[] mensagemBytes; string criptografia; chaveBytes = Encoding.UTF8.GetBytes(chave); mensagemBytes = Encoding.UTF8.GetBytes(mensagem); System.Security.Cryptography.ICryptoTransform cryptor = des.CreateEncryptor(chaveBytes, chaveBytes); criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length); cryptor.Dispose(); criptografia = Convert.ToBase64String(criptografiaBytes); return(criptografia); }
public string Descriptografar(string chave, string criptografia) { System.Security.Cryptography.TripleDES des = System.Security.Cryptography.TripleDES.Create(); des.Mode = System.Security.Cryptography.CipherMode.CBC; des.KeySize = 192; byte[] chaveBytes; byte[] criptografiaBytes; byte[] mensagemBytes; string mensagem; chaveBytes = Encoding.UTF8.GetBytes(chave); mensagemBytes = Convert.FromBase64String(criptografia); System.Security.Cryptography.ICryptoTransform cryptor = des.CreateDecryptor(chaveBytes, chaveBytes); criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length); cryptor.Dispose(); mensagem = Encoding.UTF8.GetString(criptografiaBytes); return(mensagem); }
/// <summary> /// バイト列をRijndael暗号化します。 /// </summary> /// <param name="sourceBytes">Source bytes.</param> /// <param name="password">Password.</param> public static byte[] Encrypt(byte[] sourceBytes, string password) { // RijndaelManagedオブジェクトを作成 System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); // パスワードから共有キーと初期化ベクタを作成 byte[] key, iv; GenerateKeyFromPassword( password, rijndael.KeySize, out key, rijndael.BlockSize, out iv); rijndael.Key = key; rijndael.IV = iv; // 対称暗号化オブジェクトの作成 System.Security.Cryptography.ICryptoTransform encryptor = rijndael.CreateEncryptor(); // バイト型配列を暗号化する byte[] encBytes = encryptor.TransformFinalBlock(sourceBytes, 0, sourceBytes.Length); // 閉じる encryptor.Dispose(); return(encBytes); }
// 暗号化された文字列を返す public string CreateEncryptorString(string baseString) { string output = ""; System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged(); byte[] key; byte[] iv; GenerateKeyFromPassword( GeneratePassward, // password rijndael.KeySize, out key, rijndael.BlockSize, out iv ); rijndael.Key = key; rijndael.IV = iv; //文字列をバイト型配列に変換する byte[] strBytes = System.Text.Encoding.UTF8.GetBytes(baseString); //対称暗号化オブジェクトの作成 System.Security.Cryptography.ICryptoTransform encryptor = rijndael.CreateEncryptor(); //バイト型配列を暗号化する byte[] encBytes = encryptor.TransformFinalBlock(strBytes, 0, strBytes.Length); //閉じる encryptor.Dispose(); //バイト型配列を文字列に変換して返す output = System.Convert.ToBase64String(encBytes); return(output); }
public void DisposeInternal() { mEncoder.Dispose(); }
/// <summary>Deszyfruje przekazany strumień danych.</summary> /// <param name="cipherStream">Zaszyfrowany strumień danych.</param> /// <param name="decryptedStream">Odszyfrowany strumień bajtów.</param> /// <param name="key">Klucz deszyfrujący. Maksymalnie 256 bitów, minimalnie 128 bitów, przeskok o 64 bity.</param> /// <param name="iv">Wektor inicjalizacji. Rozmiar 128 bitów.</param> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.ArgumentException"></exception> /// <exception cref="System.InvalidOperationException"></exception> /// <exception cref="System.Security.Cryptography.CryptographicException"></exception> public static void Decrypt(System.IO.Stream cipherStream, System.IO.Stream decryptedStream, byte[] key, byte[] iv) { if (cipherStream == null) { throw new System.ArgumentNullException("cipherStream"); } if (cipherStream.CanRead == false) { throw new System.ArgumentException("Argument 'cipherStream' is not readable."); } if (decryptedStream == null) { throw new System.ArgumentNullException("decryptedStream"); } if (decryptedStream.CanWrite == false) { throw new System.ArgumentException("Argument 'decryptedStream' is not writable."); } if (key == null) { throw new System.ArgumentNullException("key"); } if (key.Length != 16 && key.Length != 22 && key.Length != 32) { throw new System.ArgumentException("Argument 'key' does not mach the block size for this algorithm."); } if (iv == null) { throw new System.ArgumentNullException("iv"); } if (iv.Length != 16) { throw new System.ArgumentException("Argument 'iv' does not mach the block size for this algorithm."); } cipherStream.Position = 0; decryptedStream.Position = 0; System.Security.Cryptography.ICryptoTransform decryptor = null; try { using (System.Security.Cryptography.RijndaelManaged algoritmCrypt = new System.Security.Cryptography.RijndaelManaged()) { decryptor = algoritmCrypt.CreateDecryptor(key, iv); using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream( cipherStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { cs.CopyTo(decryptedStream); decryptedStream.Position = 0; } } } finally { if (decryptor != null) { decryptor.Dispose(); } } }
/// <summary> /// /// </summary> /// <param name="secretKey"></param> /// <param name="cypheredData"></param> /// <returns></returns> public static ProtectedMemory DecryptData(ProtectedString secretKey, ProtectedMemory cypheredData) { ProtectedMemory returnValue = null; System.Byte[] encryptedData = null; System.Byte[] ivData = null; #region Check protection of secret key if (!secretKey.IsProtected) { throw new UnsecureException(); } #endregion #region Check protection of cyphered data if (!cypheredData.IsProtected) { throw new UnsecureException(); } #endregion #region Split cyphered data // Unprotect cyphered memory cypheredData.Unprotect(); // extract iv data (IV length is static => 16) ivData = new System.Byte[16]; System.Array.Copy(cypheredData.GetBytes(), 0, ivData, 0, 16); // extract encrypted data encryptedData = new System.Byte[cypheredData.SizeInByte - 16]; System.Array.Copy(cypheredData.GetBytes(), 16, encryptedData, 0, (cypheredData.SizeInByte - 16)); // Reprotect cyphered memory cypheredData.Protect(); #endregion #region Prepare encryption provider // Unprotect memory containing secret key secretKey.Unprotect(); // Create encryption provider System.Security.Cryptography.SymmetricAlgorithm encryptionProvider = System.Security.Cryptography.Aes.Create(); encryptionProvider.Mode = System.Security.Cryptography.CipherMode.CBC; encryptionProvider.Key = secretKey.GetBytes(); encryptionProvider.IV = ivData; // Reprotect memory containing secret key secretKey.Protect(); #endregion // Create decryptor System.Security.Cryptography.ICryptoTransform decryptor = encryptionProvider.CreateDecryptor(encryptionProvider.Key, encryptionProvider.IV); // Create handle to memory of encrypted data using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(encryptedData)) { // Create handle for data decryption; data streamed by this stream will be automatically decrypted using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { // Create handle to read data of a strea,; data readed by this stream will be automatically decrypted using (System.IO.StreamReader streamReader = new System.IO.StreamReader(cryptoStream)) { #region Save plain data in protected memory // Save plain data in temp buffer System.String plainData = streamReader.ReadToEnd(); // Create protected memory for plain data returnValue = new ProtectedMemory(plainData.Length); // Unprotect memory for plain data returnValue.Unprotect(); // Copy plain data in encrypted memory for (System.Int32 i = 0; i < plainData.Length; i++) { returnValue.SetByte(i, (System.Byte)plainData[i]); } // Reprotect memory with plain data returnValue.Protect(); // Save erase temp buffer plainData = null; System.GC.Collect(); #endregion } } } // Dispose decryptor decryptor.Dispose(); // Dispose encryption provider encryptionProvider.Dispose(); return(returnValue); }
/// <summary> /// /// </summary> /// <param name="secretKey"></param> /// <param name="plainData"></param> /// <returns></returns> public static ProtectedMemory EncryptData(ProtectedString secretKey, ProtectedMemory plainData) { ProtectedMemory returnValue = null; System.Byte[] encryptedData = null; #region Check protection of secret key if (!secretKey.IsProtected) { throw new UnsecureException(); } #endregion #region Check protection of plain data if (!plainData.IsProtected) { throw new UnsecureException(); } #endregion #region Prepare encryption provider // Unprotect memory containing secret key secretKey.Unprotect(); // Create encryption provider System.Security.Cryptography.SymmetricAlgorithm encryptionProvider = System.Security.Cryptography.Aes.Create(); encryptionProvider.Mode = System.Security.Cryptography.CipherMode.CBC; encryptionProvider.Key = secretKey.GetBytes(); encryptionProvider.GenerateIV(); // Reprotect memory containing secret key secretKey.Protect(); #endregion // Create encryptor System.Security.Cryptography.ICryptoTransform encryptor = encryptionProvider.CreateEncryptor(encryptionProvider.Key, encryptionProvider.IV); // Create handle to stream data into memory using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { // Write IV to temp memory (IV length is static => 16 ) memoryStream.Write(encryptionProvider.IV, 0, 16); // Create handle for data encryption; data streamed to this stream will be automatically encrypted and streamed to memory using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { // Create handle to write data to a stream; data written to this stream will be automatically encrypted and streamed to memory using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(cryptoStream)) { // Unprotect plain data plainData.Unprotect(); #region Write and encrypt plain data to temp memory foreach (System.Byte b in plainData.GetBytes()) { streamWriter.Write((System.Char)b); } #endregion // Reprotect plain data plainData.Protect(); } } // Save content of temp memory in temp buffer encryptedData = memoryStream.ToArray(); } // Dispose encryptor encryptor.Dispose(); // Dispose encryption provider encryptionProvider.Dispose(); #region Save cyphered data in protected memory // Create protected memory for cyphered data returnValue = new ProtectedMemory(encryptedData.Length); // Unprotect memory for cyphered data returnValue.Unprotect(); // Copy cyphered data in encrypted memory for (System.Int32 i = 0; i < encryptedData.Length; i++) { returnValue.SetByte(i, encryptedData[i]); } // Reprotect memory with cyphered data returnValue.Protect(); #endregion return(returnValue); }