static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher) { Byte[] CipherCalculated; Console.WriteLine("Encrypting the following bytes:"); PrintByteArray(Plain); Console.WriteLine("With the following Key:"); PrintByteArray(Key); Console.WriteLine("and IV:"); PrintByteArray(IV); Console.WriteLine("Expecting this ciphertext:"); PrintByteArray(Cipher); ICryptoTransform sse = aes.CreateEncryptor(Key, IV); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs.Write(Plain,0,Plain.Length); cs.FlushFinalBlock(); CipherCalculated = ms.ToArray(); cs.Close(); Console.WriteLine("Computed this cyphertext:"); PrintByteArray(CipherCalculated); if (!Compare(Cipher, CipherCalculated)) { Console.WriteLine("ERROR: result is different from the expected"); return false; } Console.WriteLine("OK"); return true; }
public static string Decrypt(string originalString, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[originalString.Length / 2]; for (int x = 0; x < originalString.Length / 2; x++) { int i = (Convert.ToInt32(originalString.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } //建立加密对象的密钥和偏移量,此值重要,不能修改 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象 StringBuilder ret = new StringBuilder(); return System.Text.Encoding.Default.GetString(ms.ToArray()); }
//cmThe function used to decrypt the text private static string Decrypt(string strText, string SaltKey) { byte[] byKey = { }; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef }; byte[] inputByteArray = new byte[strText.Length + 1]; try { byKey = System.Text.Encoding.UTF8.GetBytes(SaltKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (Exception ex) { return ex.Message; } }
public static bool ForCodeCoverage() { AesManaged aes = new AesManaged(); using (ICryptoTransform cte = aes.CreateEncryptor(), ctd = aes.CreateDecryptor()) { byte[] plain1 = new byte[64]; for (int i = 0; i < plain1.Length; i++) plain1[i] = (byte)i; byte[] encr1 = cte.TransformFinalBlock(plain1, 0, plain1.Length); using(MemoryStream ms = new MemoryStream()) using(CryptoStream cs = new CryptoStream(ms, ctd, CryptoStreamMode.Write)) { cs.Write(encr1, 0, 16); cs.Write(encr1, 16, 16); cs.Write(encr1, 32, 16); cs.Write(encr1, 48, encr1.Length-48); cs.FlushFinalBlock(); byte[] plain2 = ms.ToArray(); if (!Compare(plain1, plain2)) { Console.WriteLine("CodeCoverage case failed"); return false; } return true; } } }
/// <summary> /// Encrypt some text and return an encrypted byte array. /// </summary> /// <param name="TextValue">The Text to encrypt</param> /// <returns>byte[] of the encrypted value</returns> public byte[] Encrypt(string TextValue) { //Translates our text value into a byte array. Byte[] bytes = UTFEncoder.GetBytes(TextValue); //Used to stream the data in and out of the CryptoStream. MemoryStream memoryStream = new MemoryStream(); /* * We will have to write the unencrypted bytes to the * stream, then read the encrypted result back from the * stream. */ #region Write the decrypted value to the encryption stream CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write); cs.Write(bytes, 0, bytes.Length); cs.FlushFinalBlock(); #endregion #region Read encrypted value back out of the stream memoryStream.Position = 0; byte[] encrypted = new byte[memoryStream.Length]; memoryStream.Read(encrypted, 0, encrypted.Length); #endregion //Clean up. cs.Close(); memoryStream.Close(); return encrypted; }
/// <summary> /// Encrypt string using AES 128 /// </summary> /// <param name="plaintext"></param> /// <param name="key"></param> /// <returns></returns> public static string Encrypt(string plaintext, string key) { byte[] keybytes = Encoding.UTF8.GetBytes(key); RijndaelManaged aes = new RijndaelManaged(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; byte[] IVbytes = Encoding.ASCII.GetBytes("dongbinhuiasxiny"); ICryptoTransform encryptor = aes.CreateEncryptor(keybytes, IVbytes); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); byte[] plainBytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(plaintext))); cs.Write(plainBytes, 0, plainBytes.Length); cs.FlushFinalBlock(); byte[] cipherBytes = ms.ToArray(); ms.Close(); cs.Close(); return Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length); }
public static string Encrypt(string plainText, string passPhrase) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null)) { byte[] keyBytes = password.GetBytes(keysize / 8); using (RijndaelManaged symmetricKey = new RijndaelManaged()) { symmetricKey.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)) { using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = memoryStream.ToArray(); return Convert.ToBase64String(cipherTextBytes); } } } } } }
public static void Main() { string PlainText = "Titan"; byte[] PlainBytes = new byte[5]; PlainBytes = Encoding.ASCII.GetBytes(PlainText.ToCharArray()); PrintByteArray(PlainBytes); byte[] CipherBytes = new byte[8]; PasswordDeriveBytes pdb = new PasswordDeriveBytes("Titan", null); byte[] IV = new byte[8]; byte[] Key = pdb.CryptDeriveKey("RC2", "SHA1", 40, IV); PrintByteArray(Key); PrintByteArray(IV); // Now use the data to encrypt something RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); Console.WriteLine(rc2.Padding); Console.WriteLine(rc2.Mode); ICryptoTransform sse = rc2.CreateEncryptor(Key, IV); MemoryStream ms = new MemoryStream(); CryptoStream cs1 = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs1.Write(PlainBytes, 0, PlainBytes.Length); cs1.FlushFinalBlock(); CipherBytes = ms.ToArray(); cs1.Close(); Console.WriteLine(Encoding.ASCII.GetString(CipherBytes)); PrintByteArray(CipherBytes); ICryptoTransform ssd = rc2.CreateDecryptor(Key, IV); CryptoStream cs2 = new CryptoStream(new MemoryStream(CipherBytes), ssd, CryptoStreamMode.Read); byte[] InitialText = new byte[5]; cs2.Read(InitialText, 0, 5); Console.WriteLine(Encoding.ASCII.GetString(InitialText)); PrintByteArray(InitialText); }
public string Encrypt(string item, string password) { if (item == null) { throw new ArgumentNullException ("item"); } if (string.IsNullOrEmpty (password)) { throw new ArgumentNullException ("password"); } var des = new DESCryptoServiceProvider (); des.GenerateIV (); var rfc2898DeriveBytes = new Rfc2898DeriveBytes (password, des.IV, ITERATIONS); byte[] key = rfc2898DeriveBytes.GetBytes (8); using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, des.IV), CryptoStreamMode.Write)) { memoryStream.Write (des.IV, 0, des.IV.Length); byte[] bytes = Encoding.UTF8.GetBytes (item); cryptoStream.Write (bytes, 0, bytes.Length); cryptoStream.FlushFinalBlock (); return Convert.ToBase64String (memoryStream.ToArray ()); } } }
public static string DecryptString(string input, string cryptographicProvider_PublicKey, string cryptographicProvider_IV) { try { input = input.Replace(CryptographicProviderKey, String.Empty); using (var dataString = new MemoryStream()) { var service = new TripleDESCryptoServiceProvider().CreateDecryptor(Encoding.UTF8.GetBytes(cryptographicProvider_PublicKey), Encoding.UTF8.GetBytes(cryptographicProvider_IV)); using (var cryptoStream = new CryptoStream(dataString, service, CryptoStreamMode.Write)) { var inputData = Convert.FromBase64String(input); cryptoStream.Write(inputData, 0, inputData.Length); cryptoStream.FlushFinalBlock(); var dataResult = dataString.ToArray(); var resultString = Encoding.UTF8.GetString(Convert.FromBase64String(Convert.ToBase64String(dataResult))); cryptoStream.Close(); return resultString; } } } catch (Exception e) { return e.ToString(); } }
public static string Decrypt(string inName, string password) { PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, keySalt); Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); using (var fin = new FileStream(inName, FileMode.Open, FileAccess.Read)) using (var fout = new MemoryStream()) using (var cs = new CryptoStream(fout, alg.CreateDecryptor(), CryptoStreamMode.Write)) { byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = fin.Read(buffer, 0, buffer.Length); cs.Write(buffer, 0, bytesRead); } while (bytesRead != 0); cs.FlushFinalBlock(); return Encoding.ASCII.GetString(fout.ToArray()); } }
public static string Encrypt(string originalString, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); // 把字符串放到byte数组中 byte[] inputByteArray = Encoding.Default.GetBytes(originalString); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //原文使用ASCIIEncoding.ASCII方法的 //GetBytes方法 MemoryStream ms = new MemoryStream(); //使得输入密码必须输入英文文本 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); }
public static string Decrypt(string stringToDecrypt) { string sEncryptionKey = "thuynnxkey"; byte[] key = { }; byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 }; byte[] inputByteArray = new byte[stringToDecrypt.Length]; try { key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(stringToDecrypt); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (System.Exception ex) { SiAuto.Main.LogString("Lỗi :", ex.ToString()); return (string.Empty); } }
public static string Encrypt(this string text, string lKey) { try { using (Aes aes = new AesManaged()) { Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey)); aes.Key = deriveBytes.GetBytes(128 / 8); aes.IV = aes.Key; using (MemoryStream encryptionStream = new MemoryStream()) { using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] cleanText = Encoding.UTF8.GetBytes(text); encrypt.Write(cleanText, 0, cleanText.Length); encrypt.FlushFinalBlock(); } byte[] encryptedData = encryptionStream.ToArray(); string encryptedText = Convert.ToBase64String(encryptedData); return encryptedText; } } } catch { return String.Empty; } }
private string DeCryption(string content, string sKey, string sIV) { try { byte[] inputByteArray = Convert.FromBase64String(content); using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider()) { //byte[] inputByteArray = Convert.FromBase64String(content); desProvider.Key = System.Text.Encoding.ASCII.GetBytes(sKey); desProvider.IV = System.Text.Encoding.ASCII.GetBytes(sIV); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms,desProvider.CreateDecryptor(), CryptoStreamMode.Write)) { //cs.Clear(); cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = System.Text.Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return str; } } catch { return "String Not Base64 Encode!!!"; } }
/// <summary> /// ถอดรหัสข้อมูล /// </summary> /// <param name="Value">ข้อมูลที่ต้องการให้ถอดรหัส</param> /// <returns>ข้อมูลหลังจากถอดรหัส</returns> /// <example> /// clsSecurity.Decrypt("e0NDKIlUhHF3qcIdkmGpZw=="); /// </example> public string Decrypt(string Value) { #region Variable SymmetricAlgorithm mCSP; ICryptoTransform ct = null; MemoryStream ms = null; CryptoStream cs = null; byte[] byt; byte[] result; #endregion #region Procedure mCSP = new RijndaelManaged(); try { mCSP.Key = _key; mCSP.IV = _initVector; ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV); byt = Convert.FromBase64String(Value); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); result = ms.ToArray(); } catch { result = null; } finally { if (ct != null) ct.Dispose(); if (ms != null) if (ms.CanRead) { ms.Dispose(); } if (cs != null) if (cs.CanRead) { cs.Dispose(); } } try { return ASCIIEncoding.UTF8.GetString(result); } catch (Exception) { return ""; } #endregion }
public byte[] Encrypt(byte[] cipherText) { MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write); cryptoStream.Write(cipherText, 0, (int)cipherText.Length); cryptoStream.FlushFinalBlock(); memoryStream.Close(); return memoryStream.ToArray(); }
/**/ /// <summary> /// 对称加密解密的密钥 /// </summary> public static string Key { get { return key; } set { key = value; } } #endregion Properties #region Methods /**/ /// <summary> /// DES解密 /// </summary> /// <param name="decryptString"></param> /// <returns></returns> public static string DesDecrypt(string decryptString) { byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8)); byte[] keyIV = keyBytes; byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); }
public string Encrypt(string SourceData) { byte[] SourceDataBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(SourceData); MemoryStream TempStream = new MemoryStream(); DESCryptoServiceProvider Encryptor = new DESCryptoServiceProvider(); CryptoStream EncryptionStream = new CryptoStream(TempStream, Encryptor.CreateEncryptor(Key, Iv), CryptoStreamMode.Write); EncryptionStream.Write(SourceDataBytes, 0, SourceDataBytes.Length); EncryptionStream.FlushFinalBlock(); byte[] EncryptedDataBytes = TempStream.GetBuffer(); //MsgBox(Convert.ToBase64String(EncryptedDataBytes, 0, TempStream.Length)) return Convert.ToBase64String(EncryptedDataBytes,0, Convert.ToInt16(TempStream.Length)); }
protected static string encryptUserData(UserData user_data) { // Encode the data into a JSON object JavaScriptSerializer s = new JavaScriptSerializer(); string json_data = s.Serialize(user_data); // Example of web.config configuration/appSettings section: string site_key = "12849"; string api_key = "0d2c15da-b36f-4a9c-8f44-45d2669c3013-05e1fb36-54aa-44fc-888e-93eb95811e2e"; byte[] bIV = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // Using byte arrays now instead of strings byte[] encrypted = null; byte[] data = Encoding.ASCII.GetBytes(json_data); // Pad using block size of 16 bytes int pad = 16 - (data.Length % 16); Array.Resize(ref data, data.Length + pad); for (var i = 0; i < pad; i++) data[data.Length - pad + i] = (byte)pad; // Use the AesManaged object to do the encryption using (AesManaged aesAlg = new AesManaged()) { aesAlg.IV = bIV; aesAlg.KeySize = 16 * 8; // Create the 16-byte salted hash SHA1 sha1 = SHA1.Create(); byte[] saltedHash = sha1.ComputeHash(Encoding.ASCII.GetBytes(api_key + site_key), 0, (api_key + site_key).Length); Array.Resize(ref saltedHash, 16); aesAlg.Key = saltedHash; // Encrypt using the AES Managed object ICryptoTransform encryptor = aesAlg.CreateEncryptor(); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(data, 0, data.Length); csEncrypt.FlushFinalBlock(); } encrypted = msEncrypt.ToArray(); } } // Return the Base64-encoded encrypted data return Convert.ToBase64String(encrypted, Base64FormattingOptions.None) .TrimEnd("=".ToCharArray()) // Remove trailing equal (=) characters .Replace("+", "-") // Change any plus (+) characters to dashes (-) .Replace("/", "_"); // Change any slashes (/) characters to underscores (_) }
public string DecryptString(string Value) { ICryptoTransform ct = mCSP.CreateDecryptor(); byte[] byt = Convert.FromBase64String(Value); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return Encoding.UTF8.GetString(ms.ToArray()); }
public static string DesEncrypt(string encryptString, string encrptKey) { if (string.IsNullOrEmpty(encrptKey)) encrptKey = Key; byte[] keyBytes = Encoding.UTF8.GetBytes(encrptKey); byte[] keyIV = keyBytes; byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); }
public string Encrypto(string Source) { byte[] bytes = Encoding.UTF8.GetBytes(Source); MemoryStream stream = new MemoryStream(); this.mobjCryptoService.Key = this.GetLegalKey(); this.mobjCryptoService.IV = this.GetLegalIV(); ICryptoTransform transform = this.mobjCryptoService.CreateEncryptor(); CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write); stream2.Write(bytes, 0, bytes.Length); stream2.FlushFinalBlock(); stream.Close(); return Convert.ToBase64String(stream.ToArray()); }
static Boolean Test() { Byte[] PlainText = {0, 1, 2, 3, 4, 5, 6, 7}; //, 8, 9, 10, 11, 12, 13, 14, 15}; Byte[] Key = {1, 1, 1, 1, 1, 1, 1, 2}; Byte[] IV = {1, 1, 1, 1, 1, 1, 1, 1}; Console.WriteLine("Encrypting the following bytes:"); PrintByteArray(PlainText); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Mode = CipherMode.ECB; // des.FeedbackSize = 0; des.Padding = PaddingMode.None; Console.WriteLine("DES default key size = " + des.KeySize); ICryptoTransform sse = des.CreateEncryptor(Key, IV); Console.WriteLine("SSE mode = " + des.Mode); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs.Write(PlainText,0,PlainText.Length); cs.FlushFinalBlock(); byte[] CipherText = ms.ToArray(); cs.Close(); Console.WriteLine("Cyphertext:"); PrintByteArray(CipherText); Console.WriteLine("Decrypting..."); // DESCryptoServiceProvider des = new DESCryptoServiceProvider(); // des.Mode = CipherMode.ECB; // des.FeedbackSize = 0; ICryptoTransform ssd = des.CreateDecryptor(Key, IV); Console.WriteLine("SSD mode = " + des.Mode); cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read); byte[] NewPlainText = new byte[8]; cs.Read(NewPlainText,0,8); PrintByteArray(NewPlainText); if (!Compare(PlainText, NewPlainText)) { Console.WriteLine("ERROR: roundtrip failed"); return false; } return true; }
static Boolean Test(CipherMode md) { Byte[] PlainText = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; Byte[] Key = {1, 1, 1, 1, 1, 1, 1, 1,2,2,2,2,2,2,2,2}; Byte[] IV = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115}; Console.WriteLine("Encrypting the following bytes:"); PrintByteArray(PlainText); RijndaelManaged des = new RijndaelManaged(); des.Mode = md; // des.FeedbackSize = 0; // des.Padding = PaddingMode.PKCS7; Console.WriteLine("DES default key size = " + des.KeySize); ICryptoTransform sse = des.CreateEncryptor(Key, IV); Console.WriteLine("SSE mode = " + des.Mode); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write); cs.Write(PlainText,0,PlainText.Length); cs.FlushFinalBlock(); byte[] CipherText = ms.ToArray(); cs.Close(); Console.WriteLine("Cyphertext:"); PrintByteArray(CipherText); Console.WriteLine("Decrypting..."); // RijndaelManaged des = new RijndaelManaged(); // des.Mode = CipherMode.ECB; // des.FeedbackSize = 0; ICryptoTransform ssd = des.CreateDecryptor(Key, IV); Console.WriteLine("SSD mode = " + des.Mode); cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read); byte[] NewPlainText = new byte[PlainText.Length]; cs.Read(NewPlainText,0,PlainText.Length); PrintByteArray(NewPlainText); if (!Compare(PlainText, NewPlainText)) { Console.WriteLine("ERROR: roundtrip failed"); return false; } return true; }
/** * str_in is in format of FF-FF-FF-FF, hex string with the dashes seperating each byte */ public static string DecryptAES(string str_in) { MemoryStream msAES = new MemoryStream(); CryptoStream csAES = new CryptoStream(msAES, GetDecryptor(), CryptoStreamMode.Write); byte[] bstr = HexStringToBytes(str_in); csAES.Write(bstr, 0, bstr.Length); csAES.FlushFinalBlock(); byte[] decMsg = msAES.ToArray(); msAES.Close(); csAES.Close(); return BytesToString(decMsg); }
public static byte[] EncryptString(string data) { byte[] ClearData = Encoding.UTF8.GetBytes(data); SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(); Algorithm.Key = SymmetricKey; MemoryStream Target = new MemoryStream(); Algorithm.GenerateIV(); Target.Write(Algorithm.IV, 0, Algorithm.IV.Length); CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(ClearData, 0, ClearData.Length); cs.FlushFinalBlock(); return Target.ToArray(); }
public static string DESEncrypt(string input) { byte[] bytes = Encoding.ASCII.GetBytes((string)ConfigurationSettings.AppSettings["CipherKeyProd"]); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write); StreamWriter writer = new StreamWriter(cryptoStream); writer.Write(input); writer.Flush(); cryptoStream.FlushFinalBlock(); writer.Flush(); return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length); }
public static string DecryptString(byte[] data) { SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(); Algorithm.Key = SymmetricKey; MemoryStream Target = new MemoryStream(); int ReadPos = 0; byte[] IV = new byte[Algorithm.IV.Length]; Array.Copy(data, IV, IV.Length); Algorithm.IV = IV; ReadPos += Algorithm.IV.Length; CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(data, ReadPos, data.Length - ReadPos); cs.FlushFinalBlock(); return Encoding.UTF8.GetString(Target.ToArray()); }
//Encrypt & Decrypt Files public static string EncryptFile(string inFile) { Aes aes = Aes.Create(); ICryptoTransform transform = aes.CreateEncryptor(); byte[] keyEncrypted = rsa.Encrypt(aes.Key, false); byte[] LenK = new byte[4]; //Key length byte[] LenIV = new byte[4]; //boot vector length int lKey = keyEncrypted.Length; LenK = BitConverter.GetBytes(lKey); int lIV = aes.IV.Length; LenIV = BitConverter.GetBytes(lIV); int startFileName = inFile.LastIndexOf("\\") + 1; string outFile = EncrFloder + inFile.Substring(startFileName) + ".enc"; try { using (FileStream outFs = new FileStream(outFile, FileMode.Create)) { outFs.Write(LenK, 0, 4); outFs.Write(LenIV, 0, 4); outFs.Write(keyEncrypted, 0, lKey); outFs.Write(aes.IV, 0, lIV); //Encrypting using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write)) { int count = 0; int offset = 0; //BlockSizeBytes int sizeBytes = aes.BlockSize / 8; byte[] date = new byte[sizeBytes]; int bytesRead = 0; using (FileStream inFs = new FileStream(inFile, FileMode.Open)) { do { count = inFs.Read(date, 0, sizeBytes); offset += count; outStreamEncrypted.Write(date, 0, count); bytesRead += sizeBytes; } while (count > 0); inFs.Close(); } outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } outFs.Close(); //Removing file original DialogResult option = new DialogResult(); option = MessageBox.Show("Delete file when finished encryption?", "Caution!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (option == DialogResult.OK) { File.Delete(inFile); } } } catch (Exception ex) { return(ex.Message); } return($"File encrypted.\n Origin: {inFile}\n Destiny: {outFile}"); }
private void tbutton_Click(object sender, EventArgs e) { string VIkey = "@15sd45defcdr965"; switch (tbutton.Text) { default: break; case "Encryption": { try { byte[] plaintextbyte = Encoding.UTF8.GetBytes(richTextBox1.Text); byte[] keyBytes = new Rfc2898DeriveBytes(textBox1.Text, Encoding.ASCII.GetBytes(textBox2.Text)).GetBytes(256 / 8); var symmetrickey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; var encryptor = symmetrickey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIkey)); byte[] cipherTextBytes; using (var memoryStream = new MemoryStream()) { 23 using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plaintextbyte, 0, plaintextbyte.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); cryptoStream.Close(); } memoryStream.Close(); richTextBox2.Text = Convert.ToBase64String(cipherTextBytes); label22.Text = "Done"; MessageBox.Show("The Encryption Operation was Successful", "Successful Encryption", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception) { label22.Text = "The Decryption Operation Failed"; MessageBox.Show("Please Insert the Text You want to Encrypt and a Valid Password with 8 Characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; } case "Decryption": { try { byte[] cipherTextBytes = Convert.FromBase64String(richTextBox2.Text); byte[] keyBytes = new Rfc2898DeriveBytes(textBox1.Text, Encoding.ASCII.GetBytes(textBox2.Text)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None }; var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIkey)); var memoryStream = new MemoryStream(cipherTextBytes); var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] PlainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); richTextBox1.Text = Encoding.UTF8.GetString(PlainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray()); label22.Text = "Done"; 24 MessageBox.Show("The Decyption Operation was Successful ", "Successful Decyrption", MessageBoxButtons.OK, MessageBoxIcon.Information ); } catch (Exception ) { label22.Text = "Decryption Operation Failed"; MessageBox.Show("Please Insert the Text you want to Decrypt and a Valid Password with 8 Characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } break; } } }
private void DecryptFile(string inFile) { RijndaelManaged rjndl = new RijndaelManaged(); rjndl.KeySize = 256; rjndl.BlockSize = 256; rjndl.Mode = CipherMode.CBC; byte[] LenK = new byte[4]; byte[] LenIV = new byte[4]; string outFile = DecrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt"; using (FileStream inFs = new FileStream(EncrFolder + inFile, FileMode.Open)) { inFs.Seek(0, SeekOrigin.Begin); inFs.Seek(0, SeekOrigin.Begin); inFs.Read(LenK, 0, 3); inFs.Seek(4, SeekOrigin.Begin); inFs.Read(LenIV, 0, 3); int lenK = BitConverter.ToInt32(LenK, 0); int lenIV = BitConverter.ToInt32(LenIV, 0); int startC = lenK + lenIV + 8; int lenC = (int)inFs.Length - startC; byte[] KeyEncrypted = new byte[lenK]; byte[] IV = new byte[lenIV]; inFs.Seek(8, SeekOrigin.Begin); inFs.Read(KeyEncrypted, 0, lenK); inFs.Seek(8 + lenK, SeekOrigin.Begin); inFs.Read(IV, 0, lenIV); var private_key = (RSAParameters)Session["private_key"]; myRSA.ImportParameters(private_key); byte[] KeyDecrypted = myRSA.Decrypt(KeyEncrypted, false); ICryptoTransform transform = rjndl.CreateDecryptor(KeyDecrypted, IV); using (FileStream outFs = new FileStream(outFile, FileMode.Create)) { int count = 0; int offset = 0; int blockSizeBytes = rjndl.BlockSize / 8; byte[] data = new byte[blockSizeBytes]; inFs.Seek(startC, SeekOrigin.Begin); using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write)) { do { count = inFs.Read(data, 0, blockSizeBytes); offset += count; outStreamDecrypted.Write(data, 0, count); }while (count > 0); outStreamDecrypted.FlushFinalBlock(); outStreamDecrypted.Close(); } outFs.Close(); } inFs.Close(); } }
/// <summary> /// A helper function to convert an encrypted HotDocs package stream to an unencrypted HotDocs package stream. /// </summary> /// <param name="ms">The encrypted HotDocs package file/stream.</param> /// <param name="rsaParamsXml">RSA key serialized to XML.</param> /// <returns>If rsaParamsXml is null or empty or if the input stream ms is not an encrypted HotDocs package, the input stream ms is simply returned. Otherwise, the input stream ms is being copied and decrypted to the returned output stream.</returns> public static MemoryStream Decrypt(MemoryStream ms, string rsaParamsXml) { byte[] buf = new byte[4]; byte[] encryptedAesKey; byte[] decryptedAesKey; byte[] encryptedAesIV; byte[] decryptedAesIV; int len; MemoryStream s; // if (ms.Length < 4) { return(ms); } ms.Position = 0; ms.Read(buf, 0, 4); if (EqualBytes(buf, ZipSig, 4)) { return(ms); // Unencrypted zip file } if (!EqualBytes(buf, HDSig, 4)) { throw new Exception("Encrypted package has an unknown file signature"); } if (string.IsNullOrEmpty(rsaParamsXml)) { throw new Exception("No key provided for encrypted package"); } len = ms.ReadByte(); if (len > 0) { throw new Exception("This package was encrypted with a later version of the program"); } len = ms.ReadByte(); if (len <= 0 || len > 255) { throw new Exception("Unknown key length detected"); } encryptedAesKey = new byte[len]; ms.Read(encryptedAesKey, 0, len); len = ms.ReadByte(); if (len <= 0 || len > 255) { throw new Exception("Unknown iv length detected"); } encryptedAesIV = new byte[len]; ms.Read(encryptedAesIV, 0, len); s = new MemoryStream(); using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(rsaParamsXml); decryptedAesKey = rsa.Decrypt(encryptedAesKey, false); decryptedAesIV = rsa.Decrypt(encryptedAesIV, false); } aes.Key = decryptedAesKey; aes.IV = decryptedAesIV; MemoryStream temps = new MemoryStream(); using (CryptoStream cs = new CryptoStream(temps, aes.CreateDecryptor(), CryptoStreamMode.Write)) { CopyStream(cs, ms); cs.FlushFinalBlock(); cs.Flush(); temps.Position = 0; CopyStream(s, temps); } } /* --- Doesn't work. RSA Encrypt function can only encrypt up to 245 bytes! * See http://social.msdn.microsoft.com/forums/en-US/clr/thread/4e3ada0a-bcaf-4c67-bdef-a6b15f5bfdce/ * byte[] encryptedData; * byte[] decryptedData; * using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) * { * rsa.FromXmlString(rsaParamsXml); * encryptedData = new byte[len]; * ms.Read(encryptedData, 0, len); * decryptedData = rsa.Decrypt(encryptedData, false); * s.Write(decryptedData, 0, decryptedData.Length); * } */ return(s); }
public static string DesencriptarTexto(string strTexto, ArrayList arrPConexion) { byte[] mIV = new byte[8]; byte[] mKey = new byte[8]; ArrayList arrConexion = new ArrayList(); string strMIV = string.Empty; string strMKey = string.Empty; string strAuxiliar = string.Empty; bool blnContinuar = true; DESCryptoServiceProvider des; byte[] inputByteArray; System.Text.Encoding encoding; MemoryStream ms; CryptoStream cs; if (arrPConexion == null) { arrConexion = CargarArchivoConexion(arrConexion); } else { arrConexion = arrPConexion; } strMIV = arrConexion[6].ToString(); strMKey = arrConexion[7].ToString(); while (blnContinuar) { strAuxiliar = strMIV.Substring(0, 4); mIV[Convert.ToInt32(strAuxiliar.Substring(2, 2)) - 1] = Convert.ToByte(strAuxiliar.Substring(0, 2)); strAuxiliar = strMKey.Substring(0, 4); mKey[Convert.ToInt32(strAuxiliar.Substring(2, 2)) - 1] = Convert.ToByte(strAuxiliar.Substring(0, 2)); if (strMIV.Length > 4) { strMIV = strMIV.Substring(5); strMKey = strMKey.Substring(5); } else { blnContinuar = false; } } try { des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(strTexto); ms = new MemoryStream(); cs = new CryptoStream(ms, des.CreateDecryptor(mKey, mIV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); } catch (Exception e) { System.Console.WriteLine(e.Message + " " + e.InnerException); des = null; ms = null; cs = null; arrConexion = null; strMIV = null; strMKey = null; strAuxiliar = null; return("-1"); } encoding = System.Text.Encoding.UTF8; strAuxiliar = encoding.GetString(ms.ToArray()); des = null; ms = null; cs = null; arrConexion = null; strMIV = null; strMKey = null; return(strAuxiliar); }
/// <summary> /// Decrypts a file which was encrypted by its sister method <see cref="EncryptFile"/> /// </summary> /// <param name="path"></param> /// <param name="certCerPath"></param> /// <param name="certPassword"></param> public static void DecryptFile(string path, string certCerPath, string certPassword) { //test inputs TestEnDeCryptInputs(path, certCerPath, certPassword); //import the cert var cert = new X509Certificate2(); cert.Import(certCerPath, certPassword, X509KeyStorageFlags.Exportable); var privKey = cert.PrivateKey as RSACryptoServiceProvider; if (privKey == null) { throw new ItsDeadJim("The private could not be resolved."); } var plainTextFile = Path.Combine(Path.GetDirectoryName(path) ?? Environment.CurrentDirectory, Path.GetFileNameWithoutExtension(path) ?? NfString.GetNfRandomName()); using (var aes = new AesManaged()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; var bufferK = new byte[4]; var bufferIv = new byte[4]; using (var inFs = new FileStream(path, FileMode.Open)) { inFs.Seek(0, SeekOrigin.Begin); inFs.Read(bufferK, 0, 3); inFs.Seek(4, SeekOrigin.Begin); inFs.Read(bufferIv, 0, 3); var lenK = BitConverter.ToInt32(bufferK, 0); var lenIv = BitConverter.ToInt32(bufferIv, 0); var startC = lenK + lenIv + 8; var enKey = new byte[lenK]; var iv = new byte[lenIv]; inFs.Seek(8, SeekOrigin.Begin); inFs.Read(enKey, 0, lenK); inFs.Seek(8 + lenK, SeekOrigin.Begin); inFs.Read(iv, 0, lenIv); var decKey = privKey.Decrypt(enKey, false); using (var trans = aes.CreateDecryptor(decKey, iv)) { using (var outFs = new FileStream(plainTextFile, FileMode.Create)) { var blockSz = aes.BlockSize / 8; var data = new byte[blockSz]; inFs.Seek(startC, SeekOrigin.Begin); using (var outCrypto = new CryptoStream(outFs, trans, CryptoStreamMode.Write)) { var count = 0; do { count = inFs.Read(data, 0, blockSz); outCrypto.Write(data, 0, count); } while (count > 0); outCrypto.FlushFinalBlock(); outCrypto.Close(); } outFs.Close(); } inFs.Close(); } // end decryptor } // end fs in } //end aes managed }
static bool smethod_0(int int_3) { if (Class14.byte_1.Length == 0) { BinaryReader binaryReader = new BinaryReader(typeof(Class14).Assembly.GetManifestResourceStream("552aa579-b26a-42c6-927d-ada4908113cd")); binaryReader.BaseStream.Position = 0L; byte[] array = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length); byte[] array2 = new byte[32]; array2[0] = 181; array2[0] = 122; array2[0] = 116; array2[0] = 131; array2[1] = 147; array2[1] = 98; array2[1] = 215; array2[2] = 166; array2[2] = 117; array2[2] = 156; array2[2] = 48; array2[2] = 253; array2[3] = 186; array2[3] = 105; array2[3] = 113; array2[3] = 199; array2[4] = 148; array2[4] = 183; array2[4] = 72; array2[4] = 171; array2[4] = 104; array2[4] = 72; array2[5] = 112; array2[5] = 196; array2[5] = 155; array2[6] = 154; array2[6] = 96; array2[6] = 23; array2[7] = 90; array2[7] = 132; array2[7] = 46; array2[8] = 160; array2[8] = 101; array2[8] = 169; array2[8] = 59; array2[8] = 100; array2[8] = 135; array2[9] = 26; array2[9] = 163; array2[9] = 55; array2[9] = 74; array2[9] = 31; array2[10] = 116; array2[10] = 153; array2[10] = 59; array2[10] = 147; array2[10] = 122; array2[10] = 111; array2[11] = 81; array2[11] = 103; array2[11] = 103; array2[11] = 228; array2[12] = 219; array2[12] = 152; array2[12] = 53; array2[13] = 196; array2[13] = 164; array2[13] = 116; array2[13] = 108; array2[13] = 147; array2[13] = 138; array2[14] = 8; array2[14] = 88; array2[14] = 139; array2[15] = 100; array2[15] = 108; array2[15] = 165; array2[15] = 97; array2[15] = 213; array2[16] = 134; array2[16] = 95; array2[16] = 153; array2[16] = 134; array2[16] = 157; array2[16] = 48; array2[17] = 140; array2[17] = 152; array2[17] = 126; array2[17] = 96; array2[17] = 22; array2[18] = 216; array2[18] = 120; array2[18] = 155; array2[18] = 142; array2[18] = 217; array2[18] = 33; array2[19] = 91; array2[19] = 116; array2[19] = 96; array2[19] = 194; array2[19] = 4; array2[20] = 67; array2[20] = 119; array2[20] = 214; array2[21] = 117; array2[21] = 136; array2[21] = 90; array2[21] = 122; array2[21] = 215; array2[22] = 79; array2[22] = 111; array2[22] = 139; array2[22] = 177; array2[23] = 63; array2[23] = 86; array2[23] = 130; array2[23] = 120; array2[23] = 138; array2[23] = 175; array2[24] = 113; array2[24] = 92; array2[24] = 173; array2[24] = 122; array2[24] = 166; array2[25] = 129; array2[25] = 95; array2[25] = 98; array2[25] = 162; array2[25] = 89; array2[25] = 191; array2[26] = 124; array2[26] = 166; array2[26] = 37; array2[27] = 84; array2[27] = 47; array2[27] = 83; array2[27] = 135; array2[27] = 66; array2[27] = 218; array2[28] = 121; array2[28] = 140; array2[28] = 82; array2[28] = 149; array2[28] = 140; array2[28] = 29; array2[29] = 171; array2[29] = 160; array2[29] = 55; array2[29] = 77; array2[29] = 111; array2[29] = 163; array2[30] = 152; array2[30] = 118; array2[30] = 152; array2[30] = 153; array2[31] = 94; array2[31] = 171; array2[31] = 89; array2[31] = 35; byte[] rgbKey = array2; byte[] array3 = new byte[16]; array3[0] = 126; array3[0] = 161; array3[0] = 104; array3[1] = 31; array3[1] = 126; array3[1] = 148; array3[1] = 110; array3[1] = 173; array3[1] = 154; array3[2] = 122; array3[2] = 99; array3[2] = 86; array3[2] = 88; array3[2] = 88; array3[2] = 51; array3[3] = 168; array3[3] = 121; array3[3] = 39; array3[3] = 183; array3[3] = 148; array3[3] = 253; array3[4] = 102; array3[4] = 100; array3[4] = 100; array3[4] = 158; array3[4] = 21; array3[5] = 154; array3[5] = 204; array3[5] = 155; array3[5] = 168; array3[5] = 161; array3[6] = 160; array3[6] = 92; array3[6] = 203; array3[7] = 162; array3[7] = 157; array3[7] = 90; array3[7] = 20; array3[8] = 147; array3[8] = 127; array3[8] = 43; array3[9] = 98; array3[9] = 177; array3[9] = 127; array3[9] = 117; array3[10] = 154; array3[10] = 134; array3[10] = 205; array3[11] = 59; array3[11] = 172; array3[11] = 103; array3[11] = 170; array3[11] = 3; array3[12] = 134; array3[12] = 155; array3[12] = 88; array3[12] = 149; array3[12] = 216; array3[13] = 84; array3[13] = 138; array3[13] = 143; array3[13] = 115; array3[13] = 98; array3[13] = 139; array3[14] = 189; array3[14] = 88; array3[14] = 168; array3[14] = 136; array3[14] = 171; array3[15] = 187; array3[15] = 166; array3[15] = 209; byte[] array4 = array3; byte[] publicKeyToken = typeof(Class14).Assembly.GetName().GetPublicKeyToken(); if (publicKeyToken != null && publicKeyToken.Length > 0) { array4[1] = publicKeyToken[0]; array4[3] = publicKeyToken[1]; array4[5] = publicKeyToken[2]; array4[7] = publicKeyToken[3]; array4[9] = publicKeyToken[4]; array4[11] = publicKeyToken[5]; array4[13] = publicKeyToken[6]; array4[15] = publicKeyToken[7]; } ICryptoTransform transform = new RijndaelManaged { Mode = CipherMode.CBC }.CreateDecryptor(rgbKey, array4); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write); cryptoStream.Write(array, 0, array.Length); cryptoStream.FlushFinalBlock(); Class14.byte_1 = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); binaryReader.Close(); } if (Class14.byte_0.Length == 0) { Class14.byte_0 = Class14.smethod_6(Class14.smethod_5(typeof(Class14).Assembly).ToString()); } int num = 0; try { num = BitConverter.ToInt32(new byte[] { Class14.byte_1[int_3], Class14.byte_1[int_3 + 1], Class14.byte_1[int_3 + 2], Class14.byte_1[int_3 + 3] }, 0); } catch { } try { if (Class14.byte_0[num] == 128) { return(true); } } catch { } return(false); }
static string smethod_2(int int_3) { if (Class14.byte_3.Length == 0) { BinaryReader binaryReader = new BinaryReader(typeof(Class14).Assembly.GetManifestResourceStream("15b96398-9597-4145-8e52-82e25906b4b2")); binaryReader.BaseStream.Position = 0L; byte[] array = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length); byte[] array2 = new byte[32]; array2[0] = 126; array2[0] = 124; array2[0] = 146; array2[0] = 48; array2[1] = 152; array2[1] = 88; array2[1] = 254; array2[2] = 96; array2[2] = 27; array2[2] = 244; array2[3] = 102; array2[3] = 110; array2[3] = 124; array2[3] = 140; array2[4] = 98; array2[4] = 152; array2[4] = 174; array2[4] = 128; array2[5] = 185; array2[5] = 85; array2[5] = 173; array2[6] = 69; array2[6] = 147; array2[6] = 87; array2[6] = 86; array2[7] = 130; array2[7] = 124; array2[7] = 101; array2[8] = 109; array2[8] = 134; array2[8] = 157; array2[8] = 243; array2[9] = 132; array2[9] = 86; array2[9] = 47; array2[9] = 101; array2[9] = 197; array2[10] = 106; array2[10] = 135; array2[10] = 138; array2[10] = 182; array2[10] = 84; array2[10] = 214; array2[11] = 95; array2[11] = 140; array2[11] = 95; array2[11] = 92; array2[11] = 248; array2[12] = 157; array2[12] = 142; array2[12] = 11; array2[13] = 120; array2[13] = 62; array2[13] = 115; array2[13] = 138; array2[13] = 156; array2[13] = 145; array2[14] = 134; array2[14] = 138; array2[14] = 88; array2[14] = 164; array2[14] = 120; array2[14] = 105; array2[15] = 123; array2[15] = 112; array2[15] = 80; array2[15] = 122; array2[15] = 46; array2[16] = 165; array2[16] = 84; array2[16] = 132; array2[16] = 108; array2[16] = 108; array2[17] = 160; array2[17] = 143; array2[17] = 105; array2[17] = 94; array2[17] = 150; array2[17] = 166; array2[18] = 138; array2[18] = 90; array2[18] = 202; array2[19] = 162; array2[19] = 107; array2[19] = 186; array2[20] = 130; array2[20] = 128; array2[20] = 113; array2[20] = 148; array2[20] = 132; array2[20] = 165; array2[21] = 66; array2[21] = 171; array2[21] = 94; array2[21] = 194; array2[22] = 166; array2[22] = 155; array2[22] = 126; array2[22] = 121; array2[22] = 133; array2[22] = 14; array2[23] = 163; array2[23] = 106; array2[23] = 84; array2[23] = 195; array2[23] = 232; array2[24] = 154; array2[24] = 129; array2[24] = 142; array2[25] = 168; array2[25] = 153; array2[25] = 136; array2[25] = 94; array2[25] = 118; array2[25] = 131; array2[26] = 136; array2[26] = 102; array2[26] = 121; array2[27] = 150; array2[27] = 84; array2[27] = 102; array2[27] = 10; array2[28] = 141; array2[28] = 104; array2[28] = 120; array2[28] = 117; array2[29] = 145; array2[29] = 144; array2[29] = 85; array2[29] = 7; array2[30] = 84; array2[30] = 178; array2[30] = 157; array2[30] = 173; array2[30] = 88; array2[30] = 212; array2[31] = 75; array2[31] = 153; array2[31] = 139; byte[] rgbKey = array2; byte[] array3 = new byte[16]; array3[0] = 126; array3[0] = 121; array3[0] = 222; array3[1] = 29; array3[1] = 163; array3[1] = 167; array3[1] = 120; array3[1] = 234; array3[2] = 31; array3[2] = 60; array3[2] = 72; array3[3] = 145; array3[3] = 150; array3[3] = 247; array3[4] = 74; array3[4] = 165; array3[4] = 164; array3[5] = 117; array3[5] = 104; array3[5] = 113; array3[5] = 136; array3[5] = 224; array3[6] = 227; array3[6] = 157; array3[6] = 222; array3[6] = 166; array3[6] = 45; array3[7] = 129; array3[7] = 93; array3[7] = 118; array3[7] = 175; array3[7] = 89; array3[7] = 24; array3[8] = 103; array3[8] = 136; array3[8] = 170; array3[8] = 142; array3[9] = 156; array3[9] = 85; array3[9] = 55; array3[9] = 167; array3[9] = 196; array3[9] = 179; array3[10] = 104; array3[10] = 92; array3[10] = 147; array3[10] = 85; array3[10] = 219; array3[11] = 170; array3[11] = 192; array3[11] = 121; array3[11] = 140; array3[11] = 27; array3[12] = 122; array3[12] = 94; array3[12] = 108; array3[12] = 155; array3[13] = 75; array3[13] = 122; array3[13] = 49; array3[13] = 86; array3[13] = 120; array3[13] = 112; array3[14] = 156; array3[14] = 126; array3[14] = 90; array3[14] = 153; array3[14] = 170; array3[14] = 100; array3[15] = 205; array3[15] = 156; array3[15] = 212; array3[15] = 112; array3[15] = 136; byte[] array4 = array3; byte[] publicKeyToken = typeof(Class14).Assembly.GetName().GetPublicKeyToken(); if (publicKeyToken != null && publicKeyToken.Length > 0) { array4[1] = publicKeyToken[0]; array4[3] = publicKeyToken[1]; array4[5] = publicKeyToken[2]; array4[7] = publicKeyToken[3]; array4[9] = publicKeyToken[4]; array4[11] = publicKeyToken[5]; array4[13] = publicKeyToken[6]; array4[15] = publicKeyToken[7]; } ICryptoTransform transform = new RijndaelManaged { Mode = CipherMode.CBC }.CreateDecryptor(rgbKey, array4); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write); cryptoStream.Write(array, 0, array.Length); cryptoStream.FlushFinalBlock(); Class14.byte_3 = memoryStream.ToArray(); if (Class14.byte_3.Length > 0) { Class14.string_0 = new string[Class14.byte_3.Length / 4 + 1]; Class14.int_0 = new int[Class14.byte_3.Length / 4 + 1]; } memoryStream.Close(); cryptoStream.Close(); binaryReader.Close(); Assembly assembly = typeof(Class14).Assembly; Class14.int_2 = Marshal.GetHINSTANCE(assembly.GetModules()[0]).ToInt32(); Class14.long_0 = Marshal.GetHINSTANCE(assembly.GetModules()[0]).ToInt64(); } int num = int_3 / 4; if (Class14.int_0[num] > 0) { return(((string[])Class14.string_0)[Class14.int_0[num]]); } int num2 = BitConverter.ToInt32(Class14.byte_3, int_3); if (Class14.intptr_0 == IntPtr.Zero) { Class14.intptr_0 = Class14.OpenProcess(16u, 1, (uint)Process.GetCurrentProcess().Id); } byte[] array5 = new byte[4]; if (IntPtr.Size == 4) { Class14.ReadProcessMemory(Class14.intptr_0, new IntPtr(Class14.int_2 + num2), array5, 4u, out Class14.intptr_1); } else { Class14.ReadProcessMemory(Class14.intptr_0, new IntPtr(Class14.long_0 + (long)num2), array5, 4u, out Class14.intptr_1); } int num3 = BitConverter.ToInt32(array5, 0); array5 = new byte[num3]; if (IntPtr.Size == 4) { Class14.ReadProcessMemory(Class14.intptr_0, new IntPtr(Class14.int_2 + num2 + 4), array5, Convert.ToUInt32(num3), out Class14.intptr_1); } else { Class14.ReadProcessMemory(Class14.intptr_0, new IntPtr(Class14.long_0 + (long)num2 + 4L), array5, Convert.ToUInt32(num3), out Class14.intptr_1); } byte[] array6 = Class14.smethod_7(array5); string @string = Encoding.Unicode.GetString(array6, 0, array6.Length); Class14.int_0[num] = Class14.int_1; ((string[])Class14.string_0)[Class14.int_1] = @string; Class14.int_1++; return(@string); }
static string smethod_1(int int_3) { if (Class14.byte_2.Length == 0) { BinaryReader binaryReader = new BinaryReader(typeof(Class14).Assembly.GetManifestResourceStream("15b96398-9597-4145-8e52-82e25906b4b2")); binaryReader.BaseStream.Position = 0L; byte[] array = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length); byte[] array2 = new byte[32]; array2[0] = 126; array2[0] = 124; array2[0] = 146; array2[0] = 48; array2[1] = 152; array2[1] = 88; array2[1] = 254; array2[2] = 96; array2[2] = 27; array2[2] = 244; array2[3] = 102; array2[3] = 110; array2[3] = 124; array2[3] = 140; array2[4] = 98; array2[4] = 152; array2[4] = 174; array2[4] = 128; array2[5] = 185; array2[5] = 85; array2[5] = 173; array2[6] = 69; array2[6] = 147; array2[6] = 87; array2[6] = 86; array2[7] = 130; array2[7] = 124; array2[7] = 101; array2[8] = 109; array2[8] = 134; array2[8] = 157; array2[8] = 243; array2[9] = 132; array2[9] = 86; array2[9] = 47; array2[9] = 101; array2[9] = 197; array2[10] = 106; array2[10] = 135; array2[10] = 138; array2[10] = 182; array2[10] = 84; array2[10] = 214; array2[11] = 95; array2[11] = 140; array2[11] = 95; array2[11] = 92; array2[11] = 248; array2[12] = 157; array2[12] = 142; array2[12] = 11; array2[13] = 120; array2[13] = 62; array2[13] = 115; array2[13] = 138; array2[13] = 156; array2[13] = 145; array2[14] = 134; array2[14] = 138; array2[14] = 88; array2[14] = 164; array2[14] = 120; array2[14] = 105; array2[15] = 123; array2[15] = 112; array2[15] = 80; array2[15] = 122; array2[15] = 46; array2[16] = 165; array2[16] = 84; array2[16] = 132; array2[16] = 108; array2[16] = 108; array2[17] = 160; array2[17] = 143; array2[17] = 105; array2[17] = 94; array2[17] = 150; array2[17] = 166; array2[18] = 138; array2[18] = 90; array2[18] = 202; array2[19] = 162; array2[19] = 107; array2[19] = 186; array2[20] = 130; array2[20] = 128; array2[20] = 113; array2[20] = 148; array2[20] = 132; array2[20] = 165; array2[21] = 66; array2[21] = 171; array2[21] = 94; array2[21] = 194; array2[22] = 166; array2[22] = 155; array2[22] = 126; array2[22] = 121; array2[22] = 133; array2[22] = 14; array2[23] = 163; array2[23] = 106; array2[23] = 84; array2[23] = 195; array2[23] = 232; array2[24] = 154; array2[24] = 129; array2[24] = 142; array2[25] = 168; array2[25] = 153; array2[25] = 136; array2[25] = 94; array2[25] = 118; array2[25] = 131; array2[26] = 136; array2[26] = 102; array2[26] = 121; array2[27] = 150; array2[27] = 84; array2[27] = 102; array2[27] = 10; array2[28] = 141; array2[28] = 104; array2[28] = 120; array2[28] = 117; array2[29] = 145; array2[29] = 144; array2[29] = 85; array2[29] = 7; array2[30] = 84; array2[30] = 178; array2[30] = 157; array2[30] = 173; array2[30] = 88; array2[30] = 212; array2[31] = 75; array2[31] = 153; array2[31] = 139; byte[] rgbKey = array2; byte[] array3 = new byte[16]; array3[0] = 126; array3[0] = 121; array3[0] = 222; array3[1] = 29; array3[1] = 163; array3[1] = 167; array3[1] = 120; array3[1] = 234; array3[2] = 31; array3[2] = 60; array3[2] = 72; array3[3] = 145; array3[3] = 150; array3[3] = 247; array3[4] = 74; array3[4] = 165; array3[4] = 164; array3[5] = 117; array3[5] = 104; array3[5] = 113; array3[5] = 136; array3[5] = 224; array3[6] = 227; array3[6] = 157; array3[6] = 222; array3[6] = 166; array3[6] = 45; array3[7] = 129; array3[7] = 93; array3[7] = 118; array3[7] = 175; array3[7] = 89; array3[7] = 24; array3[8] = 103; array3[8] = 136; array3[8] = 170; array3[8] = 142; array3[9] = 156; array3[9] = 85; array3[9] = 55; array3[9] = 167; array3[9] = 196; array3[9] = 179; array3[10] = 104; array3[10] = 92; array3[10] = 147; array3[10] = 85; array3[10] = 219; array3[11] = 170; array3[11] = 192; array3[11] = 121; array3[11] = 140; array3[11] = 27; array3[12] = 122; array3[12] = 94; array3[12] = 108; array3[12] = 155; array3[13] = 75; array3[13] = 122; array3[13] = 49; array3[13] = 86; array3[13] = 120; array3[13] = 112; array3[14] = 156; array3[14] = 126; array3[14] = 90; array3[14] = 153; array3[14] = 170; array3[14] = 100; array3[15] = 205; array3[15] = 156; array3[15] = 212; array3[15] = 112; array3[15] = 136; byte[] array4 = array3; byte[] publicKeyToken = typeof(Class14).Assembly.GetName().GetPublicKeyToken(); if (publicKeyToken != null && publicKeyToken.Length > 0) { array4[1] = publicKeyToken[0]; array4[3] = publicKeyToken[1]; array4[5] = publicKeyToken[2]; array4[7] = publicKeyToken[3]; array4[9] = publicKeyToken[4]; array4[11] = publicKeyToken[5]; array4[13] = publicKeyToken[6]; array4[15] = publicKeyToken[7]; } ICryptoTransform transform = new RijndaelManaged { Mode = CipherMode.CBC }.CreateDecryptor(rgbKey, array4); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write); cryptoStream.Write(array, 0, array.Length); cryptoStream.FlushFinalBlock(); Class14.byte_2 = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); binaryReader.Close(); } int num = BitConverter.ToInt32(Class14.byte_2, int_3); try { byte[] array5 = new byte[num]; Array.Copy(Class14.byte_2, int_3 + 4, array5, 0, num); return(Encoding.Unicode.GetString(array5, 0, array5.Length)); } catch { } return(""); }
internal static string smethod_11(int int_5) { if (Class2.byte_2.Length == 0) { BinaryReader binaryReader = new BinaryReader(Class2.JhHvOiKbi.GetManifestResourceStream("DJucFXL0oclpIZNx7I.loluK2421PM52EkXJW")); binaryReader.BaseStream.Position = 0L; byte[] array = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length); binaryReader.Close(); byte[] array2 = new byte[32]; array2[0] = 102; array2[0] = 128; array2[0] = 177; array2[0] = 147; array2[0] = 230; array2[1] = 108; array2[1] = 162; array2[1] = 131; array2[1] = 157; array2[2] = 108; array2[2] = 97; array2[2] = 226; array2[3] = 121; array2[3] = 132; array2[3] = 150; array2[3] = 136; array2[4] = 164; array2[4] = 154; array2[4] = 204; array2[4] = 122; array2[4] = 193; array2[5] = 122; array2[5] = 107; array2[5] = 16; array2[5] = 248; array2[6] = 127; array2[6] = 86; array2[6] = 123; array2[6] = 121; array2[6] = 157; array2[6] = 82; array2[7] = 164; array2[7] = 148; array2[7] = 197; array2[8] = 125; array2[8] = 100; array2[8] = 20; array2[9] = 116; array2[9] = 107; array2[9] = 178; array2[10] = 99; array2[10] = 164; array2[10] = 99; array2[10] = 96; array2[10] = 234; array2[11] = 114; array2[11] = 131; array2[11] = 96; array2[11] = 46; array2[12] = 140; array2[12] = 166; array2[12] = 44; array2[12] = 120; array2[12] = 113; array2[12] = 197; array2[13] = 97; array2[13] = 133; array2[13] = 158; array2[13] = 112; array2[13] = 74; array2[13] = 150; array2[14] = 150; array2[14] = 135; array2[14] = 28; array2[14] = 115; array2[14] = 121; array2[14] = 246; array2[15] = 166; array2[15] = 155; array2[15] = 118; array2[15] = 209; array2[16] = 168; array2[16] = 151; array2[16] = 81; array2[17] = 117; array2[17] = 103; array2[17] = 119; array2[17] = 98; array2[17] = 132; array2[17] = 168; array2[18] = 94; array2[18] = 72; array2[18] = 150; array2[18] = 84; array2[18] = 134; array2[18] = 192; array2[19] = 68; array2[19] = 94; array2[19] = 85; array2[19] = 137; array2[19] = 125; array2[19] = 95; array2[20] = 92; array2[20] = 140; array2[20] = 157; array2[20] = 138; array2[21] = 132; array2[21] = 126; array2[21] = 124; array2[21] = 39; array2[22] = 231; array2[22] = 147; array2[22] = 44; array2[23] = 146; array2[23] = 138; array2[23] = 163; array2[23] = 11; array2[23] = 158; array2[23] = 185; array2[24] = 169; array2[24] = 152; array2[24] = 94; array2[24] = 160; array2[25] = 143; array2[25] = 158; array2[25] = 165; array2[25] = 244; array2[26] = 105; array2[26] = 94; array2[26] = 202; array2[27] = 165; array2[27] = 27; array2[27] = 33; array2[27] = 45; array2[28] = 100; array2[28] = 223; array2[28] = 232; array2[29] = 131; array2[29] = 102; array2[29] = 148; array2[29] = 94; array2[30] = 154; array2[30] = 139; array2[30] = 136; array2[30] = 95; array2[30] = 152; array2[31] = 124; array2[31] = 123; array2[31] = 10; array2[31] = 91; array2[31] = 101; array2[31] = 201; byte[] array3 = array2; byte[] array4 = new byte[16]; array4[0] = 102; array4[0] = 96; array4[0] = 142; array4[0] = 79; array4[1] = 156; array4[1] = 88; array4[1] = 230; array4[1] = 176; array4[1] = 74; array4[1] = 219; array4[2] = 95; array4[2] = 59; array4[2] = 132; array4[2] = 53; array4[3] = 125; array4[3] = 235; array4[3] = 145; array4[4] = 161; array4[4] = 163; array4[4] = 122; array4[4] = 5; array4[5] = 134; array4[5] = 90; array4[5] = 138; array4[6] = 100; array4[6] = 108; array4[6] = 130; array4[6] = 91; array4[7] = 157; array4[7] = 210; array4[7] = 114; array4[7] = 125; array4[7] = 110; array4[7] = 67; array4[8] = 90; array4[8] = 107; array4[8] = 134; array4[8] = 54; array4[8] = 216; array4[9] = 89; array4[9] = 144; array4[9] = 135; array4[9] = 203; array4[10] = 108; array4[10] = 133; array4[10] = 106; array4[11] = 100; array4[11] = 119; array4[11] = 241; array4[12] = 120; array4[12] = 123; array4[12] = 161; array4[12] = 38; array4[12] = 49; array4[13] = 125; array4[13] = 69; array4[13] = 96; array4[13] = 95; array4[13] = 119; array4[13] = 170; array4[14] = 28; array4[14] = 90; array4[14] = 23; array4[14] = 156; array4[15] = 117; array4[15] = 106; array4[15] = 90; byte[] array5 = array4; Array.Reverse(array5); byte[] publicKeyToken = Class2.JhHvOiKbi.GetName().GetPublicKeyToken(); if (publicKeyToken != null && publicKeyToken.Length > 0) { array5[1] = publicKeyToken[0]; array5[3] = publicKeyToken[1]; array5[5] = publicKeyToken[2]; array5[7] = publicKeyToken[3]; array5[9] = publicKeyToken[4]; array5[11] = publicKeyToken[5]; array5[13] = publicKeyToken[6]; array5[15] = publicKeyToken[7]; } for (int i = 0; i < array5.Length; i++) { array3[i] ^= array5[i]; } if (int_5 == -1) { SymmetricAlgorithm symmetricAlgorithm = Class2.smethod_7(); symmetricAlgorithm.Mode = CipherMode.CBC; ICryptoTransform transform = symmetricAlgorithm.CreateDecryptor(array3, array5); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write); cryptoStream.Write(array, 0, array.Length); cryptoStream.FlushFinalBlock(); Class2.byte_2 = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); array = Class2.byte_2; } int num = array.Length % 4; int num2 = array.Length / 4; byte[] array6 = new byte[array.Length]; int num3 = array3.Length / 4; uint num4 = 0u; if (num > 0) { num2++; } for (int j = 0; j < num2; j++) { int num5 = j % num3; int num6 = j * 4; uint num7 = (uint)(num5 * 4); uint num8 = (uint)((int)array3[(int)((UIntPtr)(num7 + 3u))] << 24 | (int)array3[(int)((UIntPtr)(num7 + 2u))] << 16 | (int)array3[(int)((UIntPtr)(num7 + 1u))] << 8 | (int)array3[(int)((UIntPtr)num7)]); uint num9 = 255u; int num10 = 0; uint num11; if (j == num2 - 1 && num > 0) { num11 = 0u; num4 += num8; for (int k = 0; k < num; k++) { if (k > 0) { num11 <<= 8; } num11 |= (uint)array[array.Length - (1 + k)]; } } else { num4 += num8; num7 = (uint)num6; num11 = (uint)((int)array[(int)((UIntPtr)(num7 + 3u))] << 24 | (int)array[(int)((UIntPtr)(num7 + 2u))] << 16 | (int)array[(int)((UIntPtr)(num7 + 1u))] << 8 | (int)array[(int)((UIntPtr)num7)]); } uint num12 = num4; uint num13 = num12; uint num14 = num12; uint num15 = 1117540173u; uint num16 = 2053035004u; uint num17 = 236713647u; uint num18 = 476602603u; uint num19 = 3769154997u; if (1117540173 == 0.0) { num15 -= 1u; } uint num20 = (uint)((double)((short)num16) / num15 + num15); num15 = (uint)(27282u * num20 + 809622430.0); num14 ^= num14 >> 5; num14 += num18; num14 ^= num14 >> 12; num14 += num19; num14 ^= num14 << 21; num14 += num15; num14 = ((num18 << 9) + num17 ^ num18) + num14; num12 = num13 + (uint)num14; num4 = num12; if (j == num2 - 1 && num > 0) { uint num21 = num4 ^ num11; for (int l = 0; l < num; l++) { if (l > 0) { num9 <<= 8; num10 += 8; } array6[num6 + l] = (byte)((num21 & num9) >> num10); } } else { uint num22 = num4 ^ num11; array6[num6] = (byte)(num22 & 255u); array6[num6 + 1] = (byte)((num22 & 65280u) >> 8); array6[num6 + 2] = (byte)((num22 & 16711680u) >> 16); array6[num6 + 3] = (byte)((num22 & 4278190080u) >> 24); } } Class2.byte_2 = array6; } int count = BitConverter.ToInt32(Class2.byte_2, int_5); try { return(Encoding.Unicode.GetString(Class2.byte_2, int_5 + 4, count)); } catch { } return(""); }
// Encrypt a file using a public key. private static void EncryptFile(string inFile, RSACryptoServiceProvider rsaPublicKey) { using (AesManaged aesManaged = new AesManaged()) { // Create instance of AesManaged for // symetric encryption of the data. aesManaged.KeySize = 256; aesManaged.BlockSize = 128; aesManaged.Mode = CipherMode.CBC; using (ICryptoTransform transform = aesManaged.CreateEncryptor()) { RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey); byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType()); // Create byte arrays to contain // the length values of the key and IV. byte[] LenK = new byte[4]; byte[] LenIV = new byte[4]; int lKey = keyEncrypted.Length; LenK = BitConverter.GetBytes(lKey); int lIV = aesManaged.IV.Length; LenIV = BitConverter.GetBytes(lIV); // Write the following to the FileStream // for the encrypted file (outFs): // - length of the key // - length of the IV // - ecrypted key // - the IV // - the encrypted cipher content int startFileName = inFile.LastIndexOf("\\") + 1; // Change the file's extension to ".enc" string outFile = encrFolder + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc"; Directory.CreateDirectory(encrFolder); using (FileStream outFs = new FileStream(outFile, FileMode.Create)) { outFs.Write(LenK, 0, 4); outFs.Write(LenIV, 0, 4); outFs.Write(keyEncrypted, 0, lKey); outFs.Write(aesManaged.IV, 0, lIV); // Now write the cipher text using // a CryptoStream for encrypting. using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write)) { // By encrypting a chunk at // a time, you can save memory // and accommodate large files. int count = 0; int offset = 0; // blockSizeBytes can be any arbitrary size. int blockSizeBytes = aesManaged.BlockSize / 8; byte[] data = new byte[blockSizeBytes]; int bytesRead = 0; using (FileStream inFs = new FileStream(inFile, FileMode.Open)) { do { count = inFs.Read(data, 0, blockSizeBytes); offset += count; outStreamEncrypted.Write(data, 0, count); bytesRead += blockSizeBytes; }while (count > 0); inFs.Close(); } outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } outFs.Close(); } } } }
public static PTable FromMemtable(IMemTable table, string filename, int cacheDepth = 16, bool skipIndexVerify = false) { Ensure.NotNull(table, "table"); Ensure.NotNullOrEmpty(filename, "filename"); Ensure.Nonnegative(cacheDepth, "cacheDepth"); int indexEntrySize = GetIndexEntrySize(table.Version); long dumpedEntryCount = 0; var sw = Stopwatch.StartNew(); using (var fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.None, DefaultSequentialBufferSize, FileOptions.SequentialScan)) { var fileSize = GetFileSizeUpToIndexEntries(table.Count, table.Version); fs.SetLength(fileSize); fs.Seek(0, SeekOrigin.Begin); using (var md5 = MD5.Create()) using (var cs = new CryptoStream(fs, md5, CryptoStreamMode.Write)) using (var bs = new BufferedStream(cs, DefaultSequentialBufferSize)) { // WRITE HEADER var headerBytes = new PTableHeader(table.Version).AsByteArray(); cs.Write(headerBytes, 0, headerBytes.Length); // WRITE INDEX ENTRIES var buffer = new byte[indexEntrySize]; var records = table.IterateAllInOrder(); List <Midpoint> midpoints = new List <Midpoint>(); var requiredMidpointCount = GetRequiredMidpointCountCached(table.Count, table.Version, cacheDepth); long indexEntry = 0L; foreach (var rec in records) { AppendRecordTo(bs, buffer, table.Version, rec, indexEntrySize); dumpedEntryCount += 1; if (table.Version >= PTableVersions.IndexV4 && IsMidpointIndex(indexEntry, table.Count, requiredMidpointCount)) { midpoints.Add(new Midpoint(new IndexEntryKey(rec.Stream, rec.Version), indexEntry)); } indexEntry++; } //WRITE MIDPOINTS if (table.Version >= PTableVersions.IndexV4) { var numIndexEntries = table.Count; if (dumpedEntryCount != numIndexEntries) { //if index entries have been removed, compute the midpoints again numIndexEntries = dumpedEntryCount; requiredMidpointCount = GetRequiredMidpointCount(numIndexEntries, table.Version, cacheDepth); midpoints = ComputeMidpoints(bs, fs, table.Version, indexEntrySize, numIndexEntries, requiredMidpointCount, midpoints); } WriteMidpointsTo(bs, fs, table.Version, indexEntrySize, buffer, dumpedEntryCount, numIndexEntries, requiredMidpointCount, midpoints); } bs.Flush(); cs.FlushFinalBlock(); // WRITE MD5 var hash = md5.Hash; fs.SetLength(fs.Position + MD5Size); fs.Write(hash, 0, hash.Length); fs.FlushToDisk(); } } Log.Trace("Dumped MemTable [{0}, {1} entries] in {2}.", table.Id, table.Count, sw.Elapsed); return(new PTable(filename, table.Id, depth: cacheDepth, skipIndexVerify: skipIndexVerify)); }
public static Stream Create(Stream originalStream, string sharedSecret, string salt, bool leaveOpen) { var pipeOptions = new PipedStreamOptions() { WriteTimeout = TimeSpan.FromMinutes(10) }; var pipe = new PipedStreamManager(pipeOptions); var saltBytes = Encoding.UTF8.GetBytes(salt); var encryptorTask = Task.Run(async() => { try { using (var writerStream = pipe.CreateWriter(throwsFailedWrite: true)) using (var aesAlg = new RijndaelManaged()) using (var key = new Rfc2898DeriveBytes(sharedSecret, saltBytes)) { try { aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); // prepends the IV await writerStream.WriteAsync(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)) .IgnoreContext(); await writerStream.WriteAsync(aesAlg.IV, 0, aesAlg.IV.Length) .IgnoreContext(); // Creates an encryptor to perform the stream transform. using (var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)) using (var cryptoStream = new CryptoStream(writerStream, encryptor, CryptoStreamMode.Write)) { await originalStream.CopyToAsync(cryptoStream, bufferSize: pipeOptions.BlockSize) .IgnoreContext(); await cryptoStream.FlushAsync() .IgnoreContext(); await writerStream.FlushAsync() .IgnoreContext(); if (!cryptoStream.HasFlushedFinalBlock) { cryptoStream.FlushFinalBlock(); } await writerStream.FlushAsync() .IgnoreContext(); } } catch (Exception ex) { pipe.FaultPipe(ex); } } } finally { if (!leaveOpen) { originalStream.Dispose(); } } }); return(ReadOnlyStreamWrapper.Create(pipe.CreateReader(), onDisposingAction: (Stream s) => s?.Dispose())); }
public static string CreateEncryptedJweToken(JsonObject jwtPayload, RSAParameters publicKey) { //From: http://self-issued.info/docs/draft-ietf-jose-json-web-encryption-09.html#RSACBCExample var jweHeader = new JsonObject { { "alg", "RSA-OAEP" }, { "enc", "A128CBC-HS256" }, { "kid", Convert.ToBase64String(publicKey.Modulus).Substring(0, 3) }, }; var jweHeaderBase64Url = jweHeader.ToJson().ToUtf8Bytes().ToBase64UrlSafe(); var authKey = new byte[128 / 8]; var cryptKey = new byte[128 / 8]; var cryptAuthKeys256 = AesUtils.CreateKey(); Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length); Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length); var aes = Aes.Create(); aes.KeySize = 128; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; using (aes) { aes.GenerateIV(); var iv = aes.IV; aes.Key = cryptKey; var jweEncKey = RsaUtils.Encrypt(cryptAuthKeys256, publicKey, UseRsaKeyLength); var jweEncKeyBase64Url = jweEncKey.ToBase64UrlSafe(); var ivBase64Url = iv.ToBase64UrlSafe(); var aad = jweHeaderBase64Url + "." + jweEncKeyBase64Url; var aadBytes = aad.ToUtf8Bytes(); var payloadBytes = jwtPayload.ToJson().ToUtf8Bytes(); using (var cipherStream = MemoryStreamFactory.GetStream()) using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) using (var writer = new BinaryWriter(cryptoStream)) { writer.Write(payloadBytes); cryptoStream.FlushFinalBlock(); using (var hmac = new HMACSHA256(authKey)) using (var encryptedStream = MemoryStreamFactory.GetStream()) using (var bw = new BinaryWriter(encryptedStream)) { bw.Write(aadBytes); bw.Write(iv); bw.Write(cipherStream.GetBuffer(), 0, (int)cipherStream.Length); bw.Flush(); var tag = hmac.ComputeHash(encryptedStream.GetBuffer(), 0, (int)encryptedStream.Length); var cipherTextBase64Url = cipherStream.ToBase64UrlSafe(); var tagBase64Url = tag.ToBase64UrlSafe(); var jweToken = jweHeaderBase64Url + "." + jweEncKeyBase64Url + "." + ivBase64Url + "." + cipherTextBase64Url + "." + tagBase64Url; return(jweToken); } } } }
public static PTable MergeTo(IList <PTable> tables, string outputFile, Func <string, ulong, ulong> upgradeHash, Func <IndexEntry, bool> existsAt, Func <IndexEntry, Tuple <string, bool> > readRecord, byte version, int cacheDepth = 16) { Ensure.NotNull(tables, "tables"); Ensure.NotNullOrEmpty(outputFile, "outputFile"); Ensure.Nonnegative(cacheDepth, "cacheDepth"); var indexEntrySize = GetIndexEntrySize(version); var fileSize = GetFileSize(tables, indexEntrySize); // approximate file size if (tables.Count == 2) { return(MergeTo2(tables, fileSize, indexEntrySize, outputFile, upgradeHash, existsAt, readRecord, version, cacheDepth)); // special case } Log.Trace("PTables merge started."); var watch = Stopwatch.StartNew(); var enumerators = tables.Select(table => new EnumerableTable(version, table, upgradeHash, existsAt, readRecord)).ToList(); for (int i = 0; i < enumerators.Count; i++) { if (!enumerators[i].MoveNext()) { enumerators[i].Dispose(); enumerators.RemoveAt(i); i--; } } long dumpedEntryCount = 0; using (var f = new FileStream(outputFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, DefaultSequentialBufferSize, FileOptions.SequentialScan)) { f.SetLength(fileSize); f.Seek(0, SeekOrigin.Begin); using (var md5 = MD5.Create()) using (var cs = new CryptoStream(f, md5, CryptoStreamMode.Write)) using (var bs = new BufferedStream(cs, DefaultSequentialBufferSize)) { // WRITE HEADER var headerBytes = new PTableHeader(version).AsByteArray(); cs.Write(headerBytes, 0, headerBytes.Length); var buffer = new byte[indexEntrySize]; // WRITE INDEX ENTRIES while (enumerators.Count > 0) { var idx = GetMaxOf(enumerators); var current = enumerators[idx].Current; if (existsAt(current)) { AppendRecordTo(bs, buffer, version, current, indexEntrySize); dumpedEntryCount += 1; } if (!enumerators[idx].MoveNext()) { enumerators[idx].Dispose(); enumerators.RemoveAt(idx); } } bs.Flush(); cs.FlushFinalBlock(); f.FlushToDisk(); f.SetLength(f.Position + MD5Size); // WRITE MD5 var hash = md5.Hash; f.Write(hash, 0, hash.Length); f.FlushToDisk(); } } Log.Trace("PTables merge finished in {0} ([{1}] entries merged into {2}).", watch.Elapsed, string.Join(", ", tables.Select(x => x.Count)), dumpedEntryCount); return(new PTable(outputFile, Guid.NewGuid(), depth: cacheDepth)); }
private bool EmpLogin(string _UserName, string _Password) { Sb = new StringBuilder(); Sb.Append("SELECT E.Employee_ID,U.User_Password,E.Employee_FirstName,E.Employee_LastName"); Sb.Append(" FROM Employee E"); Sb.Append(" INNER JOIN User_Login U ON E.Employee_ID = U.User_ID "); Sb.Append(" WHERE (U.User_ID=@UserName)"); Sb.Append(" AND (U.User_Password=@Password)"); string sqlLogin; sqlLogin = Sb.ToString(); byte[] CurrentIV = new byte[] { 51, 52, 53, 54, 55, 56, 57, 58 }; byte[] CurrentKey = { }; if (_UserName.Length == 8) { CurrentKey = Encoding.ASCII.GetBytes(_UserName); } else if (_UserName.Length > 8) { CurrentKey = Encoding.ASCII.GetBytes(_UserName.Substring(0, 8)); } else { string AddString = _UserName.Substring(0, 1); int TotalLoop = 8 - Convert.ToInt32(_UserName.Length); string tmpKey = _UserName; for (int i = 1; i <= TotalLoop; i++) { tmpKey = tmpKey + AddString; } CurrentKey = Encoding.ASCII.GetBytes(tmpKey); } desCrypt = new DESCryptoServiceProvider(); desCrypt.IV = CurrentIV; desCrypt.Key = CurrentKey; ms = new MemoryStream(); ms.Position = 0; ICryptoTransform ce = desCrypt.CreateEncryptor(); cs = new CryptoStream(ms, ce, CryptoStreamMode.Write); byte[] arrByte = Encoding.ASCII.GetBytes(_Password); cs.Write(arrByte, 0, arrByte.Length); cs.FlushFinalBlock(); cs.Close(); PwdWithEncrypt = Convert.ToBase64String(ms.ToArray()); Cmd = new SqlCommand(); Cmd.CommandText = sqlLogin; Cmd.CommandType = CommandType.Text; Cmd.Connection = Conn; Cmd.Parameters.Clear(); Cmd.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = _UserName; Cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = PwdWithEncrypt; Sdr = Cmd.ExecuteReader(); if (Sdr.HasRows) { Sdr.Read(); //CurrentAuthentication = Sdr.GetString(Sdr.GetOrdinal("Auth")); // string UserName = dr.GetString(dr.GetOrdinal("UserId")); string UserName = Sdr.GetString(Sdr.GetOrdinal("Employee_ID")); string SureName = Sdr.GetString(Sdr.GetOrdinal("Employee_FirstName")); string LastName = Sdr.GetString(Sdr.GetOrdinal("Employee_LastName")); DBConnString.sUserIdLogin = UserName; DBConnString.sUserlogin = SureName + " " + LastName; return(true); } else { Sdr.Close(); return(false); } }
/// <summary> /// Encrypts a file using AES 256 and saves it. /// </summary> /// <param name="originalFilePath">The file to be encrypted.</param> /// <param name="newFilePath">The location where the resulting file has to be saved.</param> /// <param name="password">The password to use for the encryption.</param> /// <param name="salt"></param> public static CryptographicOperationResult EncryptFileToFile(string originalFilePath, string newFilePath, string password, Encoding encoding, string salt = "asdk23904uasdfji", byte[] initVector = null) //do not remove the preset salt string or some functions used in other applications might stop working { if (string.IsNullOrEmpty(password)) { return new CryptographicOperationResult() { IsSuccessful = false, IsPasswordWrong = true } } ; if (initVector == null) { initVector = INIT_VECTOR; } SecureString securePwd = new SecureString(); foreach (char c in password) { securePwd.AppendChar(c); } securePwd.MakeReadOnly(); byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt); byte[] plainTextBytes = null; //read file using (StreamReader sr = new StreamReader(originalFilePath)) { try { plainTextBytes = Encoding.Default.GetBytes(sr.ReadToEnd()); } catch (Exception e) { Logger.AddLogEntry(Logger.LogEntryCategories.Error, "Exception while encrypting file '" + originalFilePath + "' to file '" + newFilePath + "'.", e, "Security"); return(new CryptographicOperationResult() { IsSuccessful = false, IsSourceFaulty = true, Exception = e, Password = securePwd }); } } if (plainTextBytes == null) { return new CryptographicOperationResult() { IsSuccessful = false, IsPasswordWrong = false, Password = securePwd } } ; Rfc2898DeriveBytes passwordBytes = new Rfc2898DeriveBytes(password, saltValueBytes, 1000); byte[] keyBytes = passwordBytes.GetBytes(256 / 8); RijndaelManaged symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVector); byte[] cipherTextBytes; try { //define memory stream which will be used to hold the encrypted data using (MemoryStream memoryStream = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); } } catch (Exception ex) { return(new CryptographicOperationResult() { IsSuccessful = false, Exception = ex, Password = securePwd }); } try { //convert the encrypted data into a base64-encoded string string cipherText = Convert.ToBase64String(cipherTextBytes); using (StreamWriter sw = new StreamWriter(newFilePath, false, encoding)) { sw.Write(cipherText); } return(new CryptographicOperationResult() { IsSuccessful = true, Password = securePwd }); } catch (Exception ex) { return(new CryptographicOperationResult() { IsSuccessful = false, IsTargetFaulty = true, Exception = ex, Password = securePwd }); } }
private static PTable MergeTo2(IList <PTable> tables, long fileSize, int indexEntrySize, string outputFile, Func <string, ulong, ulong> upgradeHash, Func <IndexEntry, bool> existsAt, Func <IndexEntry, Tuple <string, bool> > readRecord, byte version, int cacheDepth) { Log.Trace("PTables merge started (specialized for <= 2 tables)."); var watch = Stopwatch.StartNew(); var enumerators = tables.Select(table => new EnumerableTable(version, table, upgradeHash, existsAt, readRecord)).ToList(); long dumpedEntryCount = 0; using (var f = new FileStream(outputFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, DefaultSequentialBufferSize, FileOptions.SequentialScan)) { f.SetLength(fileSize); f.Seek(0, SeekOrigin.Begin); using (var md5 = MD5.Create()) using (var cs = new CryptoStream(f, md5, CryptoStreamMode.Write)) using (var bs = new BufferedStream(cs, DefaultSequentialBufferSize)) { // WRITE HEADER var headerBytes = new PTableHeader(version).AsByteArray(); cs.Write(headerBytes, 0, headerBytes.Length); // WRITE INDEX ENTRIES var buffer = new byte[indexEntrySize]; var enum1 = enumerators[0]; var enum2 = enumerators[1]; bool available1 = enum1.MoveNext(); bool available2 = enum2.MoveNext(); IndexEntry current; while (available1 || available2) { var entry1 = new IndexEntry(enum1.Current.Stream, enum1.Current.Version, enum1.Current.Position); var entry2 = new IndexEntry(enum2.Current.Stream, enum2.Current.Version, enum2.Current.Position); if (available1 && (!available2 || entry1.CompareTo(entry2) > 0)) { current = entry1; available1 = enum1.MoveNext(); } else { current = entry2; available2 = enum2.MoveNext(); } if (existsAt(current)) { AppendRecordTo(bs, buffer, version, current, indexEntrySize); dumpedEntryCount += 1; } } bs.Flush(); cs.FlushFinalBlock(); f.SetLength(f.Position + MD5Size); // WRITE MD5 var hash = md5.Hash; f.Write(hash, 0, hash.Length); f.FlushToDisk(); } } Log.Trace("PTables merge finished in {0} ([{1}] entries merged into {2}).", watch.Elapsed, string.Join(", ", tables.Select(x => x.Count)), dumpedEntryCount); return(new PTable(outputFile, Guid.NewGuid(), version, depth: cacheDepth)); }
private static byte[] GetCmac(Span <byte> data, byte[] omacKey, bool truncate = true) { if (omacKey?.Length != 0x10) { throw new ArgumentException(nameof(omacKey)); } byte[] AESEncrypt(byte[] key, byte[] iv, Span <byte> dataToEncrypt) { using (var result = new MemoryStream()) using (var aes = Aes.Create()) { aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; using (var cs = new CryptoStream(result, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write)) { cs.Write(dataToEncrypt); cs.FlushFinalBlock(); return(result.ToArray()); } } } byte[] Rol(byte[] b) { var r = new byte[b.Length]; byte carry = 0; for (var i = b.Length - 1; i >= 0; i--) { ushort u = (ushort)(b[i] << 1); r[i] = (byte)((u & 0xff) + carry); carry = (byte)((u & 0xff00) >> 8); } return(r); } // SubKey generation // step 1, AES-128 with key K is applied to an all-zero input block. byte[] derivedKey = AESEncrypt(omacKey, new byte[16], new byte[16]); // step 2, K1 is derived through the following operation: byte[] subKey1 = Rol(derivedKey); //If the most significant bit of L is equal to 0, K1 is the left-shift of L by 1 bit. if ((derivedKey[0] & 0x80) == 0x80) { subKey1[15] ^= 0x87; // Otherwise, K1 is the exclusive-OR of const_Rb and the left-shift of L by 1 bit. } // step 3, K2 is derived through the following operation: byte[] subKey2 = Rol(subKey1); // If the most significant bit of K1 is equal to 0, K2 is the left-shift of K1 by 1 bit. if ((subKey1[0] & 0x80) == 0x80) { subKey2[15] ^= 0x87; // Otherwise, K2 is the exclusive-OR of const_Rb and the left-shift of K1 by 1 bit. } // MAC computing byte[] buf; if ((data.Length != 0) && (data.Length % 16 == 0)) { // If the size of the input message block is equal to a positive multiple of the block size (namely, 128 bits), // the last block shall be exclusive-OR'ed with K1 before processing buf = new byte[data.Length]; Buffer.BlockCopy(data.ToArray(), 0, buf, 0, data.Length - 16); for (var j = 0; j < subKey1.Length; j++) { var idx = data.Length - 16 + j; buf[idx] = (byte)(data[idx] ^ subKey1[j]); } } else { // Otherwise, the last block shall be padded with 10^i var paddingLength = 16 - data.Length % 16; buf = new byte[data.Length + paddingLength]; Buffer.BlockCopy(data.ToArray(), 0, buf, 0, data.Length); buf[data.Length] = 0x80; // and exclusive-OR'ed with K2 for (int j = 0; j < subKey2.Length; j++) { buf[buf.Length - 16 + j] ^= subKey2[j]; } } // The result of the previous process will be the input of the last encryption. byte[] encResult = AESEncrypt(omacKey, new byte[16], buf); if (truncate) { return(encResult.AsSpan(encResult.Length - 16, 16).ToArray()); } else { return(encResult.AsSpan(encResult.Length - 0x14, 0x14).ToArray()); } }
public static PTable MergeTo(IList <PTable> tables, string outputFile, Func <string, ulong, ulong> upgradeHash, Func <IndexEntry, bool> existsAt, Func <IndexEntry, Tuple <string, bool> > readRecord, byte version, int cacheDepth = 16, bool skipIndexVerify = false) { Ensure.NotNull(tables, "tables"); Ensure.NotNullOrEmpty(outputFile, "outputFile"); Ensure.Nonnegative(cacheDepth, "cacheDepth"); var indexEntrySize = GetIndexEntrySize(version); long numIndexEntries = 0; for (var i = 0; i < tables.Count; i++) { numIndexEntries += tables[i].Count; } var fileSizeUpToIndexEntries = GetFileSizeUpToIndexEntries(numIndexEntries, version); if (tables.Count == 2) { return(MergeTo2(tables, numIndexEntries, indexEntrySize, outputFile, upgradeHash, existsAt, readRecord, version, cacheDepth, skipIndexVerify)); // special case } Log.Trace("PTables merge started."); var watch = Stopwatch.StartNew(); var enumerators = tables.Select(table => new EnumerableTable(version, table, upgradeHash, existsAt, readRecord)).ToList(); try { for (int i = 0; i < enumerators.Count; i++) { if (!enumerators[i].MoveNext()) { enumerators[i].Dispose(); enumerators.RemoveAt(i); i--; } } long dumpedEntryCount = 0; using (var f = new FileStream(outputFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, DefaultSequentialBufferSize, FileOptions.SequentialScan)) { f.SetLength(fileSizeUpToIndexEntries); f.Seek(0, SeekOrigin.Begin); using (var md5 = MD5.Create()) using (var cs = new CryptoStream(f, md5, CryptoStreamMode.Write)) using (var bs = new BufferedStream(cs, DefaultSequentialBufferSize)) { // WRITE HEADER var headerBytes = new PTableHeader(version).AsByteArray(); cs.Write(headerBytes, 0, headerBytes.Length); var buffer = new byte[indexEntrySize]; long indexEntry = 0L; List <Midpoint> midpoints = new List <Midpoint>(); var requiredMidpointCount = GetRequiredMidpointCountCached(numIndexEntries, version, cacheDepth); // WRITE INDEX ENTRIES while (enumerators.Count > 0) { var idx = GetMaxOf(enumerators); var current = enumerators[idx].Current; AppendRecordTo(bs, buffer, version, current, indexEntrySize); if (version >= PTableVersions.IndexV4 && IsMidpointIndex(indexEntry, numIndexEntries, requiredMidpointCount)) { midpoints.Add(new Midpoint(new IndexEntryKey(current.Stream, current.Version), indexEntry)); } indexEntry++; dumpedEntryCount++; if (!enumerators[idx].MoveNext()) { enumerators[idx].Dispose(); enumerators.RemoveAt(idx); } } //WRITE MIDPOINTS if (version >= PTableVersions.IndexV4) { if (dumpedEntryCount != numIndexEntries) { //if index entries have been removed, compute the midpoints again numIndexEntries = dumpedEntryCount; requiredMidpointCount = GetRequiredMidpointCount(numIndexEntries, version, cacheDepth); midpoints = ComputeMidpoints(bs, f, version, indexEntrySize, numIndexEntries, requiredMidpointCount, midpoints); } WriteMidpointsTo(bs, f, version, indexEntrySize, buffer, dumpedEntryCount, numIndexEntries, requiredMidpointCount, midpoints); } bs.Flush(); cs.FlushFinalBlock(); f.FlushToDisk(); f.SetLength(f.Position + MD5Size); // WRITE MD5 var hash = md5.Hash; f.Write(hash, 0, hash.Length); f.FlushToDisk(); } } Log.Trace("PTables merge finished in {0} ([{1}] entries merged into {2}).", watch.Elapsed, string.Join(", ", tables.Select(x => x.Count)), dumpedEntryCount); return(new PTable(outputFile, Guid.NewGuid(), depth: cacheDepth, skipIndexVerify: skipIndexVerify)); } finally { foreach (var enumerableTable in enumerators) { enumerableTable.Dispose(); } } }
/// <summary> /// A helper function to convert an unencrypted HotDocs package stream to an encrypted HotDocs package stream. /// </summary> /// <param name="ms">The unencrypted HotDocs package file/stream.</param> /// <param name="rsaParamsXml">RSA key serialized to XML.</param> /// <returns>If rsaParamsXml is null or empty, the input stream ms is simply returned. Otherwise, the input stream ms is being copied and encrypted to the returned output stream. The output stream will contain a 4 byte signature at the beginning identifying it as a HotDocs package followed by encrypted AES keys and the encrypted data.</returns> public static MemoryStream Encrypt(MemoryStream ms, string rsaParamsXml) { byte[] encryptedAesKey; byte[] decryptedAesKey; byte[] encryptedAesIV; byte[] decryptedAesIV; MemoryStream s; // if (string.IsNullOrEmpty(rsaParamsXml)) { return(ms); } s = new MemoryStream(); using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { aes.GenerateKey(); decryptedAesKey = aes.Key; aes.GenerateIV(); decryptedAesIV = aes.IV; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(rsaParamsXml); encryptedAesKey = rsa.Encrypt(decryptedAesKey, false); encryptedAesIV = rsa.Encrypt(decryptedAesIV, false); } s.Write(HDSig, 0, 4); s.WriteByte(0); // Version number s.WriteByte((byte)encryptedAesKey.Length); s.Write(encryptedAesKey, 0, encryptedAesKey.Length); s.WriteByte((byte)encryptedAesIV.Length); s.Write(encryptedAesIV, 0, encryptedAesIV.Length); MemoryStream temps = new MemoryStream(); using (CryptoStream cs = new CryptoStream(temps, aes.CreateEncryptor(), CryptoStreamMode.Write)) { ms.Position = 0; CopyStream(cs, ms); cs.FlushFinalBlock(); cs.Flush(); temps.Position = 0; CopyStream(s, temps); } } /* --- Doesn't work. RSA Encrypt function can only encrypt up to 245 bytes! * See http://social.msdn.microsoft.com/forums/en-US/clr/thread/4e3ada0a-bcaf-4c67-bdef-a6b15f5bfdce/ * byte[] encryptedData; * byte[] decryptedData; * int len = (int)ms.Length; * using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) * { * rsa.FromXmlString(rsaParamsXml); * decryptedData = new byte[len]; * ms.Position = 0; * ms.Read(decryptedData, 0, len); * encryptedData = rsa.Encrypt(decryptedData, false); * s.Write(HDSig, 0, 4); * s.Write(encryptedData, 0, encryptedData.Length); * } */ s.Position = 0; return(s); }
public static PTable Scavenged(PTable table, string outputFile, Func <string, ulong, ulong> upgradeHash, Func <IndexEntry, bool> existsAt, Func <IndexEntry, Tuple <string, bool> > readRecord, byte version, out long spaceSaved, int cacheDepth = 16, bool skipIndexVerify = false, CancellationToken ct = default(CancellationToken)) { Ensure.NotNull(table, "table"); Ensure.NotNullOrEmpty(outputFile, "outputFile"); Ensure.Nonnegative(cacheDepth, "cacheDepth"); var indexEntrySize = GetIndexEntrySize(version); var numIndexEntries = table.Count; var fileSizeUpToIndexEntries = GetFileSizeUpToIndexEntries(numIndexEntries, version); Log.Trace("PTables scavenge started with {0} entries.", numIndexEntries); var watch = Stopwatch.StartNew(); long keptCount = 0L; long droppedCount; try { using (var f = new FileStream(outputFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, DefaultSequentialBufferSize, FileOptions.SequentialScan)) { f.SetLength(fileSizeUpToIndexEntries); f.Seek(0, SeekOrigin.Begin); using (var md5 = MD5.Create()) using (var cs = new CryptoStream(f, md5, CryptoStreamMode.Write)) using (var bs = new BufferedStream(cs, DefaultSequentialBufferSize)) { // WRITE HEADER var headerBytes = new PTableHeader(version).AsByteArray(); cs.Write(headerBytes, 0, headerBytes.Length); // WRITE SCAVENGED INDEX ENTRIES var buffer = new byte[indexEntrySize]; using (var enumerator = new EnumerableTable(version, table, upgradeHash, existsAt, readRecord)) { while (enumerator.MoveNext()) { ct.ThrowIfCancellationRequested(); if (existsAt(enumerator.Current)) { AppendRecordTo(bs, buffer, version, enumerator.Current, indexEntrySize); keptCount++; } } } // We calculate this as the EnumerableTable can silently drop entries too. droppedCount = numIndexEntries - keptCount; var forceKeep = version > table.Version; if (droppedCount == 0 && !forceKeep) { Log.Trace( "PTable scavenge finished in {0}. No entries removed so not keeping scavenged table.", watch.Elapsed); try { bs.Close(); File.Delete(outputFile); } catch (Exception ex) { Log.ErrorException(ex, "Unable to delete unwanted scavenged PTable: {0}", outputFile); } spaceSaved = 0; return(null); } if (droppedCount == 0 && forceKeep) { Log.Trace("Keeping scavenged index even though it isn't smaller; version upgraded."); } //CALCULATE AND WRITE MIDPOINTS if (version >= PTableVersions.IndexV4) { var requiredMidpointCount = GetRequiredMidpointCount(keptCount, version, cacheDepth); var midpoints = ComputeMidpoints(bs, f, version, indexEntrySize, keptCount, requiredMidpointCount, new List <Midpoint>(), ct); WriteMidpointsTo(bs, f, version, indexEntrySize, buffer, keptCount, keptCount, requiredMidpointCount, midpoints); } bs.Flush(); cs.FlushFinalBlock(); f.FlushToDisk(); f.SetLength(f.Position + MD5Size); // WRITE MD5 var hash = md5.Hash; f.Write(hash, 0, hash.Length); f.FlushToDisk(); } } Log.Trace("PTable scavenge finished in {0} ({1} entries removed, {2} remaining).", watch.Elapsed, droppedCount, keptCount); var scavengedTable = new PTable(outputFile, Guid.NewGuid(), depth: cacheDepth, skipIndexVerify: skipIndexVerify); spaceSaved = table._size - scavengedTable._size; return(scavengedTable); } catch (Exception) { try { File.Delete(outputFile); } catch (Exception ex) { Log.ErrorException(ex, "Unable to delete unwanted scavenged PTable: {0}", outputFile); } throw; } }
public static string EncryptString(string inputText, string password) { if (inputText.Length <= 0) { return(""); } // We are now going to create an instance of the // Rihndael class. RijndaelManaged RijndaelCipher = new RijndaelManaged(); //RijndaelCipher.BlockSize = 16 * 8; // First we need to turn the input strings into a byte array. byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(inputText); // We are using salt to make it harder to guess our key // using a dictionary attack. byte[] Salt = Encoding.ASCII.GetBytes(password.Length.ToString()); // The (Secret Key) will be generated from the specified // password and salt. PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(password, Salt); // Create a encryptor from the existing SecretKey value. // We use 32 value for the secret key // (the default Rijndael key length is 256 bit = 32 value) and // then 16 value for the IV (initialization vector), // (the default Rijndael IV length is 128 bit = 16 value) ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)); // Create a MemoryStream that is going to hold the encrypted value MemoryStream memoryStream = new MemoryStream(); // Create a CryptoStream through which we are going to be processing our data. // CryptoStreamMode.Write means that we are going to be writing data // to the stream and the output will be written in the MemoryStream // we have provided. (always use write mode for encryption) CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write); // Start the encryption process. cryptoStream.Write(PlainText, 0, PlainText.Length); // Finish encrypting. cryptoStream.FlushFinalBlock(); // Convert our encrypted data from a memoryStream into a byte array. byte[] CipherBytes = memoryStream.ToArray(); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert encrypted data into a base64-encoded string. // A common mistake would be to use an Encoding class for that. // It does not work, because not all byte values can be // represented by characters. We are going to be using Base64 encoding // That is designed exactly for what we are trying to do. string EncryptedData = Convert.ToBase64String(CipherBytes); // Return encrypted string. return(EncryptedData); }
private static PTable MergeTo2(IList <PTable> tables, long numIndexEntries, int indexEntrySize, string outputFile, Func <string, ulong, ulong> upgradeHash, Func <IndexEntry, bool> existsAt, Func <IndexEntry, Tuple <string, bool> > readRecord, byte version, int cacheDepth, bool skipIndexVerify) { Log.Trace("PTables merge started (specialized for <= 2 tables)."); var watch = Stopwatch.StartNew(); var fileSizeUpToIndexEntries = GetFileSizeUpToIndexEntries(numIndexEntries, version); var enumerators = tables.Select(table => new EnumerableTable(version, table, upgradeHash, existsAt, readRecord)).ToList(); try { long dumpedEntryCount = 0; using (var f = new FileStream(outputFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, DefaultSequentialBufferSize, FileOptions.SequentialScan)) { f.SetLength(fileSizeUpToIndexEntries); f.Seek(0, SeekOrigin.Begin); using (var md5 = MD5.Create()) using (var cs = new CryptoStream(f, md5, CryptoStreamMode.Write)) using (var bs = new BufferedStream(cs, DefaultSequentialBufferSize)) { // WRITE HEADER var headerBytes = new PTableHeader(version).AsByteArray(); cs.Write(headerBytes, 0, headerBytes.Length); // WRITE INDEX ENTRIES var buffer = new byte[indexEntrySize]; long indexEntry = 0L; List <Midpoint> midpoints = new List <Midpoint>(); var requiredMidpointCount = GetRequiredMidpointCountCached(numIndexEntries, version, cacheDepth); var enum1 = enumerators[0]; var enum2 = enumerators[1]; bool available1 = enum1.MoveNext(); bool available2 = enum2.MoveNext(); IndexEntry current; while (available1 || available2) { var entry1 = new IndexEntry(enum1.Current.Stream, enum1.Current.Version, enum1.Current.Position); var entry2 = new IndexEntry(enum2.Current.Stream, enum2.Current.Version, enum2.Current.Position); if (available1 && (!available2 || entry1.CompareTo(entry2) > 0)) { current = entry1; available1 = enum1.MoveNext(); } else { current = entry2; available2 = enum2.MoveNext(); } AppendRecordTo(bs, buffer, version, current, indexEntrySize); if (version >= PTableVersions.IndexV4 && IsMidpointIndex(indexEntry, numIndexEntries, requiredMidpointCount)) { midpoints.Add(new Midpoint(new IndexEntryKey(current.Stream, current.Version), indexEntry)); } indexEntry++; dumpedEntryCount++; } //WRITE MIDPOINTS if (version >= PTableVersions.IndexV4) { if (dumpedEntryCount != numIndexEntries) { //if index entries have been removed, compute the midpoints again numIndexEntries = dumpedEntryCount; requiredMidpointCount = GetRequiredMidpointCount(numIndexEntries, version, cacheDepth); midpoints = ComputeMidpoints(bs, f, version, indexEntrySize, numIndexEntries, requiredMidpointCount, midpoints); } WriteMidpointsTo(bs, f, version, indexEntrySize, buffer, dumpedEntryCount, numIndexEntries, requiredMidpointCount, midpoints); } bs.Flush(); cs.FlushFinalBlock(); f.SetLength(f.Position + MD5Size); // WRITE MD5 var hash = md5.Hash; f.Write(hash, 0, hash.Length); f.FlushToDisk(); } } Log.Trace("PTables merge finished in {0} ([{1}] entries merged into {2}).", watch.Elapsed, string.Join(", ", tables.Select(x => x.Count)), dumpedEntryCount); return(new PTable(outputFile, Guid.NewGuid(), depth: cacheDepth, skipIndexVerify: skipIndexVerify)); } finally { foreach (var enumerator in enumerators) { enumerator.Dispose(); } } }
// Decrypt a file using a private key. private static void DecryptFile(string inFile, RSACryptoServiceProvider rsaPrivateKey) { // Create instance of AesManaged for // symetric decryption of the data. using (AesManaged aesManaged = new AesManaged()) { aesManaged.KeySize = 256; aesManaged.BlockSize = 128; aesManaged.Mode = CipherMode.CBC; // Create byte arrays to get the length of // the encrypted key and IV. // These values were stored as 4 bytes each // at the beginning of the encrypted package. byte[] LenK = new byte[4]; byte[] LenIV = new byte[4]; // Consruct the file name for the decrypted file. string outFile = decrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt"; // Use FileStream objects to read the encrypted // file (inFs) and save the decrypted file (outFs). using (FileStream inFs = new FileStream(encrFolder + inFile, FileMode.Open)) { inFs.Seek(0, SeekOrigin.Begin); inFs.Seek(0, SeekOrigin.Begin); inFs.Read(LenK, 0, 3); inFs.Seek(4, SeekOrigin.Begin); inFs.Read(LenIV, 0, 3); // Convert the lengths to integer values. int lenK = BitConverter.ToInt32(LenK, 0); int lenIV = BitConverter.ToInt32(LenIV, 0); // Determine the start postition of // the ciphter text (startC) // and its length(lenC). int startC = lenK + lenIV + 8; int lenC = (int)inFs.Length - startC; // Create the byte arrays for // the encrypted AesManaged key, // the IV, and the cipher text. byte[] KeyEncrypted = new byte[lenK]; byte[] IV = new byte[lenIV]; // Extract the key and IV // starting from index 8 // after the length values. inFs.Seek(8, SeekOrigin.Begin); inFs.Read(KeyEncrypted, 0, lenK); inFs.Seek(8 + lenK, SeekOrigin.Begin); inFs.Read(IV, 0, lenIV); Directory.CreateDirectory(decrFolder); // Use RSACryptoServiceProvider // to decrypt the AesManaged key. byte[] KeyDecrypted = rsaPrivateKey.Decrypt(KeyEncrypted, false); // Decrypt the key. using (ICryptoTransform transform = aesManaged.CreateDecryptor(KeyDecrypted, IV)) { // Decrypt the cipher text from // from the FileSteam of the encrypted // file (inFs) into the FileStream // for the decrypted file (outFs). using (FileStream outFs = new FileStream(outFile, FileMode.Create)) { int count = 0; int offset = 0; int blockSizeBytes = aesManaged.BlockSize / 8; byte[] data = new byte[blockSizeBytes]; // By decrypting a chunk a time, // you can save memory and // accommodate large files. // Start at the beginning // of the cipher text. inFs.Seek(startC, SeekOrigin.Begin); using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write)) { do { count = inFs.Read(data, 0, blockSizeBytes); offset += count; outStreamDecrypted.Write(data, 0, count); }while (count > 0); outStreamDecrypted.FlushFinalBlock(); outStreamDecrypted.Close(); } outFs.Close(); } inFs.Close(); } } } }
public static string DecryptFile(string inFile) { Aes aes = Aes.Create(); byte[] LenK = new byte[4]; byte[] LenIV = new byte[4]; string outFile = DecrFloder + inFile.Substring(0, inFile.LastIndexOf(".")); //MessageBox.Show(outFile); try { //Use FileStream objects to read the encrypted one (inFs) and save the decrypted file (ouFs). using (FileStream inFs = new FileStream(EncrFloder + inFile, FileMode.Open)) { inFs.Seek(0, SeekOrigin.Begin); inFs.Seek(0, SeekOrigin.Begin); inFs.Read(LenK, 0, 3); inFs.Seek(4, SeekOrigin.Begin); inFs.Read(LenIV, 0, 3); //Convert value inti int lenK = BitConverter.ToInt32(LenK, 0); int lenIV = BitConverter.ToInt32(LenIV, 0); //Text encrypted to length int startC = lenK + lenIV + 8; int lenC = (int)inFs.Length - startC; //Matriz encrypted byte[] KeyEncrypted = new byte[lenK]; byte[] IV = new byte[lenIV]; inFs.Seek(8, SeekOrigin.Begin); inFs.Read(KeyEncrypted, 0, lenK); inFs.Seek(8 + lenK, SeekOrigin.Begin); inFs.Read(IV, 0, lenIV); if (!Directory.Exists(DecrFloder)) { Directory.CreateDirectory(DecrFloder); } //RSA Decrypt Key byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false); ICryptoTransform transform = aes.CreateDecryptor(KeyDecrypted, IV); //RSA Decrypt File using (FileStream outFs = new FileStream(outFile, FileMode.Create)) { int count = 0; int offset = 0; int sizeBytes = aes.BlockSize / 8; byte[] date = new byte[sizeBytes]; inFs.Seek(startC, SeekOrigin.Begin); using (CryptoStream outDecrypt = new CryptoStream(outFs, transform, CryptoStreamMode.Write)) { do { count = inFs.Read(date, 0, sizeBytes); offset += count; outDecrypt.Write(date, 0, count); } while (count > 0); outDecrypt.FlushFinalBlock(); outDecrypt.Close(); } outFs.Close(); } inFs.Close(); } } catch (Exception ex) { return(ex.Message); } return($"File Decrypted.\n Origin: {inFile}\n Destiny: {outFile}"); }
/// <summary> /// Encrypts specified plaintext using Rijndael symmetric key algorithm /// and returns a base64-encoded result. /// </summary> /// <param name="plainText"> /// Plaintext value to be encrypted. /// </param> /// <param name="passPhrase"> /// Passphrase from which a pseudo-random password will be derived. The /// derived password will be used to generate the encryption key. /// Passphrase can be any string. In this example we assume that this /// passphrase is an ASCII string. /// </param> /// <param name="saltValue"> /// Salt value used along with passphrase to generate password. Salt can /// be any string. In this example we assume that salt is an ASCII string. /// </param> /// <param name="hashAlgorithm"> /// Hash algorithm used to generate password. Allowed values are: "MD5" and /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes. /// </param> /// <param name="passwordIterations"> /// Number of iterations used to generate password. One or two iterations /// should be enough. /// </param> /// <param name="initVector"> /// Initialization vector (or IV). This value is required to encrypt the /// first block of plaintext data. For RijndaelManaged class IV must be /// exactly 16 ASCII characters long. /// </param> /// <param name="keySize"> /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. /// Longer keys are more secure than shorter keys. /// </param> /// <returns> /// Encrypted value formatted as a base64-encoded string. /// </returns> public static string Encrypt ( string plainText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize ) { // Convert strings into byte arrays. // Let us assume that strings only contain ASCII codes. // If strings include Unicode characters, use Unicode, UTF7, or UTF8 // encoding. byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue); // Convert our plaintext into a byte array. // Let us assume that plaintext contains UTF8-encoded characters. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // First, we must create a password, from which the key will be derived. // This password will be generated from the specified passphrase and // salt value. The password will be created using the specified hash // algorithm. Password creation can be done in several iterations. PasswordDeriveBytes password = new PasswordDeriveBytes ( passPhrase, saltValueBytes, hashAlgorithm, passwordIterations ); // Use the password to generate pseudo-random bytes for the encryption // key. Specify the size of the key in bytes (instead of bits). byte[] keyBytes = password.GetBytes(keySize / 8); // Create uninitialized Rijndael encryption object. RijndaelManaged symmetricKey = new RijndaelManaged(); // It is reasonable to set encryption mode to Cipher Block Chaining // (CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = CipherMode.CBC; // Generate encryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. ICryptoTransform encryptor = symmetricKey.CreateEncryptor ( keyBytes, initVectorBytes ); // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = new MemoryStream(); // Define cryptographic stream (always use Write mode for encryption). CryptoStream cryptoStream = new CryptoStream ( memoryStream, encryptor, CryptoStreamMode.Write ); // Start encrypting. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); // Finish encrypting. cryptoStream.FlushFinalBlock(); // Convert our encrypted data from a memory stream into a byte array. byte[] cipherTextBytes = memoryStream.ToArray(); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert encrypted data into a base64-encoded string. string cipherText = Convert.ToBase64String(cipherTextBytes); // Return encrypted string. return(cipherText); }
public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks) { ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); var stream = new MemoryStream(); using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { Assert.True(encryptStream.CanWrite); Assert.False(encryptStream.CanRead); Assert.False(encryptStream.CanSeek); Assert.False(encryptStream.HasFlushedFinalBlock); byte[] toWrite = Encoding.UTF8.GetBytes(LoremText); // Write it all at once encryptStream.Write(toWrite, 0, toWrite.Length); Assert.False(encryptStream.HasFlushedFinalBlock); // Write in chunks encryptStream.Write(toWrite, 0, toWrite.Length / 2); encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2)); Assert.False(encryptStream.HasFlushedFinalBlock); // Write one byte at a time for (int i = 0; i < toWrite.Length; i++) { encryptStream.WriteByte(toWrite[i]); } Assert.False(encryptStream.HasFlushedFinalBlock); // Write async encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult(); Assert.False(encryptStream.HasFlushedFinalBlock); // Flush (nops) encryptStream.Flush(); encryptStream.FlushAsync().GetAwaiter().GetResult(); encryptStream.FlushFinalBlock(); Assert.Throws <NotSupportedException>(() => encryptStream.FlushFinalBlock()); Assert.True(encryptStream.HasFlushedFinalBlock); Assert.True(stream.Length > 0); } // Read/decrypt using Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { Assert.False(decryptStream.CanWrite); Assert.True(decryptStream.CanRead); Assert.False(decryptStream.CanSeek); Assert.False(decryptStream.HasFlushedFinalBlock); using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEnd()); } } // Read/decrypt using ReadToEnd stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt using a small buffer to force multiple calls to Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt one byte at a time with ReadByte stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { string expectedStr = LoremText + LoremText + LoremText + LoremText; foreach (char c in expectedStr) { Assert.Equal(c, decryptStream.ReadByte()); // relies on LoremText being ASCII } Assert.Equal(-1, decryptStream.ReadByte()); } }
public static string EncryptRijndael(string original) { byte[] encrypted; byte[] toEncrypt; UTF8Encoding utf8Converter = new UTF8Encoding(); toEncrypt = utf8Converter.GetBytes(original); RijndaelManaged myRijndael = new RijndaelManaged(); MemoryStream ms = new MemoryStream(); ICryptoTransform encryptor = myRijndael.CreateEncryptor(Key, IV); CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(toEncrypt, 0, toEncrypt.Length); cs.FlushFinalBlock(); encrypted = ms.ToArray(); string encryptedString = Convert.ToBase64String(encrypted); return encryptedString; }