private static byte[] Decrypt(byte[] cipherKey, byte[] ciphertext) { var cipher = new System.Security.Cryptography.AesManaged(); cipher.Key = cipherKey; cipher.Mode = System.Security.Cryptography.CipherMode.CBC; cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126; var ivSize = cipher.IV.Length; var iv = new byte[ivSize]; Array.Copy(ciphertext, iv, ivSize); cipher.IV = iv; var data = new byte[ciphertext.Length - ivSize]; Array.Copy(ciphertext, ivSize, data, 0, data.Length); using (var ms = new System.IO.MemoryStream()) { using (var cs = new System.Security.Cryptography.CryptoStream( ms, cipher.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { cs.Write(data, 0, data.Length); } var plaintext = ms.ToArray(); return plaintext; } }
/// <summary> /// Saves the dataset encrypted in specified file /// </summary> /// <param name="dataset">Dataset to save</param> /// <param name="username">Username for encryption</param> /// <param name="password">Password for encryption</param> /// <param name="fileName">File name where to save</param> /// <param name="compress">Should the file be compressed</param> internal static void EncryptDataSet(System.Data.DataSet dataset, string username, string password, string fileName, bool compress) { // Check the parameters if (dataset == null || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fileName)) { throw new System.ArgumentNullException("All arguments must be supplied."); } // Save the dataset as encrypted using (System.Security.Cryptography.Aes aes = Cryptography.InitAes(username, password)) { using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None)) { using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(fileStream, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { if (compress) { // when compression is requested, use GZip using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(cryptoStream, System.IO.Compression.CompressionMode.Compress)) { dataset.WriteXml(zipStream, System.Data.XmlWriteMode.WriteSchema); zipStream.Flush(); } } else { dataset.WriteXml(cryptoStream, System.Data.XmlWriteMode.WriteSchema); cryptoStream.FlushFinalBlock(); } } } } }
/// <summary> /// 加密文件 /// </summary> public void EncryptFile(string Value, string OuputFileName) { try { // Must be 64 bits, 8 bytes. // Distribute this key to the user who will decrypt this file. //Get the Key for the file to Encrypt. string sKey = GenerateKey(); byte[] b = ASCIIEncoding.ASCII.GetBytes(Value); System.IO.FileStream fsEncrypted = new System.IO.FileStream(OuputFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.Security.Cryptography.DESCryptoServiceProvider DES = new System.Security.Cryptography.DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey); System.Security.Cryptography.ICryptoTransform desencrypt = DES.CreateEncryptor(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(fsEncrypted, desencrypt, System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(b, 0, b.Length); cs.Close(); fsEncrypted.Close(); } catch (Exception ex) { throw ex; } }
private static string Decrypt(string cipherText, string passPhrase) { byte[] initVectorBytes = System.Text.Encoding.ASCII.GetBytes("tu89geji340t89u2"); const int keysize = 256; byte[] cipherTextBytes = Convert.FromBase64String(cipherText); using (System.Security.Cryptography.PasswordDeriveBytes password = new System.Security.Cryptography.PasswordDeriveBytes(passPhrase, null)) { byte[] keyBytes = password.GetBytes(keysize / 8); using (System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged()) { symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; using (System.Security.Cryptography.ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)) { using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes)) { using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); return(System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)); } } } } } }
//static Logger logger = SimpleLogger.setLogger("Common"); #region �Í����W /// <summary> /// �������Í������� /// </summary> /// <param name="str">�Í������镶����</param> /// <param name="key">�p�X���[�h</param> /// <returns>�Í������ꂽ������</returns> public static string EncryptString(string str, string key) { //�������o�C�g�^�z��ɂ��� byte[] bytesIn = System.Text.Encoding.UTF8.GetBytes(str); //DESCryptoServiceProvider�I�u�W�F�N�g�̍쐬 System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider(); //���L�L�[�Ə������x�N�^����� //�p�X���[�h��o�C�g�z��ɂ��� byte[] bytesKey = System.Text.Encoding.UTF8.GetBytes(key); //���L�L�[�Ə������x�N�^��ݒ� des.Key = ResizeBytesArray(bytesKey, des.Key.Length); des.IV = ResizeBytesArray(bytesKey, des.IV.Length); //�Í������ꂽ�f�[�^������o�����߂�MemoryStream MemoryStream msOut = new System.IO.MemoryStream(); //DES�Í����I�u�W�F�N�g�̍쐬 System.Security.Cryptography.ICryptoTransform desdecrypt = des.CreateEncryptor(); //�������ނ��߂�CryptoStream�̍쐬 System.Security.Cryptography.CryptoStream cryptStreem = new System.Security.Cryptography.CryptoStream(msOut, desdecrypt, System.Security.Cryptography.CryptoStreamMode.Write); //�������� cryptStreem.Write(bytesIn, 0, bytesIn.Length); cryptStreem.FlushFinalBlock(); //�Í������ꂽ�f�[�^��擾 byte[] bytesOut = msOut.ToArray(); //���� cryptStreem.Close(); msOut.Close(); //Base64�ŕ�����ɕύX���Č��ʂ�Ԃ� return System.Convert.ToBase64String(bytesOut).Replace("=", ""); }
/// /// DES解密 /// /// 要解密字符串 /// 返回解密后字符串 public static String Decrypt_DES(String str) { if (str.Trim() == "") { return(""); } try { System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider(); Int32 x; Byte[] inputByteArray = new Byte[str.Length / 2]; for (x = 0; x < str.Length / 2; x++) { inputByteArray[x] = (Byte)(Convert.ToInt32(str.Substring(x * 2, 2), 16)); } des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey); des.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.StringBuilder ret = new System.Text.StringBuilder(); return(System.Text.Encoding.Default.GetString(ms.ToArray())); } catch (System.Exception ex) { return(""); } }
public static string Encrypt(string plainText, string passPhrase) { byte[] initVectorBytes = Encoding.ASCII.GetBytes("tu89geji340t89u2"); const int keysize = 256; byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); using (System.Security.Cryptography.PasswordDeriveBytes password = new System.Security.Cryptography.PasswordDeriveBytes(passPhrase, null)) { byte[] keyBytes = password.GetBytes(keysize / 8); using (System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged()) { symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; using (System.Security.Cryptography.ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)) { using (MemoryStream memoryStream = new MemoryStream()) { using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = memoryStream.ToArray(); return(Convert.ToBase64String(cipherTextBytes)); } } } } } }
/// <summary> /// 暗号化された文字列を復号化する /// </summary> public static string DecryptString(string str, string password) { var aes = new System.Security.Cryptography.AesCryptoServiceProvider(); var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password); aes.Key = ResizeBytesArray(passwordBytes, aes.Key.Length); aes.IV = ResizeBytesArray(passwordBytes, aes.IV.Length); var data = System.Convert.FromBase64String(str); var stream = new System.IO.MemoryStream(data); var decryptor = aes.CreateDecryptor(); var cryptStreem = new System.Security.Cryptography.CryptoStream( stream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read ); var reader = new System.IO.StreamReader( cryptStreem, System.Text.Encoding.UTF8 ); try { var result = reader.ReadToEnd(); return(result); } finally { reader.Close(); cryptStreem.Close(); stream.Close(); } }
public static byte[] GetEmbeddedBytes(String file) { using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(file)) { if (stream != null) { var assemblyData = new Byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); var key = System.Text.Encoding.ASCII.GetBytes("t7n6cVWf9Tbns0eI"); var iv = System.Text.Encoding.ASCII.GetBytes("9qh17ZUf"); var provider = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); var transform = provider.CreateDecryptor(key, iv); byte[] bytes; using (var cstream = new MemoryStream()) { using (var cryptoStream = new System.Security.Cryptography.CryptoStream(cstream, transform, System.Security.Cryptography.CryptoStreamMode.Write)) { cryptoStream.Write(assemblyData, 0, assemblyData.Length); cryptoStream.FlushFinalBlock(); bytes = cstream.ToArray(); using (var compressedStream = new MemoryStream(bytes)) using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress)) using (var resultStream = new MemoryStream()) { zipStream.CopyTo(resultStream); return(resultStream.ToArray()); } } } } } return(null); }
public static byte[] EncryptData(byte[] publickey, byte[] data) { using (System.Security.Cryptography.Aes myAes = System.Security.Cryptography.Aes.Create()) { System.Security.Cryptography.ICryptoTransform encryptor = myAes.CreateEncryptor(myAes.Key, myAes.IV); using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { System.IO.MemoryStream headerms = new System.IO.MemoryStream(); System.IO.BinaryWriter headerbw = new System.IO.BinaryWriter(headerms); using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(csEncrypt)) { System.Security.Cryptography.RSACryptoServiceProvider public_key = new System.Security.Cryptography.RSACryptoServiceProvider(1024); public_key.ImportCspBlob(publickey); byte[] encryptedkey = public_key.Encrypt(Combine(myAes.Key, myAes.IV), false); headerbw.Write(encryptedkey.Length); headerbw.Write(myAes.Key.Length); headerbw.Write(myAes.IV.Length); headerbw.Write(encryptedkey); headerbw.Flush(); bw.Write(data); } byte[] result = Combine(headerms.ToArray(), msEncrypt.ToArray()); headerbw.Close(); return(result); } } } }
// ======================================== // static field // ======================================== public static string EncryptString(string str, string password) { var aes = new System.Security.Cryptography.AesCryptoServiceProvider(); var data = System.Text.Encoding.UTF8.GetBytes(str); var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password); aes.Key = ResizeBytesArray(passwordBytes, aes.Key.Length); aes.IV = ResizeBytesArray(passwordBytes, aes.IV.Length); var stream = new System.IO.MemoryStream(); var encryptor = aes.CreateEncryptor(); var cryptStream = new System.Security.Cryptography.CryptoStream( stream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write ); try { cryptStream.Write(data, 0, data.Length); cryptStream.FlushFinalBlock(); var encrypted = stream.ToArray(); return(System.Convert.ToBase64String(encrypted)); } finally { cryptStream.Close(); stream.Close(); } }
/// <summary> /// رمزگشایی داده ها /// </summary> /// <param name="data">داده ها</param> /// <param name="Key">Key</param> /// <param name="IV">IV</param> public byte[] Decrypt(byte[] data, byte[] Key, byte[] IV) { System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(data); System.Security.Cryptography.CryptoStream _CryptoStream; if (Key == null && IV == null) { _CryptoStream = new System.Security.Cryptography.CryptoStream(_MemoryStream, DES.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read); } else { _CryptoStream = new System.Security.Cryptography.CryptoStream(_MemoryStream, DES.CreateDecryptor(Key, IV), System.Security.Cryptography.CryptoStreamMode.Read); } List <byte> DecryptedDataList = new List <byte>(); byte[] TempData = new byte[2048]; int readCount = 0; do { readCount = _CryptoStream.Read(TempData, 0, 2048); for (int i = 0; i < readCount; i++) { DecryptedDataList.Add(TempData[i]); } }while (readCount > 0); _CryptoStream.Close(); _MemoryStream.Close(); _CryptoStream.Dispose(); _MemoryStream.Dispose(); return(DecryptedDataList.ToArray()); }
public static string DesDecrypt(string inputString, string decryptKey) { #region byte[] byKey = null; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byte[] inputByteArray = new Byte[inputString.Length]; try { byKey = System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8)); System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(inputString); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(byKey, IV), System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = new System.Text.UTF8Encoding(); inputString = encoding.GetString(ms.ToArray()); } catch { throw; } return(inputString); #endregion }
public static string DecryptPAN(string encryptedPAN) { // Log log = new Log(LogPath); System.Security.Cryptography.SymmetricAlgorithm alg = System.Security.Cryptography.TripleDES.Create(); alg.KeySize = 128; alg.Key = Hex2Bin(PEncKey); alg.IV = Hex2Bin(PEncIV); alg.Padding = System.Security.Cryptography.PaddingMode.None; alg.Mode = System.Security.Cryptography.CipherMode.CBC; byte[] buf = new byte[16]; Hex2Bin(encryptedPAN, buf); try { MemoryStream outs = new MemoryStream(); System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(outs, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write); encStream.Write(buf, 0, 16); encStream.FlushFinalBlock(); Buffer.BlockCopy(outs.GetBuffer(), 0, buf, 0, 16); encStream.Close(); return(Bin2Hex(buf).Trim('A')); } catch { } return(null); }
public static byte[] DES_Enc(string str, string key, string vit) { //判断向量是否为空,进行默认赋值; if (string.IsNullOrEmpty(key)) { key = "KCCT"; } //判断向量是否为空,进行默认赋值; if (string.IsNullOrEmpty(vit)) { vit = "MNSN"; } try { //实例化加解密类的对象; using (var descsp = new System.Security.Cryptography.DESCryptoServiceProvider()) { //定义字节数组,用来存储要加密的字符串; var data = System.Text.Encoding.UTF8.GetBytes(str); //实例化内存流对象; using (var mStream = new System.IO.MemoryStream()) { //使用内存流实例化加密流对象; using (var cStream = new System.Security.Cryptography.CryptoStream(mStream, descsp.CreateEncryptor(System.Text.Encoding.Unicode.GetBytes(key), System.Text.Encoding.Unicode.GetBytes(vit)), System.Security.Cryptography.CryptoStreamMode.Write)) { //向加密流中写入数据; cStream.Write(data, 0, data.Length); //释放加密流; cStream.FlushFinalBlock(); //返回加密后的字符串; return mStream.ToArray(); } } } } catch { return null; } }
public void init() { // signature=java.security.Signature.getInstance("SHA1withRSA"); // keyFactory=KeyFactory.getInstance("RSA"); sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); cs = new System.Security.Cryptography.CryptoStream(System.IO.Stream.Null, sha1, System.Security.Cryptography.CryptoStreamMode.Write); }
public static string Encrypt(string[] keyArray) { string key = ""; foreach (string s in keyArray) { key = key + s + ";"; } byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] PlainTextBytes = Encoding.UTF8.GetBytes(key); System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged(); SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; byte[] CipherTextBytes = null; using (System.Security.Cryptography.ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)) { using (System.IO.MemoryStream MemStream = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length); CryptoStream.FlushFinalBlock(); CipherTextBytes = MemStream.ToArray(); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return(Convert.ToBase64String(CipherTextBytes)); }
/// <summary> /// Criptografa um array de bytes em outro array de bytes. /// </summary> /// <returns>Array de bytes criptografado.</returns> /// <param name="p_plaintextbytes">Array de bytes.</param> public byte[] EncryptToBytes(byte[] p_plaintextbytes) { byte[] v_ciphertextbytes; byte[] v_plaintextbyteswithsalt; System.IO.MemoryStream v_memory; System.Security.Cryptography.CryptoStream v_crypto; this.Initialize(); v_plaintextbyteswithsalt = this.AddSalt(p_plaintextbytes); v_memory = new System.IO.MemoryStream(); lock (this) { v_crypto = new System.Security.Cryptography.CryptoStream(v_memory, this.v_encryptor, System.Security.Cryptography.CryptoStreamMode.Write); v_crypto.Write(v_plaintextbyteswithsalt, 0, v_plaintextbyteswithsalt.Length); v_crypto.FlushFinalBlock(); v_ciphertextbytes = v_memory.ToArray(); v_memory.Close(); v_crypto.Close(); return(v_ciphertextbytes); } }
public static string aesDecryptBase64(string SourceStr, ulong Key) { string decrypt = ""; try { var aes = new System.Security.Cryptography.AesCryptoServiceProvider(); var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider(); byte[] key = sha256.ComputeHash(BitConverter.GetBytes(Key)); byte[] iv = md5.ComputeHash(BitConverter.GetBytes(Key)); aes.Key = key; aes.IV = iv; byte[] dataByteArray = Convert.FromBase64String(SourceStr); using (var ms = new System.IO.MemoryStream()) { using (var cs = new System.Security.Cryptography.CryptoStream(ms, aes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { cs.Write(dataByteArray, 0, dataByteArray.Length); cs.FlushFinalBlock(); decrypt = Encoding.UTF8.GetString(ms.ToArray()); } } } catch (Exception e) { } return(decrypt); }
/// <summary> /// 微信小程序 encryptedData 解密 /// </summary> /// <param name="encryptedDataStr"></param> /// <param name="key">session_key</param> /// <param name="iv">iv</param> /// <returns></returns> public string AES_Decrypt(string encryptedDataStr, string key, string iv) { var rijalg = System.Security.Cryptography.Aes.Create(); rijalg.KeySize = 128; rijalg.Padding = System.Security.Cryptography.PaddingMode.PKCS7; rijalg.Mode = System.Security.Cryptography.CipherMode.CBC; rijalg.Key = System.Convert.FromBase64String(key); rijalg.IV = System.Convert.FromBase64String(iv); var decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV); var encryptedData = System.Convert.FromBase64String(encryptedDataStr); using (var msDecrypt = new System.IO.MemoryStream(encryptedData)) { using (var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { using (var srDecrypt = new System.IO.StreamReader(csDecrypt)) { return(srDecrypt.ReadToEnd()); } } } }
public static string decryptRJ256(string target, string key, string iv) { var rijndael = new System.Security.Cryptography.RijndaelManaged() { Padding = System.Security.Cryptography.PaddingMode.Zeros, Mode = System.Security.Cryptography.CipherMode.CBC, KeySize = 256, BlockSize = 256 }; var keyBytes = Encoding.ASCII.GetBytes(key); var ivBytes = Encoding.ASCII.GetBytes(iv); var decryptor = rijndael.CreateDecryptor(keyBytes, ivBytes); var toDecrypt = Convert.FromBase64String(target); var fromEncrypt = new byte[toDecrypt.Length]; var msDecrypt = new System.IO.MemoryStream(toDecrypt); var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read); csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); string data = Encoding.ASCII.GetString(fromEncrypt); data = data.Replace("\0", ""); return data; }
static public byte[] Decode(byte[] Data, System.Security.Cryptography.ICryptoTransform Decoder) { byte[] Outer = new byte[] { }; int rdlen = 0; if (Data.Length > 0) { using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()) { byte[] bin = new byte[128]; int len; System.IO.MemoryStream InputStr = new System.IO.MemoryStream(); InputStr.Write(Data, 0, Data.Length); InputStr.Position = 0; System.Security.Cryptography.CryptoStream CryptStream = new System.Security.Cryptography.CryptoStream(memStream, Decoder, System.Security.Cryptography.CryptoStreamMode.Write); while (rdlen < Data.Length) { len = InputStr.Read(bin, 0, 128); CryptStream.Write(bin, 0, len); rdlen = rdlen + len; } CryptStream.FlushFinalBlock(); Outer = memStream.ToArray(); CryptStream.Close(); } } return(Outer); }
public static string encryptRJ256(string target, string key, string iv) { var rijndael = new System.Security.Cryptography.RijndaelManaged() { Padding = System.Security.Cryptography.PaddingMode.Zeros, Mode = System.Security.Cryptography.CipherMode.CBC, KeySize = 256, BlockSize = 256 }; var bytesKey = Encoding.ASCII.GetBytes(key); var bytesIv = Encoding.ASCII.GetBytes(iv); var encryptor = rijndael.CreateEncryptor(bytesKey, bytesIv); var msEncrypt = new System.IO.MemoryStream(); var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write); var toEncrypt = Encoding.ASCII.GetBytes(target); csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); var encrypted = msEncrypt.ToArray(); return Convert.ToBase64String(encrypted); }
private static string Encrypt(string hashKey, string strQueryStringParameter) { System.Security.Cryptography.MD5CryptoServiceProvider hash_func = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] key = hash_func.ComputeHash(Encoding.ASCII.GetBytes(hashKey)); byte[] IV = new byte[hashKey.Length]; System.Security.Cryptography.SHA1CryptoServiceProvider sha_func = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] temp = sha_func.ComputeHash(Encoding.ASCII.GetBytes(hashKey)); for (int i = 0; i < hashKey.Length; i++) { IV[i] = temp[hashKey.Length]; } byte[] toenc = System.Text.Encoding.UTF8.GetBytes(strQueryStringParameter); System.Security.Cryptography.TripleDESCryptoServiceProvider des = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); des.KeySize = 128; MemoryStream ms = new MemoryStream(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream( ms, des.CreateEncryptor(key, IV), System.Security.Cryptography.CryptoStreamMode.Write ); cs.Write(toenc, 0, toenc.Length); cs.FlushFinalBlock(); return(Convert.ToBase64String(ms.ToArray())); }
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. }
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 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); }
public static byte[] DecryptData(System.Security.Cryptography.RSACryptoServiceProvider full_rsa, byte[] data) { System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.MemoryStream(data)); int encryptedkeylength = br.ReadInt32(); int aeskeylength = br.ReadInt32(); int aesivlength = br.ReadInt32(); byte[] encryptedaeskey = br.ReadBytes(encryptedkeylength); byte[] encrypteddata = br.ReadBytes((int)(data.Length - br.BaseStream.Position)); br.Close(); byte[] decryptedkey = full_rsa.Decrypt(encryptedaeskey, false); br = new System.IO.BinaryReader(new System.IO.MemoryStream(decryptedkey)); using (System.Security.Cryptography.Aes myAes = System.Security.Cryptography.Aes.Create()) { byte[] aeskey = br.ReadBytes(aeskeylength); byte[] aesiv = br.ReadBytes(aesivlength); System.Security.Cryptography.ICryptoTransform decryptor = myAes.CreateDecryptor(aeskey, aesiv); using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(csEncrypt)) { bw.Write(encrypteddata); } return(msDecrypt.ToArray()); } } } }
public static string Decrypt(string CipherText, string Password, string Salt = "Kosher", string HashAlgorithm = "SHA1", int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(CipherText)) { return(""); } byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(CipherText); System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged(); SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = 0; using (System.Security.Cryptography.ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)) { using (System.IO.MemoryStream MemStream = new System.IO.MemoryStream(CipherTextBytes)) { using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return(Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount)); }
public string Descifrar(string Cadena) { try { if (string.IsNullOrEmpty(Cadena)) { return(Cadena); } byte[] PlainText; PlainText = Convert.FromBase64String(Cadena); MemoryStream memdata = new MemoryStream(); System.Security.Cryptography.DESCryptoServiceProvider DES = new System.Security.Cryptography.DESCryptoServiceProvider(); System.Security.Cryptography.CryptoStream cryptostream = new System.Security.Cryptography.CryptoStream(memdata, DES.CreateDecryptor(Encoding.ASCII.GetBytes(Default8Key), Encoding.ASCII.GetBytes(Default8VI)), System.Security.Cryptography.CryptoStreamMode.Write); cryptostream.Write(PlainText, 0, PlainText.Length); cryptostream.FlushFinalBlock(); cryptostream.Close(); return(Encoding.ASCII.GetString(memdata.ToArray())); } catch (Exception ex) { return(null); } }
/// <summary> /// Reads and decrypts the dataset from the given file /// </summary> /// <param name="dataset">Dataset to read</param> /// <param name="username">Username for decryption</param> /// <param name="password">Password for decryption</param> /// <param name="fileName">File name to read</param> /// <param name="compressed">Is the file compressed</param> /// <returns>XmlReadMode used for reading</returns> internal static System.Data.XmlReadMode DecryptDataSet(System.Data.DataSet dataset, string username, string password, string fileName, bool compressed) { System.Data.XmlReadMode xmlReadMode; // Check the parameters if (dataset == null || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fileName)) { throw new System.ArgumentNullException("All arguments must be supplied."); } // Read the dataset and encrypt it using (System.Security.Cryptography.Aes aes = Cryptography.InitAes(username, password)) { using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open)) { using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(fileStream, aes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read)) { if (compressed) { // when decompression is requested, use GZip using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(cryptoStream, System.IO.Compression.CompressionMode.Decompress)) { xmlReadMode = dataset.ReadXml(zipStream, System.Data.XmlReadMode.ReadSchema); } } else { xmlReadMode = dataset.ReadXml(cryptoStream, System.Data.XmlReadMode.ReadSchema); } } } } return(xmlReadMode); }
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 string EncryptString(string value, string keyString) { try { byte[] resultBA = new byte[value.Length], valueBA = new byte[value.Length]; byte[] iv = new byte[] { 0x14, 0xD7, 0x5B, 0xA2, 0x47, 0x83, 0x0F, 0xC4 }; System.Text.ASCIIEncoding ascEncoding = new System.Text.ASCIIEncoding(); byte[] key = new byte[24]; ascEncoding.GetBytes(keyString, 0, keyString.Length < 24?keyString.Length:24, key, 0); MemoryStream memStream = new MemoryStream(); byte[] tempBA = new byte[value.Length]; ascEncoding.GetBytes(value, 0, value.Length, tempBA, 0); System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream(memStream, System.Security.Cryptography.TripleDESCryptoServiceProvider.Create().CreateEncryptor(key, iv), System.Security.Cryptography.CryptoStreamMode.Write); cStream.Write(tempBA, 0, tempBA.Length); cStream.FlushFinalBlock(); resultBA = memStream.ToArray(); cStream.Close(); return(InternalMethods.BytesToHexString(resultBA)); } catch (Exception exc) { LogEvent(exc.Source, "EncryptString()", exc.ToString(), 4); return(""); } }
/// <summary> /// Encrypts a source stream and returns a Base64 result. /// </summary> /// <param name="Source">The source steam.</param> /// <param name="Key">A key to use for the encryption.</param> /// <returns>A Base64 string of the encrypted information.</returns> public string Encrypt(System.IO.Stream Source, string Key) { // read the stream into a byte array Source.Position = 0; byte[] bytIn = new byte[Source.Length]; Source.Read(bytIn, 0, (int)Source.Length); // create a MemoryStream so that the process can be done without I/O files System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] bytKey = GetLegalKey(Key); // set the private key _cryptoservice.Key = bytKey; _cryptoservice.IV = bytKey; // create an Encryptor from the Provider Service instance System.Security.Cryptography.ICryptoTransform encrypto = _cryptoservice.CreateEncryptor(); // create Crypto Stream that transforms a stream using the encryption System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encrypto, System.Security.Cryptography.CryptoStreamMode.Write); // write out encrypted content into MemoryStream cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); byte[] bytOut = ms.GetBuffer(); // convert into Base64 so that the result can be used in xml return(System.Convert.ToBase64String(bytOut, 0, (int)ms.Length)); }
private static readonly String strDesKey = "gaoguanj";//加密所需8位密匙 /// /// DES加密 /// /// 要加密字符串 /// 返回加密后字符串 public static String Encrypt_DES(String str) { if (str.Trim() == "") { return(""); } try { System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider(); Byte[] inputByteArray = System.Text.Encoding.Default.GetBytes(str); des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey); des.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (Byte b in ms.ToArray()) { sb.AppendFormat("{0:X2}", b); } return(sb.ToString()); } catch (System.Exception ex) { return(""); } }
/// <summary> /// AES 解密 Byte -> String /// </summary> /// <param name="cipherText"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static string ByteAesDecToString(byte[] cipherText, string key, string iv) { #region AES 解密 Byte -> String // 检查参数 if (cipherText.IsEmptyBytes()) return null; if (key.IsNullOrEmptyOrSpace()) return null; if (iv.IsNullOrEmptyOrSpace()) return null; // 合成密钥 var deckey = StringMd5ShaToString(false, string.Format("<{0}/>{1}</{2}>[{3}]", iv, key, iv, EnDecryptConst), 16, false, 1, System.Text.Encoding.UTF8); var deciv = StringMd5ShaToString(false, string.Format("[{0}/]{1}[/{2}]<{3}>", iv, key, iv, EnDecryptConst), 16, false, 1, System.Text.Encoding.UTF8); // 转换参数 var keybyte = System.Text.Encoding.UTF8.GetBytes(deckey); if (keybyte.Length <= 0) return null; var ivbyte = System.Text.Encoding.UTF8.GetBytes(deciv); if (ivbyte.Length <= 0) return null; // 存储解密结果 string plaintext; // 创建一个解密对象 using (var aesAlg = new System.Security.Cryptography.AesManaged()) { aesAlg.Key = keybyte; aesAlg.IV = ivbyte; // 创建一个解密对象 var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // 创建一个解密内存流 try { using (var msDecrypt = new System.IO.MemoryStream(cipherText)) { using ( var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography .CryptoStreamMode.Read)) { using (var srDecrypt = new System.IO.StreamReader(csDecrypt)) { // 得到String plaintext = srDecrypt.ReadToEnd(); } } } } catch { return null; } } // 返回String return plaintext; #endregion }
public override void init(){ try { //md=MessageDigest.getInstance("SHA-1"); md=new System.Security.Cryptography.SHA1CryptoServiceProvider(); cs = new System.Security.Cryptography.CryptoStream( System.IO.Stream.Null, md, System.Security.Cryptography.CryptoStreamMode.Write); } catch(Exception e){ Console.WriteLine(e); } }
/// <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; }
public void init(byte[] key) { if (key.Length > 20) { byte[] tmp = new byte[20]; Array.Copy(key, 0, tmp, 0, 20); key = tmp; } // SecretKeySpec skey=new SecretKeySpec(key, "HmacSHA1"); // mac=Mac.getInstance("HmacSHA1"); // mac.init(skey); mentalis_mac = new System.Security.Cryptography.HMACMD5(key); cs = new System.Security.Cryptography.CryptoStream(System.IO.Stream.Null, mentalis_mac, System.Security.Cryptography.CryptoStreamMode.Write); }
/// <summary> /// 从加密的密钥交换数据中提取机密信息<br/> /// </summary> /// <param name="str">被加密的字符串</param> /// <param name="key">密钥</param> /// <returns>还原的字符串</returns> public static string DecryptString(string str, string key) { try { //义访问数据加密标准 (DES) 算法的加密服务提供程序 (CSP) 版本的包装对象. System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider(); //对密钥进行编码. byte[] bytesKey = System.Text.Encoding.UTF8.GetBytes(key); //初始化机密适配器.. des.Key = ResizeBytesArray(bytesKey, des.Key.Length); des.IV = ResizeBytesArray(bytesKey, des.IV.Length); //返回由以 64 为基的二进制数组 byte[] bytesIn = System.Convert.FromBase64String(str); System.IO.MemoryStream msIn = new System.IO.MemoryStream(bytesIn); //定义基本的加密转换运算. System.Security.Cryptography.ICryptoTransform desdecrypt = des.CreateDecryptor(); //定义将数据流链接到加密转换的流。. System.Security.Cryptography.CryptoStream cryptStreem = new System.Security.Cryptography.CryptoStream(msIn, desdecrypt, System.Security.Cryptography.CryptoStreamMode.Read); //以UTF8编码从字节流中读取字符. System.IO.StreamReader srOut = new System.IO.StreamReader(cryptStreem, System.Text.Encoding.UTF8); //以UTF8编码从字节流中读取字符. string result = srOut.ReadToEnd(); srOut.Close(); cryptStreem.Close(); msIn.Close(); return result; } catch (Exception ep) { throw (ep); // return ""; } }
public void init(byte[] key) { if(key.Length>16) { byte[] tmp=new byte[16]; Array.Copy(key, 0, tmp, 0, 16); key=tmp; } // SecretKeySpec skey=new SecretKeySpec(key, "HmacMD5"); // mac=Mac.getInstance("HmacMD5"); // mac.init(skey); mentalis_mac = new Org.Mentalis.Security.Cryptography.HMAC(new System.Security.Cryptography.MD5CryptoServiceProvider(), key); cs = new System.Security.Cryptography.CryptoStream( System.IO.Stream.Null, mentalis_mac, System.Security.Cryptography.CryptoStreamMode.Write); }
/// <summary> /// Encripcion Byte Key IV /// </summary> /// <param name="clearData">Datos en limpio</param> /// <param name="Key">Llave</param> /// <param name="IV">IV</param> /// <returns>Arreglo de byte's.</returns> private static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Security.Cryptography.Rijndael alg; alg = System.Security.Cryptography.Rijndael.Create(); alg.Key = Key; alg.IV = IV; System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, alg.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(clearData, 0, clearData.Length); cs.Close(); byte[] encryptedData = ms.ToArray(); return encryptedData; }
public static MemoryStream EncryptStream(string key, byte[] content) { System.Security.Cryptography.SymmetricAlgorithm rijn = System.Security.Cryptography.SymmetricAlgorithm.Create(); using (MemoryStream ms = new MemoryStream()) { byte[] rgbIV = Encoding.ASCII.GetBytes("polychorepolycho"); byte[] rgbKey = Encoding.ASCII.GetBytes(key); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, rijn.CreateEncryptor(rgbKey, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(content, 0, content.Length); cs.Close(); return ms; } }
public static string Decrypt_Aes(this object value, string aesKey, string aesIV) { byte[] cipherText = GetBytes(value as string); byte[] Key = GetBytes(aesKey); byte[] IV = GetBytes(aesIV); // Check arguments. if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV"); // Declare the string used to hold // the decrypted text. string plaintext = null; // Create an AesCryptoServiceProvider object // with the specified key and IV. using (System.Security.Cryptography.AesCryptoServiceProvider aesAlg = new System.Security.Cryptography.AesCryptoServiceProvider()) { aesAlg.Key = Key; aesAlg.IV = IV; // Create a decrytor to perform the stream transform. System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } } return plaintext; }
public static string DeCrypt(string strEncryptedInput) { string strReturnValue = null; if (string.IsNullOrEmpty(strEncryptedInput)) { throw new System.ArgumentNullException("strEncryptedInput", "strEncryptedInput may not be string.Empty or NULL, because these are invid values."); } // Dim encASCII As New System.Text.ASCIIEncoding() System.Text.Encoding enc = System.Text.Encoding.UTF8; System.Security.Cryptography.RijndaelManaged objRijndael = new System.Security.Cryptography.RijndaelManaged(); byte[] baCipherTextBuffer = HexStringToByteArray(strEncryptedInput); byte[] baDecryptionKey = HexStringToByteArray(strKey); byte[] baInitializationVector = HexStringToByteArray(strIV); // This is where the message would be transmitted to a recipient // who already knows your secret key. Optionally, you can // also encrypt your secret key using a public key algorithm // and pass it to the mesage recipient along with the RijnDael // encrypted message. //Get a decryptor that uses the same key and IV as the encryptor. System.Security.Cryptography.ICryptoTransform ifaceAESdecryptor = objRijndael.CreateDecryptor(baDecryptionKey, baInitializationVector); //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(baCipherTextBuffer); System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, ifaceAESdecryptor, System.Security.Cryptography.CryptoStreamMode.Read); //Dim baPlainTextBuffer() As Byte //baPlainTextBuffer = New Byte(baCipherTextBuffer.Length) {} byte[] baPlainTextBuffer = new byte[baCipherTextBuffer.Length + 1]; //Read the data out of the crypto stream. csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length); //Convert the byte array back into a string. strReturnValue = enc.GetString(baPlainTextBuffer); if (!string.IsNullOrEmpty(strReturnValue)) strReturnValue = strReturnValue.Trim('\0'); return strReturnValue; }
/// <summary> /// 解密数据 /// </summary> /// <param name="Text"></param> /// <param name="sKey"></param> /// <returns></returns> private static string Decrypt(string Text, string sKey) { try { System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider(); int len; len = Text.Length / 2; byte[] inputByteArray = new byte[len]; int x, i; for (x = 0; x < len; x++) { i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.Default.GetString(ms.ToArray()); } catch { return Text; } }
public static string Decrypt(string cipherString) { byte[] cipherText = Convert.FromBase64String(cipherString); // Check arguments. if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText"); if (aesProperties.Key == null || aesProperties.Key.Length <= 0) throw new ArgumentNullException("Key"); if (aesProperties.InitializationVector == null || aesProperties.InitializationVector.Length <= 0) throw new ArgumentNullException("Key"); // Declare the string used to hold // the decrypted text. string plaintext = null; // Create an Aes object // with the specified key and IV. using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create()) { aesAlg.Key = aesProperties.Key; aesAlg.IV = aesProperties.InitializationVector; // Create a decrytor to perform the stream transform. System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } } return plaintext; }
/// <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); }
public static string Decrypt_Des(this object value, string desKey, string desIV) { string cryptedString = value as string; byte[] Key = GetBytes(desKey); byte[] IV = GetBytes(desIV); // Check arguments. if (string.IsNullOrEmpty(cryptedString)) throw new ArgumentNullException("cipherText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV"); System.Security.Cryptography.DESCryptoServiceProvider cryptoProvider = new System.Security.Cryptography.DESCryptoServiceProvider(); MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(cryptedString)); System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(Key, IV), System.Security.Cryptography.CryptoStreamMode.Read); StreamReader reader = new StreamReader(cryptoStream); return reader.ReadToEnd(); }
/// <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> /// 暗号化された文字列を復号化する /// </summary> /// <param name="str">暗号化された文字列</param> /// <param name="key">パスワード</param> /// <returns>復号化された文字列</returns> public static string DecryptString(string str, string key) { //DESCryptoServiceProviderオブジェクトの作成 var des = new System.Security.Cryptography.DESCryptoServiceProvider(); // 共有キーと初期化ベクタを決定 // パスワードをバイト配列にする var bytesKey = System.Text.Encoding.UTF8.GetBytes(key); // 共有キーと初期化ベクタを設定 des.Key = ResizeBytesArray(bytesKey, des.Key.Length); des.IV = ResizeBytesArray(bytesKey, des.IV.Length); // Base64で文字列をバイト配列に戻す var bytesIn = System.Convert.FromBase64String(str); // 暗号化されたデータを読み込むためのMemoryStream var msIn = new System.IO.MemoryStream(bytesIn); // DES復号化オブジェクトの作成 var desdecrypt = des.CreateDecryptor(); // 読み込むためのCryptoStreamの作成 var cryptStreem = new System.Security.Cryptography.CryptoStream(msIn, desdecrypt, System.Security.Cryptography.CryptoStreamMode.Read); // 復号化されたデータを取得するためのStreamReader var srOut = new System.IO.StreamReader(cryptStreem, System.Text.Encoding.UTF8); // 復号化されたデータを取得する var result = srOut.ReadToEnd(); // 閉じる srOut.Close(); cryptStreem.Close(); msIn.Close(); return result; }
private static byte[] Encrypt(byte[] cipherKey, byte[] plaintext) { var cipher = new System.Security.Cryptography.AesManaged(); cipher.Key = cipherKey; cipher.Mode = System.Security.Cryptography.CipherMode.CBC; cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126; using (var ms = new System.IO.MemoryStream()) { using (var cs = new System.Security.Cryptography.CryptoStream( ms, cipher.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { cs.Write(plaintext, 0, plaintext.Length); } var ciphertext = ms.ToArray(); var message = new byte[cipher.IV.Length + ciphertext.Length]; cipher.IV.CopyTo(message, 0); ciphertext.CopyTo(message, cipher.IV.Length); return message; } }
/// /// <summary> /// AES 加密 String -> Byte /// </summary> /// <param name="plainText"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static byte[] StringAesEncToByte(string plainText, string key, string iv) { #region AES 加密 String -> Byte // 检查参数 if (string.IsNullOrEmpty(plainText)) return null; if (string.IsNullOrEmpty(key)) return null; if (string.IsNullOrEmpty(iv)) return null; // 合成密钥 var enckey = StringMd5ShaToString(false, string.Format("<{0}/>{1}</{2}>[{3}]", iv, key, iv, EnDecryptConst), 16, false, 1, System.Text.Encoding.UTF8); var enciv = StringMd5ShaToString(false, string.Format("[{0}/]{1}[/{2}]<{3}>", iv, key, iv, EnDecryptConst), 16, false, 1, System.Text.Encoding.UTF8); // 转换密钥 var keybyte = System.Text.Encoding.UTF8.GetBytes(enckey); if (keybyte.Length <= 0) return null; var ivbyte = System.Text.Encoding.UTF8.GetBytes(enciv); if (ivbyte.Length <= 0) return null; byte[] encrypted; // 创建一个加密对象 using (var aesAlg = new System.Security.Cryptography.AesManaged()) { aesAlg.Key = keybyte; aesAlg.IV = ivbyte; // 创建一个加密来执行流的转换 var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // 为加密创建一个内存流 try { using (var msEncrypt = new System.IO.MemoryStream()) { using ( var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography .CryptoStreamMode.Write) ) { using (var swEncrypt = new System.IO.StreamWriter(csEncrypt)) { // 把所有数据写进流 swEncrypt.Write(plainText); } // 把内存流转换为字节数组 encrypted = msEncrypt.ToArray(); } } } catch { return null; } } // 返回此加密字节 return encrypted; #endregion }
public static string Encrypt(string strPlainText) { //Dim roundtrip As String //Dim encASCII As New System.Text.ASCIIEncoding() System.Text.Encoding enc = System.Text.Encoding.UTF8; System.Security.Cryptography.RijndaelManaged objRijndael = new System.Security.Cryptography.RijndaelManaged(); //Dim fromEncrypt() As Byte byte[] baCipherTextBuffer = null; byte[] baPlainTextBuffer = null; byte[] baEncryptionKey = null; byte[] baInitializationVector = null; //Create a new key and initialization vector. //objRijndael.GenerateKey() //objRijndael.GenerateIV() objRijndael.Key = HexStringToByteArray(strKey); objRijndael.IV = HexStringToByteArray(strIV); //Get the key and initialization vector. baEncryptionKey = objRijndael.Key; baInitializationVector = objRijndael.IV; //strKey = ByteArrayToHexString(baEncryptionKey) //strIV = ByteArrayToHexString(baInitializationVector) //Get an encryptor. System.Security.Cryptography.ICryptoTransform ifaceAESencryptor = objRijndael.CreateEncryptor(baEncryptionKey, baInitializationVector); //Encrypt the data. System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, ifaceAESencryptor, System.Security.Cryptography.CryptoStreamMode.Write); //Convert the data to a byte array. baPlainTextBuffer = enc.GetBytes(strPlainText); //Write all data to the crypto stream and flush it. csEncrypt.Write(baPlainTextBuffer, 0, baPlainTextBuffer.Length); csEncrypt.FlushFinalBlock(); //Get encrypted array of bytes. baCipherTextBuffer = msEncrypt.ToArray(); return ByteArrayToHexString(baCipherTextBuffer); }
public static string Decrypt(string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(CipherText)) return ""; byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(CipherText); System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged(); SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = 0; using (System.Security.Cryptography.ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)) { using (MemoryStream MemStream = new MemoryStream(CipherTextBytes)) { using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount); }
public static string Encrypt(string plainText) { // Check arguments. if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException("plainText"); if (aesProperties.Key == null || aesProperties.Key.Length <= 0) throw new ArgumentNullException("Key"); if (aesProperties.InitializationVector == null || aesProperties.InitializationVector.Length <= 0) throw new ArgumentNullException("Key"); // Create an Aes object // with the specified key and IV. byte[] encrypted = null; using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create()) { aesAlg.Key = aesProperties.Key; aesAlg.IV = aesProperties.InitializationVector; // Create a decrytor to perform the stream transform. System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } return Convert.ToBase64String(encrypted); }
/// <summary> /// Descriptografa um array de bytes em outro array de bytes. /// </summary> /// <returns>Array de bytes descriptografado.</returns> /// <param name="p_ciphertextbytes">Array de bytes criptografado.</param> public byte[] DecryptToBytes(byte[] p_ciphertextbytes) { byte[] v_plaintextbytes; byte[] v_decryptedbytes; int v_decryptedbytecount; int v_saltlength; System.IO.MemoryStream v_memory; System.Security.Cryptography.CryptoStream v_crypto; try { this.Initialize(); v_memory = new System.IO.MemoryStream(p_ciphertextbytes); v_decryptedbytes = new byte[p_ciphertextbytes.Length]; lock (this) { v_crypto = new System.Security.Cryptography.CryptoStream(v_memory, this.v_decryptor, System.Security.Cryptography.CryptoStreamMode.Read); v_decryptedbytecount = v_crypto.Read(v_decryptedbytes, 0, v_decryptedbytes.Length); v_memory.Close(); v_crypto.Close(); } v_saltlength = (v_decryptedbytes[0] & 0x03) | (v_decryptedbytes[1] & 0x0c) | (v_decryptedbytes[2] & 0x30) | (v_decryptedbytes[3] & 0xc0); v_plaintextbytes = new byte[v_decryptedbytecount - v_saltlength]; System.Array.Copy(v_decryptedbytes, v_saltlength, v_plaintextbytes, 0, v_decryptedbytecount - v_saltlength); return v_plaintextbytes; } catch (System.Security.Cryptography.CryptographicException e) { throw new Spartacus.Utils.Exception(e); } }
/// <summary> /// Criptografa um array de bytes em outro array de bytes. /// </summary> /// <returns>Array de bytes criptografado.</returns> /// <param name="p_plaintextbytes">Array de bytes.</param> public byte[] EncryptToBytes(byte[] p_plaintextbytes) { byte[] v_ciphertextbytes; byte[] v_plaintextbyteswithsalt; System.IO.MemoryStream v_memory; System.Security.Cryptography.CryptoStream v_crypto; this.Initialize(); v_plaintextbyteswithsalt = this.AddSalt(p_plaintextbytes); v_memory = new System.IO.MemoryStream(); lock (this) { v_crypto = new System.Security.Cryptography.CryptoStream(v_memory, this.v_encryptor, System.Security.Cryptography.CryptoStreamMode.Write); v_crypto.Write(v_plaintextbyteswithsalt, 0, v_plaintextbyteswithsalt.Length); v_crypto.FlushFinalBlock(); v_ciphertextbytes = v_memory.ToArray(); v_memory.Close(); v_crypto.Close(); return v_ciphertextbytes; } }
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; }