/// <summary> /// Encrypts a source string and returns a Base64 result. /// </summary> /// <param name="Source">The source string to encrypt.</param> /// <param name="Key">A key to use for the encryption.</param> /// <returns>A Base64 string of the encrypted information.</returns> public string Encrypt(string Source, string Key) { byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(Source); // create a MemoryStream so that the process can be done without I/O files System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] bytKey = GetLegalKey(Key); // set the private key _cryptoservice.Key = bytKey; _cryptoservice.IV = bytKey; // create an Encryptor from the Provider Service instance System.Security.Cryptography.ICryptoTransform encrypto = _cryptoservice.CreateEncryptor(); // create Crypto Stream that transforms a stream using the encryption System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encrypto, System.Security.Cryptography.CryptoStreamMode.Write); // write out encrypted content into MemoryStream cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); byte[] bytOut = ms.GetBuffer(); // convert into Base64 so that the result can be used in xml return(System.Convert.ToBase64String(bytOut, 0, (int)ms.Length)); }
public byte[] Encrypt(byte[] plainText) { int OriginalSize = plainText.Length; System.Security.Cryptography.ICryptoTransform encTransform = algo.CreateEncryptor(); byte[] result = ConcatDataToCipherText(ConcatDataToCipherText(encTransform.TransformFinalBlock(plainText, 0, plainText.Length), salt), algo.IV); List <byte> ret = new List <byte>(); ret.AddRange(BitConverter.GetBytes(OriginalSize)); ret.AddRange(result); return(ret.ToArray()); }
public static string EncryptString(string ClearText) { byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); MemoryStream ms = new MemoryStream(); byte[] rgbIV = Encoding.ASCII.GetBytes("abcdefghijklmnop"); byte[] key = Encoding.ASCII.GetBytes("abcdefghijklmnop"); CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(clearTextBytes, 0, clearTextBytes.Length); cs.Close(); return(Convert.ToBase64String(ms.ToArray())); }
private static byte[] Encrypt(System.Security.Cryptography.SymmetricAlgorithm sa, byte[] baPlain) { if (sa is AES128Managed) { AES128EncryptionFormatter fmt = new AES128EncryptionFormatter((sa as AES128Managed)); return(fmt.Encrypt(baPlain)); } //else if (sa is TripleDES) //{ // TripleDESEncryptionFormatter fmt = new TripleDESEncryptionFormatter((sa as TripleDES)); // return fmt.Encrypt(baPlain); //} else { return(Transform(sa.CreateEncryptor(), baPlain)); } }
public static bool ObjToFile(object ObjectToSave, string filename, SerializationMode SerializeMode, string Password, bool Compression) { lock (ThreadLock) { Exception err = null; System.Security.Cryptography.SymmetricAlgorithm EE = null; Stream FinalStream = null; System.Runtime.Serialization.IFormatter SR = default(System.Runtime.Serialization.IFormatter); byte[] IV = null; byte[] CypherKey = null; string tmpfile = null; string backupfile = null; try { filename = System.IO.Path.Combine(LaserGRBL.GrblCore.DataPath, filename); tmpfile = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + "tmp_" + System.IO.Path.GetRandomFileName(); backupfile = filename + ".bak"; if (SerializeMode == SerializationMode.Auto) { SerializeMode = ModeFromFname(filename); } SR = CreateFormatterForMode(SerializeMode); //CREATE FORMATTER FinalStream = new FileStream(tmpfile, FileMode.CreateNew, FileAccess.Write, FileShare.None); //Open a stream on the file for writing and lock the file if ((Password != null)) { EE = System.Security.Cryptography.SymmetricAlgorithm.Create(); IV = EE.IV; CypherKey = GenerateKey(Password, Convert.ToInt32(EE.KeySize / 8)); } WriteSerializerTag(FinalStream, SerializerVersion, SerializeMode, CypherKey, IV, Compression); if ((Password != null)) { FinalStream = new System.Security.Cryptography.CryptoStream(FinalStream, EE.CreateEncryptor(CypherKey, EE.IV), System.Security.Cryptography.CryptoStreamMode.Write); } if (Compression) { FinalStream = new System.IO.Compression.DeflateStream(FinalStream, System.IO.Compression.CompressionMode.Compress); } SR.Serialize(FinalStream, ObjectToSave); //WRITE DATA FinalStream.Flush(); //If TypeOf (SS) Is System.Security.Cryptography.CryptoStream Then DirectCast(SS, System.Security.Cryptography.CryptoStream).FlushFinalBlock() FinalStream.Close(); //CLOSE STREAM if ((System.IO.File.Exists(filename))) { System.IO.File.Replace(tmpfile, filename, backupfile, true); System.IO.File.Delete(backupfile); } else { System.IO.File.Move(tmpfile, filename); } return(true); } catch (Exception ex) { err = ex; try { FinalStream?.Close(); } catch { } try { ManageWriteError(ObjectToSave, filename, ex); } catch { } } finally { //evita di lasciare in giro file temporanei if ((tmpfile != null) && System.IO.File.Exists(tmpfile)) { try { System.IO.File.Delete(tmpfile); } catch { } } } } return(false); }
public static string EncryptPAN(string PAN) { 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; try { MemoryStream outs = new MemoryStream(); System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(outs, alg.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write); encStream.Write(Hex2Bin(PAN.PadRight(32, 'A')), 0, 16); encStream.FlushFinalBlock(); byte[] buf = new byte[16]; Buffer.BlockCopy(outs.GetBuffer(), 0, buf, 0, 16); encStream.Close(); return(Bin2Hex(buf)); } catch { } return(null); }
/// <summary> /// /// </summary> /// <param name="secretKey"></param> /// <param name="plainData"></param> /// <returns></returns> public static ProtectedMemory EncryptData(ProtectedString secretKey, ProtectedMemory plainData) { ProtectedMemory returnValue = null; System.Byte[] encryptedData = null; #region Check protection of secret key if (!secretKey.IsProtected) { throw new UnsecureException(); } #endregion #region Check protection of plain data if (!plainData.IsProtected) { throw new UnsecureException(); } #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.GenerateIV(); // Reprotect memory containing secret key secretKey.Protect(); #endregion // Create encryptor System.Security.Cryptography.ICryptoTransform encryptor = encryptionProvider.CreateEncryptor(encryptionProvider.Key, encryptionProvider.IV); // Create handle to stream data into memory using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { // Write IV to temp memory (IV length is static => 16 ) memoryStream.Write(encryptionProvider.IV, 0, 16); // Create handle for data encryption; data streamed to this stream will be automatically encrypted and streamed to memory using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { // Create handle to write data to a stream; data written to this stream will be automatically encrypted and streamed to memory using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(cryptoStream)) { // Unprotect plain data plainData.Unprotect(); #region Write and encrypt plain data to temp memory foreach (System.Byte b in plainData.GetBytes()) { streamWriter.Write((System.Char)b); } #endregion // Reprotect plain data plainData.Protect(); } } // Save content of temp memory in temp buffer encryptedData = memoryStream.ToArray(); } // Dispose encryptor encryptor.Dispose(); // Dispose encryption provider encryptionProvider.Dispose(); #region Save cyphered data in protected memory // Create protected memory for cyphered data returnValue = new ProtectedMemory(encryptedData.Length); // Unprotect memory for cyphered data returnValue.Unprotect(); // Copy cyphered data in encrypted memory for (System.Int32 i = 0; i < encryptedData.Length; i++) { returnValue.SetByte(i, encryptedData[i]); } // Reprotect memory with cyphered data returnValue.Protect(); #endregion return(returnValue); }
public static MemoryStream EncryptStream(string key, byte[] content) { System.Security.Cryptography.SymmetricAlgorithm rijn = System.Security.Cryptography.SymmetricAlgorithm.Create(); using (MemoryStream ms = new MemoryStream()) { byte[] rgbIV = Encoding.ASCII.GetBytes("polychorepolycho"); byte[] rgbKey = Encoding.ASCII.GetBytes(key); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, rijn.CreateEncryptor(rgbKey, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(content, 0, content.Length); cs.Close(); return(ms); } }
public string Encrypt(string inVal) { try { //System.Text.Encoder encoding; //System.Text.Encoder encoding = System.Text.Encoding.ASCII System.IO.MemoryStream MSout = new System.IO.MemoryStream(); //Create variables to help with read and write. byte[] bin; //This is intermediate storage for the encryption. System.Security.Cryptography.SymmetricAlgorithm encAlg = System.Security.Cryptography.SymmetricAlgorithm.Create("RC2"); System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(MSout, encAlg.CreateEncryptor(bKey, bIV), System.Security.Cryptography.CryptoStreamMode.Write); bin = ConvertStringToByteArray(inVal); encStream.Write(bin, 0, inVal.Length); encStream.Close(); bin = MSout.ToArray(); MSout.Close(); return(formatHexString(bin)); } catch (System.Exception ex) { // Log Error throw ex; } }
public override ICryptoTransform CreateEncryptingTransform() { return(new CryptoTransformWrapper(_symmetricAlgorithm.CreateEncryptor())); }