static Dictionary<string, string> Decrypt(string cipherText, string encryptionPassword, string salt) { using (var algorithm = new AesCryptoServiceProvider { Key =GetEncryptionKey(encryptionPassword), IV = Convert.FromBase64String(salt) }) using (var decryptor = algorithm.CreateDecryptor()) using (var decryptedTextStream = new MemoryStream()) using (var stringReader = new StreamReader(decryptedTextStream, Encoding.UTF8)) using (var jsonReader = new JsonTextReader(stringReader)) { try { using (var cryptoStream = new CryptoStream(decryptedTextStream, decryptor, CryptoStreamMode.Write)) { var cipherTextBytes = Convert.FromBase64String(cipherText); cryptoStream.Write(cipherTextBytes, 0, cipherTextBytes.Length); cryptoStream.FlushFinalBlock(); var dictionary = new Dictionary<string, string>(); var serializer = new JsonSerializer(); decryptedTextStream.Position = 0; serializer.Populate(jsonReader, dictionary); return dictionary; } } catch (CryptographicException cryptoException) { throw new CommandException( "Cannot decrypt sensitive-variables. Check your password is correct.\nError message: " + cryptoException.Message); } } }
/// <summary> /// Decrypts data from one stream to another stream. /// </summary> /// <param name="input">Stream containing encrypted data</param> /// <param name="output">Stream that will receive the decrypted data</param> /// <param name="encryptionKey">Key to decrypt the data with</param> /// <param name="IV">IV to decrypt the data with</param> internal static void DecryptAesStream(Stream input, Stream output, byte[] encryptionKey, byte[] IV) { using (var aes = new AesCryptoServiceProvider {Padding = PaddingMode.ISO10126}) using (var decryptor = aes.CreateDecryptor(encryptionKey, IV)) { var lengthBytes = new byte[AesHeaderSize]; input.Read(lengthBytes, 0, AesHeaderSize); var length = BitConverter.ToInt32(lengthBytes, 0); using (var cs = new CryptoStream(input, decryptor, CryptoStreamMode.Read)) { long position = BufferSize; var buffer = new byte[BufferSize]; while (position<length) { cs.Read(buffer, 0, BufferSize); output.Write(buffer, 0, BufferSize); position += BufferSize; } int offset = length % BufferSize; if (offset>0) { cs.Read(buffer, 0, offset); output.Write(buffer, 0, offset); } output.Flush(); } } }
/// <summary> /// Decrypts the specified crypt text. /// </summary> /// <param name="cryptoText">The crypto text.</param> /// <returns>The plain text.</returns> public string Decrypt(byte[] cryptoText) { string clearText; using (var aes = new AesCryptoServiceProvider()) { aes.Key = this.Key; aes.IV = this.InitalizationVector; var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (var memoryStream = new MemoryStream(cryptoText)) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { using (var streamReader = new StreamReader(cryptoStream)) { clearText = streamReader.ReadToEnd(); } } } } return clearText; }
public static string Decrypt(string input) { //byte[] inputBytes = Convert.FromBase64String(input); //Encoding.UTF8.GetBytes(input); string[] sInput = input.Split("-".ToCharArray()); byte[] inputBytes = new byte[sInput.Length]; for (int i = 0; i < sInput.Length; i++) { inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber); } byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 32)); using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = keyBytes; aesAlg.IV = AesIv; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream(inputBytes)) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srEncrypt = new StreamReader(csEncrypt)) { return srEncrypt.ReadToEnd(); } } } } }
public void SetUp() { using ( AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider() ) { m_Encryptor = aesAlg.CreateEncryptor(); m_Decryptor = aesAlg.CreateDecryptor(); } }
public void Decrypt(string filename) { FileStream fsInput = new FileStream(filename, FileMode.Open, FileAccess.Read); FileStream fsOutput = new FileStream(filename + ".crypt", FileMode.Create, FileAccess.Write); AesCryptoServiceProvider Aes = new AesCryptoServiceProvider(); Aes.KeySize = 128; byte[] input = new byte[256]; int count = fsInput.Read(input, 0, 256); Aes.Key = _algorithm_asym.Decrypt(input, false); count = fsInput.Read(input, 0, 256); Aes.IV = _algorithm_asym.Decrypt(input, false); ICryptoTransform desencrypt = Aes.CreateDecryptor(); CryptoStream cryptostream = new CryptoStream(fsOutput, desencrypt, CryptoStreamMode.Write); byte[] bytearrayinput = new byte[fsInput.Length - 1]; fsInput.Read(bytearrayinput, 0, bytearrayinput.Length); cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length); fsInput.Close(); fsOutput.Close(); }
public string Decription(byte[] encryptedData, byte[] alicePubKeyBlob) { byte[] rawData = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) iv[i] = encryptedData[i]; using (var bobAlgorithm = new ECDiffieHellmanCng(privKey)) using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes); cs.Close(); rawData = ms.ToArray(); } aes.Clear(); } return Encoding.UTF8.GetString(rawData); }
public static byte[] Decrypt(byte[] encryptedString, string privateKey) { // We hash the private key string to ensure we have a key with the correct // number of bytes. var privateKeyHash = HashKey(privateKey); using (var provider = new AesCryptoServiceProvider()) { provider.Key = privateKeyHash; using (var ms = new MemoryStream(encryptedString)) { // Read the first 16 bytes which is the IV. byte[] iv = new byte[16]; ms.Read(iv, 0, 16); provider.IV = iv; using (var decryptor = provider.CreateDecryptor()) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { return ReadToEnd(cs); } } } } }
/// <summary> /// 解密字节数组 /// </summary> /// <param name="inputData">要解密的字节数据</param> /// <param name="password">密码</param> /// <returns></returns> public static byte[] Decrypt(byte[] inputData, string password) { AesCryptoServiceProvider aes = new AesCryptoServiceProvider { Key = GetKeyArray(password), Mode = cipherMode, Padding = paddingMode }; var transform = aes.CreateDecryptor(); byte[] data = null; try { data = transform.TransformFinalBlock(inputData, 0, inputData.Length); } catch { return null; } aes.Clear(); return data; }
public static long Decrypt(string cipherText) { if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText"); if (AesCryptoServiceProvider.Key == null || AesCryptoServiceProvider.Key.Length <= 0) throw new ArgumentNullException("Key"); if (AesCryptoServiceProvider.IV == null || AesCryptoServiceProvider.IV.Length <= 0) throw new ArgumentNullException("IV"); string plaintext; using (var aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = AesCryptoServiceProvider.Key; aesAlg.IV = AesCryptoServiceProvider.IV; var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (var msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText))) { using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (var srDecrypt = new StreamReader(csDecrypt)) { plaintext = srDecrypt.ReadToEnd(); } } } } return Convert.ToInt64(plaintext); }
protected override string DecryptByBlocks(byte[] key, byte[] iv, List<byte> cipherText) { var message = new StringBuilder(); using (var aes = new AesCryptoServiceProvider()) { aes.BlockSize = BlockSize * 8; aes.KeySize = KeySize * 8; aes.Key = key; aes.IV = iv; aes.Padding = PaddingMode.None; using (var decr = aes.CreateDecryptor()) { while (cipherText.Count != 0) { if (cipherText.Count == BlockSize) { aes.Padding = PaddingMode.PKCS7; } var block = DetachBlock(cipherText); var decrypted = new byte[BlockSize]; decr.TransformBlock(block, 0, BlockSize, decrypted, 0); if (!decrypted.All(x => x == BlockSize)) { message.Append(BytesToPlainText(decrypted)); } aes.IV = block; } } } return message.ToString(); }
public string decrypt(byte[] msg, byte[] key) { using (var d = new System.Security.Cryptography.AesCryptoServiceProvider()) { var iv = Enumerable.Repeat((byte)0, 16).ToArray(); d.IV = iv; d.Key = key; d.Mode = CipherMode.CBC; d.Padding = PaddingMode.None; var t = d.CreateDecryptor(); using (var ms = new System.IO.MemoryStream(msg)) { using (var cs = new CryptoStream(ms, t, CryptoStreamMode.Read)) { using (var sr = new System.IO.StreamReader(cs)) { var r = sr.ReadToEnd(); return(r); } } } } }
public string Decrypt(string cipherText, string key, string iv) { try { AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); //aes.BlockSize = 128; //aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.IV = new byte[16];// Encoding.UTF8.GetBytes("DBDF15AA65379176"); aes.Key = Encoding.UTF8.GetBytes(key); // Convert Base64 strings to byte array byte[] src = System.Convert.FromBase64String(cipherText); // decryption using (ICryptoTransform decrypt = aes.CreateDecryptor()) { byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length); return Encoding.UTF8.GetString(dest); } } catch { return string.Empty; } }
/// <summary> /// Decrypts a file encrypted with AES /// </summary> /// <param name="filePath">Full path of the file to be decrypted</param> /// <param name="outputFilePath">Full path of the decrypted file</param> /// <param name="key">AES decryption key</param> /// <param name="iv">AES initialization vector</param> /// <param name="useECBMode">boolean to determine if ECB or CBC mode is used</param> public static void DecryptFile(string filePath, string outputFilePath, byte[] key, byte[] iv, bool useECBMode) { using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { if (useECBMode) aes.Mode = CipherMode.ECB; else aes.Mode = CipherMode.CBC; aes.Key = key; aes.IV = iv; using (ICryptoTransform cryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV)) { using (FileStream encrypted = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (FileStream plain = File.Open(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) { using (CryptoStream cs = new CryptoStream(plain, cryptoTransform, CryptoStreamMode.Write)) { encrypted.CopyTo(cs, bufferSize); } } } } } }
/// <summary> /// Decrypt a message using AES in CBC (cipher-block chaining) mode. /// </summary> /// <param name="ciphertext">The message encrypted with AES in CBC mode</param> /// <param name="key">The key used to encrypt the message</param> /// <param name="iv">The initialization vector provided, if one was provided. If you are absolutely certain /// the key will only be used once, an IV is not necessary and zero will be used.</param> /// <param name="checkAndRemoveHmac">Set if an HMACHSA256 was placed at the end of the plaintext before encrypting. /// The HMAC will be removed before the plaintext is returned. If the HMAC does not match, the method will throw a /// System.Security.Cryptography.CryptographicException.</param> /// <returns>The plaintext resulting from decrypting the ciphertext with the given key.</returns> public static byte[] DecryptAesCbc(byte[] ciphertext, byte[] key, byte[] iv = null, bool checkAndRemoveHmac = false) { using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { aes.Key = key; if (iv == null) iv = NullIv; aes.IV = iv; aes.Mode = CipherMode.CBC; // Decrypt the message using (System.IO.MemoryStream plaintextStream = new System.IO.MemoryStream()) { using (CryptoStream cs = new CryptoStream(plaintextStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(ciphertext, 0, ciphertext.Length); } byte[] plaintext = plaintextStream.ToArray(); if (checkAndRemoveHmac) { byte[] hmacProvided = plaintext.Skip(plaintext.Length - Sha256HmacLength).ToArray(); plaintext = plaintext.Take(plaintext.Length - Sha256HmacLength).ToArray(); byte[] hmacCalculated = new HMACSHA256(key).ComputeHash(plaintext); if (!hmacProvided.SequenceEqual(hmacCalculated)) throw new CryptographicException("Message authentication code validation failed."); } return plaintext; } } }
public static string AESDecryptor(string encryptedString, byte[] Key, byte[] IV) { byte[] data = Convert.FromBase64String(encryptedString); AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); string decryptedString = ASCIIEncoding.ASCII.GetString(aes.CreateDecryptor(Key, IV).TransformFinalBlock(data, 0, data.Length)); return decryptedString; }
/// <summary> /// AES解密 /// </summary> /// <param name="str">待解密字符串</param> /// <returns>解密后字符串</returns> public static string AesDecrypt(string str) { try { string key = AES_KEY; byte[] cipherText = Convert.FromBase64String(str); AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.Key = Encoding.UTF8.GetBytes(key); //aes.IV = Encoding.UTF8.GetBytes(key); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; byte[] decryptBytes = new byte[cipherText.Length]; using (MemoryStream ms = new MemoryStream(cipherText)) { using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read)) { cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close(); } } return Encoding.UTF8.GetString(decryptBytes).Replace("\0", ""); //将字符串后尾的'\0'去掉 } catch { } return str; }
public byte[] Unprotect(byte[] protectedData) { byte[] output = null; using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = _key; aesAlg.IV = _IV; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(protectedData)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { byte[] buffer = new byte[8]; using (MemoryStream msOutput = new MemoryStream()) { int read; while ((read = csDecrypt.Read(buffer, 0, buffer.Length)) > 0) { msOutput.Write(buffer, 0, read); } output = msOutput.ToArray(); } } } } return output; }
private Stream DecryptMessage(Stream outputStream, string keyString) { var key = Convert.FromBase64String(keyString); using (var provider = new AesCryptoServiceProvider()) { provider.Key = key; provider.Mode = CipherMode.CBC; provider.Padding = PaddingMode.PKCS7; var ms = new MemoryStream(); outputStream.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); ms.Position = 0; byte[] iv = new byte[16]; ms.Read(iv, 0, 16); provider.IV = iv; Trace.WriteLine("IV decrypt " + provider.IV); var decryptor = provider.CreateDecryptor(provider.Key, provider.IV); return new CryptoStream(ms, decryptor, CryptoStreamMode.Read); } }
/// <summary> /// AES解密 /// </summary> /// <param name="inputString">密钥</param> /// <param name="sKey">向量</param> /// <returns>明文</returns> public static string DecryptAES(string inputString, string sKey = Key) { if (string.IsNullOrWhiteSpace(inputString)) return string.Empty; string plaintext = null; using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.KeySize = 128; aesAlg.Key = ASCIIEncoding.ASCII.GetBytes(sKey); aesAlg.IV = ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(inputString))) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { plaintext = srDecrypt.ReadToEnd(); } } } } return plaintext; }
private static void BobReceiveData(byte[] encryptData) { byte[] rawdata = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; // bit to Byte, need to devide 8 byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) iv[i] = encryptData[i]; using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey)) using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); Console.WriteLine(Convert.ToBase64String(symmKey)); aes.Key = symmKey; aes.IV = iv; } using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptData, nBytes, encryptData.Length - nBytes); cs.Close(); rawdata = ms.ToArray(); Console.WriteLine(Encoding.UTF8.GetString(rawdata)); } aes.Clear(); }
public static string DecryptString(byte[] encryptedString, byte[] encryptionKey) { using (var provider = new AesCryptoServiceProvider()) { provider.Key = encryptionKey; using (var ms = new MemoryStream(encryptedString)) { // Read the first 16 bytes which is the IV. byte[] iv = new byte[16]; ms.Read(iv, 0, 16); provider.IV = iv; using (var decryptor = provider.CreateDecryptor()) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { using (var sr = new StreamReader(cs)) { return sr.ReadToEnd(); } } } } } }
void Button2Click(object sender, EventArgs e) { if (openfile.ShowDialog() == DialogResult.OK) { FileStream fsFileIn = File.OpenRead(textBox2.Text); FileStream fsKeyFile = File.OpenRead(openfile.FileName); FileStream fsFileOut = File.Create(textBox2.Text+"_decrypt"); AesCryptoServiceProvider cryptAlgorithm = new AesCryptoServiceProvider(); BinaryReader brFile = new BinaryReader(fsKeyFile); //textBox1.Text = key.ToString(); StreamWriter writer = File.AppendText(@"key.txt"); writer.WriteLine(key.Length); cryptAlgorithm.Key = key; cryptAlgorithm.IV = iv; CryptoStream csEncrypt = new CryptoStream(fsFileIn, cryptAlgorithm.CreateDecryptor(), CryptoStreamMode.Read); StreamReader srStream = new StreamReader(csEncrypt); StreamWriter swStream = new StreamWriter(fsFileOut); swStream.WriteLine(srStream.ReadToEnd()); swStream.Close(); fsFileOut.Close(); srStream.Close(); } }
// ReSharper disable once InconsistentNaming public byte[] DecryptAES(byte[] dataToDecrypt, byte[] key, byte[] iv) { using (var aes = new AesCryptoServiceProvider()) { _logger.Info("mode: CBC"); aes.Mode = CipherMode.CBC; _logger.Info("padding: PKCS7"); aes.Padding = PaddingMode.PKCS7; aes.Key = key; aes.IV = iv; _logger.Info("create stream"); using (var memoryStream = new MemoryStream()) { var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write); _logger.Info("write data to stream"); cryptoStream.Write(dataToDecrypt, 0, dataToDecrypt.Length); cryptoStream.FlushFinalBlock(); byte[] decryptBytes = memoryStream.ToArray(); return decryptBytes; } } }
public string PerformDecryption(string input) { string output = ""; Aes aes = new AesCryptoServiceProvider(); //DES des = new DESCryptoServiceProvider(); aes.Mode = CipherMode.CBC; try { UTF8Encoding utf8 = new UTF8Encoding(); byte[] ciphertext = Convert.FromBase64String(input); byte[] key = Encoding.ASCII.GetBytes(Security_Key); byte[] IV = Encoding.ASCII.GetBytes(vec); aes.Key = key; aes.IV = IV; ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV); MemoryStream memDecryptStream = new MemoryStream(); memDecryptStream.Write(ciphertext, 0, ciphertext.Length); CryptoStream cs_decrypt = new CryptoStream(memDecryptStream, transform, CryptoStreamMode.Write); byte[] plaintext = memDecryptStream.ToArray(); //output = Encoding.ASCII.GetString(plaintext); output = utf8.GetString(plaintext); } catch (Exception e) { throw e; } return output; }
/// <summary> /// Decrypts a ProcessedPacket. /// </summary> /// <param name="InitializationVector">Initialization vec to be used by AES.</param> /// <param name="PrivateKey">Private key to be used.</param> /// <param name="PubKeyBlob">Public key blob to be used.</param> /// <param name="StreamToDecrypt">The stream to decrypt.</param> /// <returns>A decrypted stream.</returns> public static byte[] DecryptData(byte[] InitializationVector, CngKey PrivateKey, byte[] PubKeyBlob, byte[] DataToDecrypt) { using (var Algorithm = new ECDiffieHellmanCng(PrivateKey)) { using (CngKey PubKey = CngKey.Import(PubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] SymmetricKey = Algorithm.DeriveKeyMaterial(PubKey); Console.WriteLine("DecryptedStream: Created symmetric key with " + "public key information: {0}", Convert.ToBase64String(SymmetricKey)); AesCryptoServiceProvider AES = new AesCryptoServiceProvider(); AES.Key = SymmetricKey; AES.IV = InitializationVector; int NBytes = AES.BlockSize >> 3; //No idea... using (ICryptoTransform Decryptor = AES.CreateDecryptor()) { using (MemoryStream DecryptedStream = new MemoryStream()) { var cs = new CryptoStream(DecryptedStream, Decryptor, CryptoStreamMode.Write); cs.Write(DataToDecrypt, NBytes, DataToDecrypt.Length - NBytes); cs.FlushFinalBlock(); return DecryptedStream.ToArray(); } } } } }
static string DecryptStringFromBytes_Aes(byte[] cipherText, AesCryptoServiceProvider cryptoProvider) { // Check arguments. if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText"); string plaintext = null; // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = cryptoProvider.CreateDecryptor(cryptoProvider.Key, cryptoProvider.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } return plaintext; }
ICryptoTransform CreateDecryptor(byte[] key, byte[] iv) { using (var provider = new AesCryptoServiceProvider {Padding = _paddingMode}) { return provider.CreateDecryptor(key, iv); } }
public static string DecryptAES(byte[] data, byte[] key, byte[] IV) { string retVal = string.Empty; var tsp = new System.Security.Cryptography.AesCryptoServiceProvider(); // default padding and mode tsp.Mode = CipherMode.CBC; tsp.Padding = PaddingMode.PKCS7; // get a crypt transform interface ICryptoTransform ct = tsp.CreateDecryptor(key, IV); // setup a memory stream MemoryStream ms = new MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write)) { // write the string through the crypto stream cs.Write(data, 0, data.Length); // flush cs.FlushFinalBlock(); // convert the data in the memory stream to base64 text ms.Seek(0, SeekOrigin.Begin); var enc = ms.ToArray();//.TakeWhile(c => c > 16).ToArray(); retVal = System.Text.Encoding.ASCII.GetString(enc, 0, enc.Length); } return retVal; }
public static byte[] decrypt(byte[] encrypted, byte[] Key, byte[] IV) { try { byte[] plain; int count; using (MemoryStream mStream = new MemoryStream(encrypted)) { using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider()) { aesProvider.Mode = CipherMode.CBC; using (CryptoStream cryptoStream = new CryptoStream(mStream, aesProvider.CreateDecryptor(Key, IV), CryptoStreamMode.Read)) { plain = new byte[encrypted.Length]; count = cryptoStream.Read(plain, 0, plain.Length); } } } byte[] returnValue = new byte[count]; Array.Copy(plain, returnValue, count); return returnValue; } catch (Exception e) { Logger.log(e.StackTrace); throw e; } }
public static string Decrypt256FromHEX(string keyin, string ivin, string cipherText) { string result = string.Empty; try { byte[] key = Encoding.UTF8.GetBytes(keyin); byte[] iv = Encoding.UTF8.GetBytes(ivin); AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider(); aesProvider.Mode = CipherMode.CBC; aesProvider.Padding = PaddingMode.Zeros; byte[] cipherTextBytesForDecrypt = HexStringToByteArray(cipherText); ICryptoTransform cryptoDecryptor = aesProvider.CreateDecryptor(key, iv); MemoryStream memStreamEncryptData = new MemoryStream(cipherTextBytesForDecrypt); CryptoStream rStream = new CryptoStream(memStreamEncryptData, cryptoDecryptor, CryptoStreamMode.Read); byte[] plainTextBytes = new byte[cipherTextBytesForDecrypt.Length]; int decryptedByteCount = rStream.Read(plainTextBytes, 0, plainTextBytes.Length); memStreamEncryptData.Close(); rStream.Close(); result = Encoding.Default.GetString(plainTextBytes, 0, decryptedByteCount).Replace("\0", ""); } catch (System.Security.Cryptography.CryptographicException) { result = cipherText; } return result; }
void recv(IAsyncResult res) { byte[] received; try { received = serverUdp.EndReceive(res, ref RemoteIp); } catch { return; } //check if connected and check that the ip corresponds if (connected && RemoteIp.Address.ToString() != connectedIp) { //if not just ignore //this avoids that a broadcast can pass return; } data = Encoding.UTF8.GetString(received); Console.WriteLine(data); try { //broadcast if (received[0] == BROADCAST) { //Keyboard.SendKeyUp(0); //TODO: if connected check if client is active Console.WriteLine(RemoteIp.Address.ToString()); sendAlive(); } else if (connected && (received[0] == CONNECTED || received[0] == CONNECTED_PASSWORD)) { if (usingPassword && received[0] == CONNECTED_PASSWORD) { ICryptoTransform decryptor = crypto.CreateDecryptor(crypto.Key, crypto.IV); var origValue = decryptor.TransformFinalBlock(received, 1, received.Length - 1); InputDispatcher.dispatch(origValue); } else if (!usingPassword && received[0] == CONNECTED) { byte[] destfoo = new byte[received.Length - 1]; Array.Copy(received, 1, destfoo, 0, received.Length - 1); InputDispatcher.dispatch(destfoo); } else { //TODO: codice errore sendMessage(RemoteIp.Address.ToString(), CONNECTION_ERROR); } } } catch (Exception e) { Console.Write(e.StackTrace); } serverUdp.BeginReceive(new AsyncCallback(recv), null); }
byte[] Transform(byte[] dataBytes, byte[] passwordBytes, bool encrypt) { /// <summary>Encrypt by using AES-256 algorithm.</summary> // Create an instance of the AES class. var cipher = new System.Security.Cryptography.AesCryptoServiceProvider(); // Calculate salt to make it harder to guess key by using a dictionary attack. var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes); var salt = hmac.ComputeHash(passwordBytes); // Generate Secret Key from the password and salt. // Note: Set number of iterations to 10 in order for JavaScript example to work faster. var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10); // Create a encryptor from the existing SecretKey bytes by using // 32 bytes (256 bits) for the secret key and // 16 bytes (128 bits) for the initialization vector (IV). var key = secretKey.GetBytes(32); var iv = secretKey.GetBytes(16); // Get cryptor as System.Security.Cryptography.ICryptoTransform class. var cryptor = encrypt ? cipher.CreateEncryptor(key, iv) : cipher.CreateDecryptor(key, iv); // Create new Input. var inputBuffer = new byte[dataBytes.Length]; // Copy data bytes to input buffer. System.Buffer.BlockCopy(dataBytes, 0, inputBuffer, 0, inputBuffer.Length); // Create a MemoryStream to hold the output bytes. var stream = new System.IO.MemoryStream(); // Create a CryptoStream through which we are going to be processing our data. var mode = System.Security.Cryptography.CryptoStreamMode.Write; var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode); // Start the crypting process. cryptoStream.Write(inputBuffer, 0, inputBuffer.Length); // Finish crypting. cryptoStream.FlushFinalBlock(); // Convert data from a memoryStream into a byte array. var outputBuffer = stream.ToArray(); // Close both streams. stream.Close(); cryptoStream.Close(); return(outputBuffer); }
private static byte[] _DecryptData(byte[] data, byte[] IV, int bitLength, byte[] passphrase) { var aes = new System.Security.Cryptography.AesCryptoServiceProvider(); var iv = new byte[16]; //always 16 for AES var key = new byte[IV.Length == 7 ? 32 : IV.Length / 8]; //HACK: for "AES-56", convert to AES-256 var ret = new byte[data.Length]; //Pad the IV if necessary Array.Copy(IV, iv, IV.Length); //Derive the key var derived = _DeriveEncryptionKey(bitLength, passphrase); Array.Copy(derived, key, derived.Length); //Decrypt it! aes.CreateDecryptor(key, iv).TransformBlock(data, 0, data.Length, ret, 0); return(ret); }
public static byte[] Decrypt(string privateKey, byte[] data) { using (var aes = new AesCryptoServiceProvider()) { var iv = new byte[128]; var key = new byte[128]; Buffer.BlockCopy(data, 0, iv, 0, 128); Buffer.BlockCopy(data, 128, key, 0, 128); using (var encryptor = aes.CreateDecryptor(Rsa.Decrypt(privateKey, key), Rsa.Decrypt(privateKey, iv))) using (var src = new MemoryStream(data, writable: false)) using (var dst = new MemoryStream()) { src.Seek(256, SeekOrigin.Begin); using (var cs = new CryptoStream(src, encryptor, CryptoStreamMode.Read)) { cs.CopyTo(dst); } return(dst.ToArray()); } } }