private static byte[] Decrypt(System.Security.Cryptography.SymmetricAlgorithm sa, byte[] baCipher) { if (sa is AES128Managed) { AES128EncryptionFormatter fmt = new AES128EncryptionFormatter((sa as AES128Managed)); return(fmt.Decrypt(baCipher)); } else { return(Transform(sa.CreateDecryptor(), baCipher)); } }
/// <summary> /// Decrypts a Base64 wrapped encrypted data from the provided key. /// </summary> /// <param name="Source">The encrypted base64 data.</param> /// <param name="Key">The key to use for decryption.</param> /// <returns>The original string of data.</returns> public string Decrypt(string Source, string Key) { // convert from Base64 to binary byte[] bytIn = System.Convert.FromBase64String(Source); // create a MemoryStream with the input System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length); byte[] bytKey = GetLegalKey(Key); // set the private key _cryptoservice.Key = bytKey; _cryptoservice.IV = bytKey; // create a Decryptor from the Provider Service instance System.Security.Cryptography.ICryptoTransform decrypto = _cryptoservice.CreateDecryptor(); // create Crypto Stream that transforms a stream using the decryption System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, decrypto, System.Security.Cryptography.CryptoStreamMode.Read); // read out the result from the Crypto Stream System.IO.StreamReader sr = new System.IO.StreamReader(cs); return(sr.ReadToEnd()); }
public static string DecryptString(string EncryptedText) { byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText); MemoryStream ms = new MemoryStream(); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); byte[] rgbIV = Encoding.ASCII.GetBytes("abcdefghijklmnop"); byte[] key = Encoding.ASCII.GetBytes("abcdefghijklmnop"); CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); cs.Close(); return(Encoding.UTF8.GetString(ms.ToArray())); }
public byte[] Decrypt(byte[] cipherText) { int OriginalSize = BitConverter.ToInt32(cipherText, 0); Array.Copy(cipherText, 4, cipherText, 0, cipherText.Length - 4); Array.Resize(ref cipherText, cipherText.Length - 4); byte[] cipherTextWithSalt = new byte[1]; byte[] encSalt = new byte[1]; byte[] origCipherText = new byte[1]; byte[] encIv = new byte[1]; SliceCipherTextIntoParts(cipherText, 16, ref cipherTextWithSalt, ref encIv); SliceCipherTextIntoParts(cipherTextWithSalt, saltSize, ref origCipherText, ref encSalt); LoadSecureParameters(key, encIv, encSalt); System.Security.Cryptography.ICryptoTransform decTransform = algo.CreateDecryptor(); byte[] plainText = decTransform.TransformFinalBlock(origCipherText, 0, origCipherText.Length); Array.Resize(ref plainText, OriginalSize); return(plainText); }
private static object ManageOldVersion(string Version, string FileWhereRead, string Password) { try { switch (Version) { case "v0.0": if (!System.IO.File.Exists(FileWhereRead)) { return(null); } SerializationMode mode = ModeFromFname(FileWhereRead); System.Runtime.Serialization.IFormatter FR = default(System.Runtime.Serialization.IFormatter); if (mode == SerializationMode.Xml) { FR = CreateFormatterForMode(SerializationMode.Xml); } else if (mode == SerializationMode.Binary) { FR = CreateFormatterForMode(SerializationMode.Binary); } else { throw new Exception("Unknown DeSerialization Mode"); } System.IO.FileStream FS = default(System.IO.FileStream); //File Stream System.Security.Cryptography.SymmetricAlgorithm DE = default(System.Security.Cryptography.SymmetricAlgorithm); //Decryption Engine System.Security.Cryptography.CryptoStream DS = null; //Decrypted Stream FS = new System.IO.FileStream(FileWhereRead, FileMode.Open, FileAccess.Read, FileShare.Read); if ((Password != null)) { DE = System.Security.Cryptography.SymmetricAlgorithm.Create(); DS = new System.Security.Cryptography.CryptoStream(FS, DE.CreateDecryptor(GenerateKey(Password, Convert.ToInt32(DE.KeySize / 8)), GenerateKey("Vettore di inizializzazione", 16)), System.Security.Cryptography.CryptoStreamMode.Read); } object Result = null; if ((DS != null)) { Result = FR.Deserialize(DS); FS.Close(); } else { Result = FR.Deserialize(FS); FS.Close(); } //Save in newer version ObjToFile(Result, FileWhereRead, Password); return(Result); } } catch (Exception ex) { ManageReadError(FileWhereRead, ex); } return(null); }
public static object ObjFromFile(string filename, string Password, bool AskForMissingPassword) { object rv = null; lock (ThreadLock) { Exception err = null; filename = System.IO.Path.Combine(LaserGRBL.GrblCore.DataPath, filename); if ((File.Exists(filename + ".bak") & !File.Exists(filename))) { ManageOrphanTmp(filename); } if (File.Exists(filename)) { System.Security.Cryptography.SymmetricAlgorithm EE = null; Stream FinalStream = null; System.Runtime.Serialization.IFormatter SR = default(System.Runtime.Serialization.IFormatter); bool REncrypted = false; bool RCompressed = false; SerializationMode Rmode = default(SerializationMode); string RVersion = null; byte[] Rhash = null; byte[] IV = null; byte[] CypherKey = null; try { //Open a stream on the file for reading (overwrite if exist) and lock the file FinalStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); GetSerializerTag(FinalStream, ref RVersion, ref Rmode, ref REncrypted, ref IV, ref Rhash, ref RCompressed); //Get serializer tag end move stream position //GESTISCI LA VERSIONE CORRENTE if (RVersion == SerializerVersion) { SR = CreateFormatterForMode(Rmode); if (RCompressed) { FinalStream = new System.IO.Compression.DeflateStream(FinalStream, System.IO.Compression.CompressionMode.Decompress); } if (REncrypted && Password == null) { if (AskForMissingPassword) { string NewKey = InputBox.Show(null, "Insert password:"******"Protected file", "", null).Text; if ((NewKey != null)) { FinalStream.Close(); return(ObjFromFile(filename, NewKey, AskForMissingPassword)); } else { throw new MissingPasswordException(filename); } } else { throw new MissingPasswordException(filename); } } //GENERATE KEY AND CRYPTO SERVICE if (REncrypted) { EE = System.Security.Cryptography.SymmetricAlgorithm.Create(); EE.IV = IV; CypherKey = GenerateKey(Password, Convert.ToInt32(EE.KeySize / 8)); } //TEST KEY VALIDITY WITH HASH COMPARE if (REncrypted) { byte[] CurHash = GenerateHash(CypherKey); if (Rhash == null || CurHash == null) { throw new WrongPasswordException(filename); } if (!(Rhash.Length == CurHash.Length)) { throw new WrongPasswordException(filename); } for (int I = 0; I <= Rhash.Length - 1; I++) { if (!(Rhash[I] == CurHash[I])) { throw new WrongPasswordException(filename); } } } if (REncrypted) { FinalStream = new System.Security.Cryptography.CryptoStream(FinalStream, EE.CreateDecryptor(CypherKey, EE.IV), System.Security.Cryptography.CryptoStreamMode.Read); } rv = SR.Deserialize(FinalStream); //READ DATA FinalStream.Close(); } else { FinalStream?.Close(); rv = ManageOldVersion(RVersion, filename, Password); } } catch (Exception ex) { err = ex; System.Diagnostics.Debug.WriteLine(string.Format("Serialization exception in {0} Position {1}", filename, FinalStream.Position)); try { FinalStream?.Close(); } catch { } try { ManageReadError(filename, ex); } catch { } } } else { ; } } return(rv); }
public static string DecryptPAN(string encryptedPAN) { // Log log = new Log(LogPath); System.Security.Cryptography.SymmetricAlgorithm alg = System.Security.Cryptography.TripleDES.Create(); alg.KeySize = 128; alg.Key = Hex2Bin(PEncKey); alg.IV = Hex2Bin(PEncIV); alg.Padding = System.Security.Cryptography.PaddingMode.None; alg.Mode = System.Security.Cryptography.CipherMode.CBC; byte[] buf = new byte[16]; Hex2Bin(encryptedPAN, buf); try { MemoryStream outs = new MemoryStream(); System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(outs, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write); encStream.Write(buf, 0, 16); encStream.FlushFinalBlock(); Buffer.BlockCopy(outs.GetBuffer(), 0, buf, 0, 16); encStream.Close(); return(Bin2Hex(buf).Trim('A')); } catch { } return(null); }
/// <summary> /// /// </summary> /// <param name="secretKey"></param> /// <param name="cypheredData"></param> /// <returns></returns> public static ProtectedMemory DecryptData(ProtectedString secretKey, ProtectedMemory cypheredData) { ProtectedMemory returnValue = null; System.Byte[] encryptedData = null; System.Byte[] ivData = null; #region Check protection of secret key if (!secretKey.IsProtected) { throw new UnsecureException(); } #endregion #region Check protection of cyphered data if (!cypheredData.IsProtected) { throw new UnsecureException(); } #endregion #region Split cyphered data // Unprotect cyphered memory cypheredData.Unprotect(); // extract iv data (IV length is static => 16) ivData = new System.Byte[16]; System.Array.Copy(cypheredData.GetBytes(), 0, ivData, 0, 16); // extract encrypted data encryptedData = new System.Byte[cypheredData.SizeInByte - 16]; System.Array.Copy(cypheredData.GetBytes(), 16, encryptedData, 0, (cypheredData.SizeInByte - 16)); // Reprotect cyphered memory cypheredData.Protect(); #endregion #region Prepare encryption provider // Unprotect memory containing secret key secretKey.Unprotect(); // Create encryption provider System.Security.Cryptography.SymmetricAlgorithm encryptionProvider = System.Security.Cryptography.Aes.Create(); encryptionProvider.Mode = System.Security.Cryptography.CipherMode.CBC; encryptionProvider.Key = secretKey.GetBytes(); encryptionProvider.IV = ivData; // Reprotect memory containing secret key secretKey.Protect(); #endregion // Create decryptor System.Security.Cryptography.ICryptoTransform decryptor = encryptionProvider.CreateDecryptor(encryptionProvider.Key, encryptionProvider.IV); // Create handle to memory of encrypted data using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(encryptedData)) { // Create handle for data decryption; data streamed by this stream will be automatically decrypted using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read)) { // Create handle to read data of a strea,; data readed by this stream will be automatically decrypted using (System.IO.StreamReader streamReader = new System.IO.StreamReader(cryptoStream)) { #region Save plain data in protected memory // Save plain data in temp buffer System.String plainData = streamReader.ReadToEnd(); // Create protected memory for plain data returnValue = new ProtectedMemory(plainData.Length); // Unprotect memory for plain data returnValue.Unprotect(); // Copy plain data in encrypted memory for (System.Int32 i = 0; i < plainData.Length; i++) { returnValue.SetByte(i, (System.Byte)plainData[i]); } // Reprotect memory with plain data returnValue.Protect(); // Save erase temp buffer plainData = null; System.GC.Collect(); #endregion } } } // Dispose decryptor decryptor.Dispose(); // Dispose encryption provider encryptionProvider.Dispose(); return(returnValue); }
public static MemoryStream DecryptStream(string key, byte[] content) { using (MemoryStream ms = new MemoryStream()) { System.Security.Cryptography.SymmetricAlgorithm rijn = System.Security.Cryptography.SymmetricAlgorithm.Create(); byte[] rgbIV = Encoding.ASCII.GetBytes("polychorepolycho"); byte[] rgbKey = Encoding.ASCII.GetBytes(key); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, rijn.CreateDecryptor(rgbKey, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(content, 0, content.Length); cs.Close(); return(ms); } }
public string Decrypt(string inVal) { try { System.IO.MemoryStream MSout = new System.IO.MemoryStream(); byte[] bin; byte[] retArr; //Create variables to help with read and write. System.Security.Cryptography.SymmetricAlgorithm encAlg = System.Security.Cryptography.SymmetricAlgorithm.Create("RC2"); System.Security.Cryptography.CryptoStream DecStream = new System.Security.Cryptography.CryptoStream(MSout, encAlg.CreateDecryptor(bKey, bIV), System.Security.Cryptography.CryptoStreamMode.Write); bin = DeformatHexString(inVal); DecStream.Write(bin, 0, bin.Length); DecStream.Close(); retArr = MSout.ToArray(); MSout.Close(); System.Text.ASCIIEncoding getStr = new ASCIIEncoding(); return(getStr.GetString(retArr)); } catch (System.Exception ex) { // Log Error throw ex; } }
public override ICryptoTransform CreateDecryptingTransform() { return(new CryptoTransformWrapper(_symmetricAlgorithm.CreateDecryptor())); }