private static void DecodeStream(Stream inStream, Stream output) { System.Security.Cryptography.ICryptoTransform transform = new System.Security.Cryptography.FromBase64Transform(); using (var cryptStream = new System.Security.Cryptography.CryptoStream(inStream, transform, System.Security.Cryptography.CryptoStreamMode.Read)) { byte[] buffer = new byte[4096]; int bytesRead = cryptStream.Read(buffer, 0, buffer.Length); while (bytesRead > 0) { output.Write(buffer, 0, bytesRead); bytesRead = cryptStream.Read(buffer, 0, buffer.Length); } } }
private static string Decrypt(string cipherText, string passPhrase) { byte[] initVectorBytes = System.Text.Encoding.ASCII.GetBytes("tu89geji340t89u2"); const int keysize = 256; byte[] cipherTextBytes = Convert.FromBase64String(cipherText); using (System.Security.Cryptography.PasswordDeriveBytes password = new System.Security.Cryptography.PasswordDeriveBytes(passPhrase, null)) { byte[] keyBytes = password.GetBytes(keysize / 8); using (System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged()) { symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; using (System.Security.Cryptography.ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)) { using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes)) { using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); return(System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)); } } } } } }
private byte[] Decrypt(byte[] EncData) { byte[] Result = null; try { System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged(); Enc.KeySize = 256; Enc.Key = this.Encryption_Key(); Enc.IV = this.Encryption_IV(); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(EncData); System.Security.Cryptography.CryptoStream cryptoStream = null; cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, Enc.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read); byte[] TempDecryptArr = null; TempDecryptArr = new byte[EncData.Length + 1]; int decryptedByteCount = 0; decryptedByteCount = cryptoStream.Read(TempDecryptArr, 0, EncData.Length); cryptoStream.Close(); memoryStream.Close(); cryptoStream.Dispose(); memoryStream.Dispose(); Result = new byte[decryptedByteCount + 1]; Array.Copy(TempDecryptArr, Result, decryptedByteCount); } catch (Exception) { Result = null; } return(Result); }
public static string decryptRJ256(string target, string key, string iv) { var rijndael = new System.Security.Cryptography.RijndaelManaged() { Padding = System.Security.Cryptography.PaddingMode.Zeros, Mode = System.Security.Cryptography.CipherMode.CBC, KeySize = 256, BlockSize = 256 }; var keyBytes = Encoding.ASCII.GetBytes(key); var ivBytes = Encoding.ASCII.GetBytes(iv); var decryptor = rijndael.CreateDecryptor(keyBytes, ivBytes); var toDecrypt = Convert.FromBase64String(target); var fromEncrypt = new byte[toDecrypt.Length]; var msDecrypt = new System.IO.MemoryStream(toDecrypt); var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read); csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); string data = Encoding.ASCII.GetString(fromEncrypt); data = data.Replace("\0", ""); return data; }
public static string decryptRJ256(string target, string key, string iv) { var rijndael = new System.Security.Cryptography.RijndaelManaged() { Padding = System.Security.Cryptography.PaddingMode.Zeros, Mode = System.Security.Cryptography.CipherMode.CBC, KeySize = 256, BlockSize = 256 }; var keyBytes = Encoding.ASCII.GetBytes(key); var ivBytes = Encoding.ASCII.GetBytes(iv); var decryptor = rijndael.CreateDecryptor(keyBytes, ivBytes); var toDecrypt = Convert.FromBase64String(target); var fromEncrypt = new byte[toDecrypt.Length]; var msDecrypt = new System.IO.MemoryStream(toDecrypt); var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read); csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); string data = Encoding.ASCII.GetString(fromEncrypt); data = data.Replace("\0", ""); return(data); }
public static string Decrypt(string CipherText, string Password, string Salt = "Kosher", string HashAlgorithm = "SHA1", int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(CipherText)) { return(""); } byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(CipherText); System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged(); SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = 0; using (System.Security.Cryptography.ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)) { using (System.IO.MemoryStream MemStream = new System.IO.MemoryStream(CipherTextBytes)) { using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return(Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount)); }
} // End Function Encrypt public string DeCrypt(string encryptedInput) { string returnValue = null; if (string.IsNullOrEmpty(encryptedInput)) { throw new System.ArgumentNullException("encryptedInput", "encryptedInput may not be string.Empty or NULL, because these are invid values."); } using (System.Security.Cryptography.Aes objRijndael = System.Security.Cryptography.Aes.Create()) { byte[] baCipherTextBuffer = HexStringToByteArray(encryptedInput); byte[] baDecryptionKey = HexStringToByteArray(this.m_key); byte[] baInitializationVector = HexStringToByteArray(this.m_iv); // This is where the message would be transmitted to a recipient // who already knows your secret key. Optionally, you can // also encrypt your secret key using a public key algorithm // and pass it to the mesage recipient along with the RijnDael // encrypted message. //Get a decryptor that uses the same key and IV as the encryptor. using (System.Security.Cryptography.ICryptoTransform transform = objRijndael.CreateDecryptor(baDecryptionKey, baInitializationVector)) { //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(baCipherTextBuffer)) { using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream( msDecrypt , transform , System.Security.Cryptography.CryptoStreamMode.Read) ) { byte[] baPlainTextBuffer = new byte[baCipherTextBuffer.Length]; //Read the data out of the crypto stream. csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length); //Convert the byte array back into a string. returnValue = this.m_encoding.GetString(baPlainTextBuffer); System.Array.Clear(baPlainTextBuffer, 0, baPlainTextBuffer.Length); baPlainTextBuffer = null; if (!string.IsNullOrEmpty(returnValue)) { returnValue = returnValue.Trim('\0'); } csDecrypt.Clear(); } // End Using csDecrypt } // End Using msDecrypt } // End Using transform } // End Using aes return(returnValue); } // End Function DeCrypt
} // End Function Encrypt public static string DeCrypt(string strEncryptedInput) { string strReturnValue = null; if (string.IsNullOrEmpty(strEncryptedInput)) { throw new ArgumentNullException("strEncryptedInput", "strEncryptedInput may not be string.Empty or NULL, because these are invid values."); } // Dim encASCII As New System.Text.ASCIIEncoding() System.Text.Encoding enc = System.Text.Encoding.UTF8; System.Security.Cryptography.RijndaelManaged objRijndael = new System.Security.Cryptography.RijndaelManaged(); byte[] baCipherTextBuffer = HexStringToByteArray(strEncryptedInput); string strKey = GetKey(); string strIV = GetIV(); byte[] baDecryptionKey = HexStringToByteArray(strKey); byte[] baInitializationVector = HexStringToByteArray(strIV); // This is where the message would be transmitted to a recipient // who already knows your secret key. Optionally, you can // also encrypt your secret key using a public key algorithm // and pass it to the mesage recipient along with the RijnDael // encrypted message. //Get a decryptor that uses the same key and IV as the encryptor. System.Security.Cryptography.ICryptoTransform ifaceAESdecryptor = objRijndael.CreateDecryptor(baDecryptionKey, baInitializationVector); //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(baCipherTextBuffer); System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, ifaceAESdecryptor, System.Security.Cryptography.CryptoStreamMode.Read); //Dim baPlainTextBuffer() As Byte //baPlainTextBuffer = New Byte(baCipherTextBuffer.Length) {} byte[] baPlainTextBuffer = new byte[baCipherTextBuffer.Length + 1]; //Read the data out of the crypto stream. csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length); //Convert the byte array back into a string. strReturnValue = enc.GetString(baPlainTextBuffer); if (!string.IsNullOrEmpty(strReturnValue)) { strReturnValue = strReturnValue.Trim('\0'); } return(strReturnValue); } // End Function DeCrypt
private string DecryptString(string value) { try { byte[] resultBA = new byte[value.Length / 2], valueBA = new byte[value.Length / 2]; byte[] iv = new byte[] { 0x14, 0xD7, 0x5B, 0xA2, 0x47, 0x83, 0x0F, 0xC4 }; System.Text.ASCIIEncoding ascEncoding = new System.Text.ASCIIEncoding(); byte[] key = new byte[24] { 0x21, 0x24, 0x25, 0x23, 0x34, 0x32, 0x37, 0x34, 0x38, 0x6A, 0x73, 0x54, 0x54, 0x4C, 0x7A, 0X51, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; MemoryStream memStream = new MemoryStream(); byte[] tempBA = HexStringToBytes(value); memStream.Write(tempBA, 0, tempBA.Length); memStream.Position = 0; System.Security.Cryptography.TripleDES cryptoServiceProvider = System.Security.Cryptography.TripleDESCryptoServiceProvider.Create(); System.Security.Cryptography.ICryptoTransform decryptor = cryptoServiceProvider.CreateDecryptor(key, iv); System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream( memStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read); cStream.Read(resultBA, 0, resultBA.Length); cStream.Close(); // Find the first zero int i = 0; for (; i < resultBA.GetLength(0); i++) { if (resultBA[i] == 0) { break; } } return(ascEncoding.GetString(resultBA, 0, i)); } catch (Exception exc) { MessageBox.Show("Decryption failure. " + exc.ToString()); return(value); } }
static internal string DecryptString(string value) { try { byte[] resultBA = new byte[value.Length / 2], valueBA = new byte[value.Length / 2]; byte[] iv = new byte[] { 0x14, 0xD7, 0x5B, 0xA2, 0x47, 0x83, 0x0F, 0xC4 }; System.Text.ASCIIEncoding ascEncoding = new System.Text.ASCIIEncoding(); byte[] key = new byte[24] { 0x21, 0x24, 0x25, 0x23, 0x34, 0x32, 0x37, 0x34, 0x38, 0x6A, 0x73, 0x54, 0x54, 0x4C, 0x7A, 0X51, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; MemoryStream memStream = new MemoryStream(); byte[] tempBA = InternalMethods.HexStringToBytes(value); memStream.Write(tempBA, 0, tempBA.Length); memStream.Position = 0; System.Security.Cryptography.TripleDES cryptoServiceProvider = System.Security.Cryptography.TripleDESCryptoServiceProvider.Create(); System.Security.Cryptography.ICryptoTransform decryptor = cryptoServiceProvider.CreateDecryptor(key, iv); System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream( memStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read); cStream.Read(resultBA, 0, resultBA.Length); cStream.Close(); // Find the first zero int i = 0; for (; i < resultBA.GetLength(0); i++) { if (resultBA[i] == 0) { break; } } return(ascEncoding.GetString(resultBA, 0, i)); } catch (Exception exc) { EPSEventLog.WriteEntry("Decryption failure. Returning original value" + Environment.NewLine + exc.Source, EventLogEntryType.Error); return(value); } }
public void Decode(string inFileName, string outFileName) { System.Security.Cryptography.ICryptoTransform transform = new System.Security.Cryptography.FromBase64Transform(); using (System.IO.FileStream inFile = System.IO.File.OpenRead(inFileName), outFile = System.IO.File.Create(outFileName)) using (System.Security.Cryptography.CryptoStream cryptStream = new System.Security.Cryptography.CryptoStream(inFile, transform, System.Security.Cryptography.CryptoStreamMode.Read)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = cryptStream.Read(buffer, 0, buffer.Length)) > 0) { outFile.Write(buffer, 0, bytesRead); } outFile.Flush(); } }
public static string DeCrypt(string strEncryptedInput) { string strReturnValue = null; if (string.IsNullOrEmpty(strEncryptedInput)) { throw new System.ArgumentNullException("strEncryptedInput", "strEncryptedInput may not be string.Empty or NULL, because these are invid values."); } // Dim encASCII As New System.Text.ASCIIEncoding() System.Text.Encoding enc = System.Text.Encoding.UTF8; System.Security.Cryptography.RijndaelManaged objRijndael = new System.Security.Cryptography.RijndaelManaged(); byte[] baCipherTextBuffer = HexStringToByteArray(strEncryptedInput); byte[] baDecryptionKey = HexStringToByteArray(strKey); byte[] baInitializationVector = HexStringToByteArray(strIV); // This is where the message would be transmitted to a recipient // who already knows your secret key. Optionally, you can // also encrypt your secret key using a public key algorithm // and pass it to the mesage recipient along with the RijnDael // encrypted message. //Get a decryptor that uses the same key and IV as the encryptor. System.Security.Cryptography.ICryptoTransform ifaceAESdecryptor = objRijndael.CreateDecryptor(baDecryptionKey, baInitializationVector); //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(baCipherTextBuffer); System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, ifaceAESdecryptor, System.Security.Cryptography.CryptoStreamMode.Read); //Dim baPlainTextBuffer() As Byte //baPlainTextBuffer = New Byte(baCipherTextBuffer.Length) {} byte[] baPlainTextBuffer = new byte[baCipherTextBuffer.Length + 1]; //Read the data out of the crypto stream. csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length); //Convert the byte array back into a string. strReturnValue = enc.GetString(baPlainTextBuffer); if (!string.IsNullOrEmpty(strReturnValue)) strReturnValue = strReturnValue.Trim('\0'); return strReturnValue; }
/// <summary> /// Decrypt a stream based on fixed internal keys /// </summary> /// <param name="EncryptedStream"></param> /// <returns></returns> private MemoryStream DecryptStream(Stream EncryptedStream) { try { System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged(); Enc.KeySize = 256; // KEY is 32 byte array Enc.Key = LineMapKeys.ENCKEY; // IV is 16 byte array Enc.IV = LineMapKeys.ENCIV; var cryptoStream = new System.Security.Cryptography.CryptoStream(EncryptedStream, Enc.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read); byte[] buf = null; buf = new byte[1024]; MemoryStream DecryptedStream = new MemoryStream(); while (EncryptedStream.Length > 0) { var l = cryptoStream.Read(buf, 0, 1024); if (l == 0) { break; // TODO: might not be correct. Was : Exit Do } if (l < 1024) { Array.Resize(ref buf, l); } DecryptedStream.Write(buf, 0, buf.GetUpperBound(0) + 1); if (l < 1024) { break; // TODO: might not be correct. Was : Exit Do } } DecryptedStream.Position = 0; return(DecryptedStream); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("ERROR: {0}", ex.ToString())); // any problems, nothing much to do, so return an empty stream return(new MemoryStream()); } }
/// <summary> /// Descriptografa um array de bytes em outro array de bytes. /// </summary> /// <returns>Array de bytes descriptografado.</returns> /// <param name="p_ciphertextbytes">Array de bytes criptografado.</param> public byte[] DecryptToBytes(byte[] p_ciphertextbytes) { byte[] v_plaintextbytes; byte[] v_decryptedbytes; int v_decryptedbytecount; int v_saltlength; System.IO.MemoryStream v_memory; System.Security.Cryptography.CryptoStream v_crypto; try { this.Initialize(); v_memory = new System.IO.MemoryStream(p_ciphertextbytes); v_decryptedbytes = new byte[p_ciphertextbytes.Length]; lock (this) { v_crypto = new System.Security.Cryptography.CryptoStream(v_memory, this.v_decryptor, System.Security.Cryptography.CryptoStreamMode.Read); v_decryptedbytecount = v_crypto.Read(v_decryptedbytes, 0, v_decryptedbytes.Length); v_memory.Close(); v_crypto.Close(); } v_saltlength = (v_decryptedbytes[0] & 0x03) | (v_decryptedbytes[1] & 0x0c) | (v_decryptedbytes[2] & 0x30) | (v_decryptedbytes[3] & 0xc0); v_plaintextbytes = new byte[v_decryptedbytecount - v_saltlength]; System.Array.Copy(v_decryptedbytes, v_saltlength, v_plaintextbytes, 0, v_decryptedbytecount - v_saltlength); return(v_plaintextbytes); } catch (System.Security.Cryptography.CryptographicException e) { throw new SpartacusMin.Utils.Exception(e); } }
public string DecryptString(string value, string keyString) { try { byte[] resultBA = new byte[value.Length / 2], valueBA = new byte[value.Length / 2]; byte[] iv = new byte[] { 0x14, 0xD7, 0x5B, 0xA2, 0x47, 0x83, 0x0F, 0xC4 }; System.Text.ASCIIEncoding ascEncoding = new System.Text.ASCIIEncoding(); byte[] key = new byte[24]; ascEncoding.GetBytes(keyString, 0, keyString.Length < 24?keyString.Length:24, key, 0); MemoryStream memStream = new MemoryStream(); byte[] tempBA = InternalMethods.HexStringToBytes(value); memStream.Write(tempBA, 0, tempBA.Length); memStream.Position = 0; System.Security.Cryptography.TripleDES cryptoServiceProvider = System.Security.Cryptography.TripleDESCryptoServiceProvider.Create(); System.Security.Cryptography.ICryptoTransform decryptor = cryptoServiceProvider.CreateDecryptor(key, iv); System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream( memStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read); cStream.Read(resultBA, 0, resultBA.Length); cStream.Close(); return(ascEncoding.GetString(resultBA)); } catch (Exception exc) { LogEvent("Decryption failure. Returning original value" + Environment.NewLine + exc.Source, "DecryptString()", exc.ToString(), 3); return(value); } }
private byte[] AESDecrypt(byte[] data, int index, int count, byte[] key) { byte[] decryptedBytes = null; // Create uninitialized Rijndael encryption object. System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged(); // It is required that the encryption mode is Electronic Codebook (ECB) // see MS-OFFCRYPTO v1.0 2.3.4.7 pp 39. symmetricKey.Mode = System.Security.Cryptography.CipherMode.ECB; symmetricKey.Padding = System.Security.Cryptography.PaddingMode.None; symmetricKey.KeySize = keySize; // symmetricKey.IV = null; // new byte[16]; // symmetricKey.Key = key; // Generate decryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. System.Security.Cryptography.ICryptoTransform decryptor; decryptor = symmetricKey.CreateDecryptor(key, null); // Define memory stream which will be used to hold encrypted data. using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(data, index, count)) { // Define memory stream which will be used to hold encrypted data. using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { // Since at this point we don't know what the size of decrypted data // will be, allocate the buffer long enough to hold ciphertext; // plaintext is never longer than ciphertext. decryptedBytes = new byte[data.Length]; int decryptedByteCount = cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length); return(decryptedBytes); } } }
public static string strDecifraString(string strTextoASerDecifrado) { string strRetorno = ""; try { byte[] byTextoASerDeCifrado, byTextoDeCifrado; byte[] byKey = new byte[] { 255, 241, 3, 17, 206, 69, 56, 167, 94, 220, 219, 76, 112, 179, 12, 97, 178, 233, 14, 172, 238, 20, 54, 232, 212, 54, 50, 151, 138, 32, 26, 122 }; byte[] byIV = new byte[] { 207, 100, 146, 104, 139, 60, 94, 109, 109, 195, 236, 213, 235, 234, 233, 114 }; System.Text.UnicodeEncoding conversorTexto = new System.Text.UnicodeEncoding(); System.Security.Cryptography.RijndaelManaged clsSecCrypRijndael = new System.Security.Cryptography.RijndaelManaged(); clsSecCrypRijndael.Padding = System.Security.Cryptography.PaddingMode.Zeros; //Get an encryptor. System.Security.Cryptography.ICryptoTransform decifrador = clsSecCrypRijndael.CreateDecryptor(byKey, byIV); byTextoASerDeCifrado = System.Convert.FromBase64String(strTextoASerDecifrado); // Cria os Streams System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(byTextoASerDeCifrado); System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decifrador, System.Security.Cryptography.CryptoStreamMode.Read); byTextoDeCifrado = new byte[byTextoASerDeCifrado.Length]; // Read all data to the crypto stream and flush it. cryptoStream.Read(byTextoDeCifrado, 0, byTextoDeCifrado.Length); strRetorno = conversorTexto.GetString(byTextoDeCifrado).Replace("\0", ""); } catch (Exception err) { m_errException = err; return(strRetorno); } return(strRetorno); }
public override int Read(byte[] buffer, int offset, int count) { return(_cryptoStream.Read(buffer, offset, count)); }
public static string Decrypt(string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(CipherText)) return ""; byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(CipherText); System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged(); SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = 0; using (System.Security.Cryptography.ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)) { using (MemoryStream MemStream = new MemoryStream(CipherTextBytes)) { using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount); }
public static T ReceiveEncrypted <T>(SharedNetwork.SharedNetworkInfo info) { Packet packet = ProtoBuf.Serializer.DeserializeWithLengthPrefix <Packet>(info.Stream, ProtoBuf.PrefixStyle.Fixed32); if (packet == null) { throw new Exception("Received packet was null!"); } Printer.PrintDiagnostics("Received {0} byte packet.", packet.Data.Length); byte[] decryptedData = packet.Data; if (info.DecryptorFunction != null) { decryptedData = new byte[packet.PayloadSize]; if (packet.PayloadSize > 0) { using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(packet.Data)) using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(memoryStream, info.Decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { cs.Read(decryptedData, 0, decryptedData.Length); } } } if (packet.DecompressedSize.HasValue) { switch (packet.Compression) { case PacketCompressionCodec.None: break; case PacketCompressionCodec.LZ4: decryptedData = LZ4.LZ4Codec.Decode(decryptedData, 0, decryptedData.Length, packet.DecompressedSize.Value); break; case PacketCompressionCodec.LZH: { Versionr.Utilities.LZHL.ResetDecompressor(info.LZHLDecompressor); byte[] result = new byte[packet.DecompressedSize.Value]; Versionr.Utilities.LZHL.Decompress(info.LZHLDecompressor, decryptedData, (uint)decryptedData.Length, result, (uint)result.Length); decryptedData = result; break; } } Printer.PrintDiagnostics(" - {0} bytes decompressed ({1})", packet.DecompressedSize.Value, packet.Compression); } if (packet.Checksum != ChecksumCodec.None) { uint checksum = 0; if (packet.Checksum == ChecksumCodec.XXHash) { checksum = ComputeChecksumXXHash(decryptedData); } if (packet.Checksum == ChecksumCodec.Adler32) { checksum = ComputeChecksumAdler32(decryptedData); } if (packet.Checksum == ChecksumCodec.FastFNV) { checksum = ComputeChecksumFNVWeak(decryptedData); } if (packet.Checksum == ChecksumCodec.MurMur3) { var hasher = new Versionr.Utilities.Murmur3(); var hash = hasher.ComputeHash(decryptedData); checksum = BitConverter.ToUInt32(hash, 0) ^ BitConverter.ToUInt32(hash, 4) ^ BitConverter.ToUInt32(hash, 8) ^ BitConverter.ToUInt32(hash, 12); } if (checksum != packet.Hash) { throw new Exception("Data did not survive the trip!"); } } using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(decryptedData)) { return(ProtoBuf.Serializer.Deserialize <T>(memoryStream)); } }
static void Main(string[] args) { Intuit.Spc.Map.Features.EntitlementClient.Api.Entitlements.IEntitlementManager e = new Intuit.Spc.Map.Features.EntitlementClient.Api.Entitlements.EntitlementManager(); e.EntitlementManifestFileName = "C:\\Program Files\\Intuit\\QuickBooks 2010\\Components\\PConfig\\manifest.ecml"; /* * if (e.CheckOfferingCode("068741")) * { * Console.WriteLine("OK"); * } * * Api.Synchronization.ISynchronizationManager ism = e.GetSynchronizationManager("103347861573284", "405697"); * object output; * if (ism.ApplyVerbalSyncEntitlementsResponse("TOTAL_FLOATING_KEYS", "71477210", out output)) * { * Console.WriteLine("Good - {0}", output.ToString()); * } * * Common.Data.Manifest me = new Common.Data.Manifest(); * try * { * Common.Data.PropertyTypeDescriptor ptd = me.GetPropertyTypeDescriptorByName("TOTAL_FLOATING_KEYS"); * Console.WriteLine(ptd.Name); * } * catch (Exception k) * { * * Console.WriteLine(k.ToString()); * } */ /* * Api.Entitlements.Custom.IOfferingEntitlement1 iof = (Api.Entitlements.Custom.IOfferingEntitlement1)e.GetOfferingEntitlement("103347861573284", "405697"); * * Console.WriteLine(iof.BindableResourceId); * * Common.PhoneTransaction.PhoneTransactionManager pm = new Common.PhoneTransaction.PhoneTransactionManager(); * if (pm.IsEnablementCodeValid("103347861573284", "405697", "", "493864")) * { * Console.WriteLine("OKOKOK"); * } */ /* * string c0 = "136471550573136405697"; * //int k0 = pm.ComputeIndex(c0); * //Console.WriteLine("1:{0}", k0); * * System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.HashAlgorithm.Create("SHA1"); * System.Text.UTF8Encoding u8e = new System.Text.UTF8Encoding(); * byte[] c1 = u8e.GetBytes(c0); * * int tick = System.Environment.TickCount; * * byte[] c2 = ha.ComputeHash(c1); * * //Console.WriteLine(BitConverter.ToString(c2)); * * for (int i = 0; i < 0x270f; i++) * { * c2 = ha.ComputeHash(c2); * } * * Console.WriteLine("s: {0}", System.Environment.TickCount - tick); * Console.WriteLine(BitConverter.ToString(c2)); * * BigInteger bi = new BigInteger(c2); * BigInteger bc = new BigInteger((Int64)0x186a0); * BigInteger bv = bi % bc; * * Console.WriteLine("2:{0}", bv.IntValue()); * int k0 = bv.IntValue(); * * //k0 = pm.ComputeIndex(c0); * //Console.WriteLine("1:{0}", k0); */ /* * Assembly ab = Assembly.GetAssembly(typeof(BigInteger)); * Console.WriteLine(ab.FullName); * * * try * { * System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Intuit.Spc.Map.Features.EntitlementClient.Common.hash", ab); * byte[] go = (byte[])(rm.GetObject("Hash Table")); * * BinaryWriter bw = new BinaryWriter(File.Open("e:\\htv10.dat", FileMode.Create)); * bw.Write(go); * bw.Close(); * * byte[] sum = new byte[20]; * * Array.Copy(go, k0 * 20, sum, 0, 20); * * BigInteger v1 = new BigInteger(sum); * string v2 = k0.ToString().PadLeft(5, '0'); * System.Text.UTF8Encoding v3 = new System.Text.UTF8Encoding(); * System.Security.Cryptography.HashAlgorithm v4 = System.Security.Cryptography.HashAlgorithm.Create("SHA1"); * int v5 = 0; * bool done = false; * m _m = new m(4); * string cc; * * int start = Int32.Parse(Console.ReadLine()); * int end = Int32.Parse(Console.ReadLine()); * Console.WriteLine("start:{0} end{1}", start, end); * * for (int k = start; k < end; k++) * { * cc = k.ToString().PadLeft(6, '0'); * if(k % 10 == 0) Console.WriteLine(">{0}", cc); * //if (!_m.a_s(cc)) continue; * * for (v5 = 0; v5 < 0x2710; v5++) * { * //if(v5 % 1000 == 0) Console.WriteLine("-{0}", v5); * * string tt = cc + v5.ToString().PadLeft(4, '0') + v2; * BigInteger bt = new BigInteger(v4.ComputeHash(v3.GetBytes(tt))); * * if (v1 == bt) * { * done = true; * Console.WriteLine("Done -- {0}-{1}", k, v5); * break; * } * } * * if (done) break; * } * * } * catch (Exception k) * { * * Console.WriteLine(k.ToString()); * } */ try { Type type = typeof(Common.Security.CryptoManager); BindingFlags privateBindings = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static; MethodInfo miGetDescription = type.GetMethod("g", privateBindings); object retObj = miGetDescription.Invoke(null, new object[] { }); System.Security.Cryptography.ICryptoTransform v2 = (System.Security.Cryptography.ICryptoTransform)retObj; FileInfo f = Common.Utilities.DirectoryUtilities.GetManifestFileLocation(); System.IO.FileStream v1 = new System.IO.FileStream(f.FullName, (System.IO.FileMode) 3, (System.IO.FileAccess) 1, (System.IO.FileShare) 3 ); byte[] v0 = null; System.Security.Cryptography.ICryptoTransform v7 = v2; System.Security.Cryptography.CryptoStream v3 = new System.Security.Cryptography.CryptoStream(v1, v2, (System.Security.Cryptography.CryptoStreamMode) 0); if (v1.Length <= 0x7fffffff) { Console.WriteLine("{0}------", v1.Length); v0 = new Byte[v1.Length]; int len = v3.Read(v0, 0, v0.Length); Console.WriteLine("size read: {0}", len); string pp = System.Text.Encoding.UTF8.GetString(v0); //Console.WriteLine(pp); StreamWriter wp = new StreamWriter("c:\\pk.xml"); wp.Write(pp); wp.Close(); } } catch (Exception k) { Console.WriteLine(k.ToString()); } Console.WriteLine("end"); Console.Read(); }
} // End Function Encrypt public static string Decrypt(string encryptedInput) { string returnValue = null; if (string.IsNullOrEmpty(encryptedInput)) { return(encryptedInput); } // System.Text.Encoding enc = System.Text.Encoding.ASCII; System.Text.Encoding enc = System.Text.Encoding.UTF8; byte[] cipherTextBuffer = HexStringToByteArray(encryptedInput); byte[] decryptionKey = HexStringToByteArray(s_key); byte[] initializationVector = HexStringToByteArray(s_IV); using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create()) { // This is where the message would be transmitted to a recipient // who already knows your secret key. Optionally, you can // also encrypt your secret key using a public key algorithm // and pass it to the mesage recipient along with the RijnDael // encrypted message. //Get a decryptor that uses the same key and IV as the encryptor. using (System.Security.Cryptography.ICryptoTransform aesDecryptor = aes.CreateDecryptor(decryptionKey, initializationVector)) { //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(cipherTextBuffer)) { using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, aesDecryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { //Dim baPlainTextBuffer() As Byte //baPlainTextBuffer = New Byte(baCipherTextBuffer.Length) {} byte[] baPlainTextBuffer = new byte[cipherTextBuffer.Length + 1]; //Read the data out of the crypto stream. csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length); //Convert the byte array back into a string. returnValue = enc.GetString(baPlainTextBuffer); if (!string.IsNullOrEmpty(returnValue)) { returnValue = returnValue.Trim('\0'); } } // End Using csDecrypt } // End Using msDecrypt } // End Using aesDecryptor } // End Using aes System.Array.Clear(cipherTextBuffer, 0, cipherTextBuffer.Length); cipherTextBuffer = null; System.Array.Clear(decryptionKey, 0, decryptionKey.Length); decryptionKey = null; System.Array.Clear(initializationVector, 0, initializationVector.Length); initializationVector = null; return(returnValue); } // End Function DeCrypt
/// <summary> /// Descriptografa um array de bytes em outro array de bytes. /// </summary> /// <returns>Array de bytes descriptografado.</returns> /// <param name="p_ciphertextbytes">Array de bytes criptografado.</param> public byte[] DecryptToBytes(byte[] p_ciphertextbytes) { byte[] v_plaintextbytes; byte[] v_decryptedbytes; int v_decryptedbytecount; int v_saltlength; System.IO.MemoryStream v_memory; System.Security.Cryptography.CryptoStream v_crypto; try { this.Initialize(); v_memory = new System.IO.MemoryStream(p_ciphertextbytes); v_decryptedbytes = new byte[p_ciphertextbytes.Length]; lock (this) { v_crypto = new System.Security.Cryptography.CryptoStream(v_memory, this.v_decryptor, System.Security.Cryptography.CryptoStreamMode.Read); v_decryptedbytecount = v_crypto.Read(v_decryptedbytes, 0, v_decryptedbytes.Length); v_memory.Close(); v_crypto.Close(); } v_saltlength = (v_decryptedbytes[0] & 0x03) | (v_decryptedbytes[1] & 0x0c) | (v_decryptedbytes[2] & 0x30) | (v_decryptedbytes[3] & 0xc0); v_plaintextbytes = new byte[v_decryptedbytecount - v_saltlength]; System.Array.Copy(v_decryptedbytes, v_saltlength, v_plaintextbytes, 0, v_decryptedbytecount - v_saltlength); return v_plaintextbytes; } catch (System.Security.Cryptography.CryptographicException e) { throw new Spartacus.Utils.Exception(e); } }
/// <SUMMARY> /// Decrypts specified ciphertext using Rijndael symmetric key algorithm. /// </SUMMARY> /// <PARAM name="cipherText"> /// Base64-formatted ciphertext value. /// </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> /// Decrypted string value. /// </RETURNS> /// <REMARKS> /// Most of the logic in this function is similar to the Encrypt /// logic. In order for decryption to work, all parameters of this function /// - except cipherText value - must match the corresponding parameters of /// the Encrypt function which was called to generate the /// ciphertext. /// </REMARKS> public string Decrypt(string cipherText) { // Convert strings defining encryption key characteristics to 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 ciphertext to a byte array. byte[] cipherTextBytes = Convert.FromBase64String(cipherText); // 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. System.Security.Cryptography.PasswordDeriveBytes password = new System.Security.Cryptography.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. System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged(); // It is reasonable to set encryption mode to Cipher Block Chaining // (CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC; // Generate decryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. System.Security.Cryptography.ICryptoTransform decryptor = symmetricKey.CreateDecryptor( keyBytes, initVectorBytes); // Define memory stream which will be used to hold encrypted data. System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(cipherTextBytes); // Define cryptographic stream (always use Read mode for encryption). System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read); // Since at this point we don't know what the size of decrypted data // will be, allocate the buffer long enough to hold ciphertext; // plaintext is never longer than ciphertext. byte[] plainTextBytes = new byte[cipherTextBytes.Length]; // Start decrypting. int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert decrypted data to a string. // Let us assume that the original plaintext string was UTF8-encoded. string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); // Return decrypted string. return(plainText); }
private byte[] AESDecrypt(byte[] data, int index, int count, byte[] key) { byte[] decryptedBytes = null; // Create uninitialized Rijndael encryption object. System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged(); // It is required that the encryption mode is Electronic Codebook (ECB) // see MS-OFFCRYPTO v1.0 2.3.4.7 pp 39. symmetricKey.Mode = System.Security.Cryptography.CipherMode.ECB; symmetricKey.Padding = System.Security.Cryptography.PaddingMode.None; symmetricKey.KeySize = keySize; // symmetricKey.IV = null; // new byte[16]; // symmetricKey.Key = key; // Generate decryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. System.Security.Cryptography.ICryptoTransform decryptor; decryptor = symmetricKey.CreateDecryptor(key, null); // Define memory stream which will be used to hold encrypted data. using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(data, index, count)) { // Define memory stream which will be used to hold encrypted data. using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { // Since at this point we don't know what the size of decrypted data // will be, allocate the buffer long enough to hold ciphertext; // plaintext is never longer than ciphertext. decryptedBytes = new byte[data.Length]; int decryptedByteCount = cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length); return decryptedBytes; } } }
private byte[] Decrypt(byte[] EncData) { byte[] Result = null; try { System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged(); Enc.KeySize = 256; Enc.Key = this.Encryption_Key(); Enc.IV = this.Encryption_IV(); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(EncData); System.Security.Cryptography.CryptoStream cryptoStream = null; cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, Enc.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read); byte[] TempDecryptArr = null; TempDecryptArr = new byte[EncData.Length + 1]; int decryptedByteCount = 0; decryptedByteCount = cryptoStream.Read(TempDecryptArr, 0, EncData.Length); cryptoStream.Close(); memoryStream.Close(); cryptoStream.Dispose(); memoryStream.Dispose(); Result = new byte[decryptedByteCount + 1]; Array.Copy(TempDecryptArr, Result, decryptedByteCount); } catch (Exception) { Result = null; } return Result; }