CreateEncryptor() public method

public CreateEncryptor ( ) : ICryptoTransform
return ICryptoTransform
Ejemplo n.º 1
0
        public DES(string key, string iv)
        {
            if (key.Length > 8)
            {
                key = key.Substring(0, 8);
            }
            if (iv.Length > 8)
            {
                iv = iv.Substring(0, 8);
            }
            this.Key = this.TextEncode.GetBytes(key);
            this.IV  = this.TextEncode.GetBytes(iv);

            try
            {
                des       = new System.Security.Cryptography.DESCryptoServiceProvider();
                des.Mode  = CipherMode.ECB;
                des.Key   = Key;
                des.IV    = IV;
                decryptor = des.CreateDecryptor(this.Key, this.IV);
                encryptor = des.CreateEncryptor(this.Key, this.IV);
            }
            catch (System.Exception ex)
            {
                log.Error(ex.ToString());
            }
        }
Ejemplo n.º 2
0
        public static string EncryptString(string Value, string parKey)
        {
            mCSP = SetEnc();
            string iv = "PenS8UCVF7s=";
            mCSP.IV = Convert.FromBase64String(iv);
            string key = SetLengthString(parKey.ToString(), 32);
            mCSP.Key = Convert.FromBase64String(key);
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            Byte[] byt = new byte[64];

            try
            {
                ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
                byt = Encoding.UTF8.GetBytes(Value);
                ms = new MemoryStream();
                cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                cs.Close();

                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception Ex)
            {
                throw (new Exception("An error occurred while encrypting string"));
            }
        }
Ejemplo n.º 3
0
		/// <summary>
		/// 加密文件
		/// </summary>
		/// <param name="inName">来源文件</param>
		/// <param name="outName">输出文件</param>
		/// <param name="Algorithm">对称算法</param>
		public static void EncryptFile(string inName, string outName, SymmetricAlgorithm Algorithm)
		{
			FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
			using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
			{
				fout.SetLength(0);

				CryptoStream encStream = new CryptoStream(fout, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);

				//Read from the input file, then encrypt and write to the output file.
				//Create variables to help with read and write.
				long rdlen = 0;					//This is the total number of bytes written.
				int len;						//This is the number of bytes to be written at a time.
				byte[] bin = new byte[FileReadStep];
				while (rdlen < fin.Length)
				{
					len = fin.Read(bin, 0, FileReadStep);
					encStream.Write(bin, 0, len);
					rdlen += len;
				}

				encStream.Close();
				fin.Close();
			}
		}
Ejemplo n.º 4
0
        public virtual byte[] Encrypt(byte[] byteArr)
        {
            ICryptoTransform cTransform = provider.CreateEncryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(byteArr, 0, byteArr.Length);
            return(resultArray);
        }
 private void TestBlock()
 {
     System.Security.Cryptography.ICryptoTransform cryptor;
     WriteLog("DataBytes String: " + System.Text.Encoding.UTF8.GetString(DataBytes));
     // -----------------------------------------------------
     cryptor = Cipher.CreateEncryptor();
     WriteLog("Cipher.FeedbackSize: " + Cipher.FeedbackSize.ToString());
     byte[] encrypted = CipherBlock(cryptor, DataBytes);
     WriteLog("Encrypted Bytes: " + System.BitConverter.ToString(encrypted).Replace("-", ""));
     // -----------------------------------------------------
     //Cipher.Padding = System.Security.Cryptography.PaddingMode.None;
     cryptor = Cipher.CreateDecryptor();
     byte[] decrypted = CipherBlock(cryptor, encrypted);
     // -----------------------------------------------------
     WriteLog("Decrypted String: " + System.Text.Encoding.UTF8.GetString(decrypted));
 }
        /// <summary>
        /// Initialize CipherTextStealingMode with a specific symmetric algorithm
        /// </summary>
        /// <param name="symmetricAlgorithm">The symmetric algorithm</param>
        public CipherTextStealingMode(SymmetricAlgorithm symmetricAlgorithm)
        {
            // in CTS Mode there is no padding
            symmetricAlgorithm.Padding = PaddingMode.None;

            // set the symmetric algorithm's mode to ECB
            // (for single block encryption and decryption)
            symmetricAlgorithm.Mode = CipherMode.ECB;

            // get the symmetric algorithm's block size in bytes
            blockSize = symmetricAlgorithm.BlockSize / 8;
            if (blockSize != symmetricAlgorithm.IV.Length)
            {
                throw new ArgumentException(
                    "The IV size should equal to the block size.");
            }

            // initialize local IV
            iv = symmetricAlgorithm.IV;

            // initialize cipher state using the symmetric algorithms's IV
            cipherState = new byte[blockSize];
            symmetricAlgorithm.IV.CopyTo(cipherState, 0);

            // create encryptor and decryptor
            encryptor = symmetricAlgorithm.CreateEncryptor();
            decryptor = symmetricAlgorithm.CreateDecryptor();
        }
Ejemplo n.º 7
0
        public AES(string key, string iv)
        {
            this.Key = this.TextEncode.GetBytes(key);
            this.IV  = this.TextEncode.GetBytes(iv);

            //System.Security.Cryptography.Aes aes = new System.Security.Cryptography.AesCryptoServiceProvider();
            //aes = new System.Security.Cryptography.AesCryptoServiceProvider();
            aes           = new System.Security.Cryptography.RijndaelManaged();
            aes.Key       = Key;
            aes.IV        = IV;
            aes.KeySize   = 128;
            aes.Mode      = CipherMode.CBC;
            aes.BlockSize = 128;
            aes.Padding   = PaddingMode.Zeros;

            try
            {
                decryptor = aes.CreateDecryptor(this.Key, this.IV);
                encryptor = aes.CreateEncryptor(this.Key, this.IV);
            }
            catch (System.Exception ex)
            {
                log.Error(ex.ToString());
            }
        }
Ejemplo n.º 8
0
        public static string Encryption(string UserID)
        {
            try
            {
                string EncryptedID    = "";
                byte[] clearTextBytes = Encoding.UTF8.GetBytes(UserID);
                System.Security.Cryptography.SymmetricAlgorithm SymmetricAlgorithm = SymmetricAlgorithm.Create();
                MemoryStream MemoryStream = new MemoryStream();

                byte[]       keyByte = Encoding.ASCII.GetBytes(key);
                CryptoStream cs      = new CryptoStream(MemoryStream, SymmetricAlgorithm.CreateEncryptor(keyByte, keyByte), CryptoStreamMode.Write);
                cs.Write(clearTextBytes, 0, clearTextBytes.Length);
                cs.Close();
                #region Convert byte[] to hex string
                byte[] byteArray = MemoryStream.ToArray();
                var    hex       = new StringBuilder(byteArray.Length * 2);
                foreach (var b in byteArray)
                {
                    hex.AppendFormat("{0:x2}", b);
                }
                #endregion
                EncryptedID = hex.ToString();
                return(EncryptedID);
            }
            catch (Exception ex)
            {
                //Utility.LogError(ex, "Reem", "Encryption");
                return(string.Empty);
            }
        }
        public static byte[] Encrypt(string strText, SymmetricAlgorithm key)
        {
            // Create a memory stream.
            MemoryStream ms = new MemoryStream();

            // Create a CryptoStream using the memory stream and the
            // CSP(cryptoserviceprovider) DES key.
            CryptoStream crypstream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);

            // Create a StreamWriter to write a string to the stream.
            StreamWriter sw = new StreamWriter(crypstream);

            // Write the strText to the stream.
            sw.WriteLine(strText);

            // Close the StreamWriter and CryptoStream.
            sw.Close();
            crypstream.Close();

            // Get an array of bytes that represents the memory stream.
            byte[] buffer = ms.ToArray();

            // Close the memory stream.
            ms.Close();

            // Return the encrypted byte array.
            return buffer;
        }
Ejemplo n.º 10
0
        public static byte[] EncryptBytes(SymmetricAlgorithm symAlg, byte[] inBlock)
        {
            ICryptoTransform xfrm = symAlg.CreateEncryptor();
            byte[] outBlock = xfrm.TransformFinalBlock(inBlock, 0, inBlock.Length);

            return outBlock;
        }
Ejemplo n.º 11
0
		private byte[] Encrypt (SymmetricAlgorithm algo, PaddingMode padding, byte[] data) 
		{
			algo.IV = new byte [algo.BlockSize >> 3];
			algo.Mode = CipherMode.CBC;
			algo.Padding = padding;
			ICryptoTransform ct = algo.CreateEncryptor ();
			return ct.TransformFinalBlock (data, 0, data.Length);
		}
Ejemplo n.º 12
0
 private static byte[] EncryptEnvelopeKeyUsingSymmetricKey(SymmetricAlgorithm symmetricAlgorithm, byte[] envelopeKey)
 {
     symmetricAlgorithm.Mode = CipherMode.ECB;
     using (ICryptoTransform encryptor = symmetricAlgorithm.CreateEncryptor())
     {
         return (encryptor.TransformFinalBlock(envelopeKey, 0, envelopeKey.Length));
     }
 }
Ejemplo n.º 13
0
        private static ICryptoTransform CreateCryptoTransform(SymmetricAlgorithm algorithm, CryptoAction action)
        {
            byte[] key = Encoding.ASCII.GetBytes(stringKey);
            byte[] vector = Encoding.ASCII.GetBytes(stringVector);

            return action == CryptoAction.Encrypt
                ? algorithm.CreateEncryptor(key, vector)
                : algorithm.CreateDecryptor(key, vector);
        }
        private byte[] TransformByCryptoStream(SymmetricAlgorithm algorithm, byte[] bytes, bool encrypt)
        {
            algorithm.Clear();

              if (encrypt)
            return TransformByCryptoStream(algorithm.CreateEncryptor(), bytes);
              else
            return TransformByCryptoStream(algorithm.CreateDecryptor(), bytes);
        }
Ejemplo n.º 15
0
        internal WinzipAesCryptoStream(Stream stream, WinzipAesEncryptionData winzipAesEncryptionData, long length)
        {
            this.stream = stream;
            totalBytesLeftToRead = length;

            cipher = CreateCipher(winzipAesEncryptionData);

            var iv = new byte[BLOCK_SIZE_IN_BYTES];
            transform = cipher.CreateEncryptor(winzipAesEncryptionData.KeyBytes, iv);
        }
 public static byte[] Encrypt(SymmetricAlgorithm algorithm,byte[] data)
 {
     using (MemoryStream memory = new MemoryStream())
     {
         using (CryptoStream encrypt = new CryptoStream(memory, algorithm.CreateEncryptor(algorithm.Key, algorithm.IV), CryptoStreamMode.Write))
         {
             encrypt.Write(data, 0, data.Length);
         }
         return memory.ToArray();
     }
 }
Ejemplo n.º 17
0
        /// <summary>
        ///  Encrypts the offline transaction file using the TripleDES cryptography.
        /// </summary>
        /// <param name="Password"></param>
        /// <returns></returns>
        public static string EncryptPassword(string Password)
        {
            string testPwd = string.Empty;

            DES = new TripleDESCryptoServiceProvider();
            byte[] plaintext = Encoding.ASCII.GetBytes(Password);
            DES.Key = ParseKey(desKey);
            DES.IV = GetIV();
            //string decPwd = DecryptPassword("Lw5AEvoSG+7VlrMK+XgmGw==");
            byte[] encrypted = DES.CreateEncryptor().TransformFinalBlock(plaintext, 0, plaintext.Length);
            return Convert.ToBase64String(encrypted);
        }
Ejemplo n.º 18
0
        public CtrModeCryptoTransform(SymmetricAlgorithm algorithm)
        {
            Contract.Requires(algorithm != null);

            algorithm.Mode = CipherMode.ECB;
            algorithm.Padding = PaddingMode.None;

            _algorithm = algorithm;
            _transform = algorithm.CreateEncryptor();
            _iv = algorithm.IV;
            _block = new byte[algorithm.BlockSize >> 3];
        }
Ejemplo n.º 19
0
 public OfbStream(Stream parent, SymmetricAlgorithm algo, CryptoStreamMode mode)
 {
     if (algo.Mode != CipherMode.CBC)
         algo.Mode = CipherMode.CBC;
     if (algo.Padding != PaddingMode.None)
         algo.Padding = PaddingMode.None;
     _parent = parent;
     _cbcStream = new CryptoStream(new ZeroStream(), algo.CreateEncryptor(), CryptoStreamMode.Read);
     _mode = mode;
     _keyStreamBuffer = new byte[algo.BlockSize * Blocks];
     _readWriteBuffer = new byte[_keyStreamBuffer.Length];
 }
Ejemplo n.º 20
0
 public static byte[] Encrypt(SymmetricAlgorithm algorithm, byte[] src)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         using (CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write))
         {
             cs.Write(src, 0, src.Length);
             cs.FlushFinalBlock();
             return ms.ToArray();
         }
     }
 }
Ejemplo n.º 21
0
 private static byte[] Encrypt(string PlainText, SymmetricAlgorithm key)
 {
     MemoryStream ms = new MemoryStream();
     CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);
     StreamWriter sw = new StreamWriter(encStream);
     sw.WriteLine(PlainText);
     sw.Close();
     encStream.Close();
     byte[] buffer = ms.ToArray();
     ms.Close();
     return buffer;
 }
        /// <summary>
        /// Encrypt a given message, provided with key and IV
        /// </summary>
        /// <param name="aesAlg"></param>
        /// <param name="plainText"></param>
        /// <returns></returns>
        static byte[] Encrypt(System.Security.Cryptography.SymmetricAlgorithm aesAlg, string plainText)
        {
            var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (StreamWriter swEncrypt = new StreamWriter(new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)))
                {
                    swEncrypt.Write(plainText);
                }
                return(msEncrypt.ToArray());
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Constructor for AES class that takes byte arrays for the key and IV
        /// </summary>
        /// <param name="key">Cryptographic key</param>
        /// <param name="IV">Cryptographic initialization vector</param>
        public AES(byte[] key, byte[] IV)
        {
            // Initialize AESProvider with AES service provider
            AESProvider = new AesCryptoServiceProvider();

            // Set the key and IV for AESProvider
            AESProvider.Key = key;
            AESProvider.IV = IV;

            // Initialize cryptographic transformers from AESProvider
            encryptor = AESProvider.CreateEncryptor();
            decryptor = AESProvider.CreateDecryptor();
        }
Ejemplo n.º 24
0
        public static byte[] Encrypt(SymmetricAlgorithm aesAlg, string plainText)
        {
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(plainText);
                }
                return msEncrypt.ToArray();
            }
        }
Ejemplo n.º 25
0
        public static string EncodePassword(string source)
        {
            byte[] binarySource = Encoding.UTF8.GetBytes(source);
            System.Security.Cryptography.SymmetricAlgorithm rijn = System.Security.Cryptography.SymmetricAlgorithm.Create();
            MemoryStream ms = new MemoryStream();

            byte[]       rgbIV = Encoding.ASCII.GetBytes("lkjhasdfyuiwhcnt");
            byte[]       key   = Encoding.ASCII.GetBytes("tkw123aaaa");
            CryptoStream cs    = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);

            cs.Write(binarySource, 0, binarySource.Length);
            cs.Close();
            return(Convert.ToBase64String(ms.ToArray()));
        }
        //private const string key1 = "aaaaaaaaaaaaaaaa";
        //private const string key2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        private 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(key1);
            byte[]       key   = Encoding.ASCII.GetBytes(key2);
            CryptoStream cs    = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);
            cs.Close();
            return(Convert.ToBase64String(ms.ToArray()));
        }
		void TestEncryptDecrypt(SymmetricAlgorithm ealg, SymmetricAlgorithm dalg)
		{
			System.Diagnostics.Trace.WriteLine(String.Format("b={0}, k={1}, r={2}", ealg.BlockSize, ealg.KeySize, 
				ealg is ModifiedRijndael ? ((ModifiedRijndael)ealg).Rounds : ((ModifiedRijndael)dalg).Rounds));
			byte[] test = Encoding.ASCII.GetBytes("Testing 123");

			byte[] copy;
			using (ICryptoTransform enc = ealg.CreateEncryptor())
				copy = enc.TransformFinalBlock(test, 0, test.Length);

			using (ICryptoTransform dec = dalg.CreateDecryptor())
				copy = dec.TransformFinalBlock(copy, 0, copy.Length);

			Assert.AreEqual(0, BinaryComparer.Compare(test, copy));
		}
 private byte[] Encrypt(SymmetricAlgorithm symmetricAlgorithm, string original)
 {
     ICryptoTransform encryptor = symmetricAlgorithm.CreateEncryptor(symmetricAlgorithm.Key, symmetricAlgorithm.IV);
     using (MemoryStream msEncrypt = new MemoryStream())
     {
         using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
         {
             using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
             {
                 swEncrypt.Write(original);
             }
             return msEncrypt.ToArray();
         }
     }
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Encrypts given text
 /// </summary>
 /// <param name="text">Text to encrypt</param>
 /// <param name="key">Key, used for encryption</param>
 /// <param name="iv">Initialization Vector</param>
 /// <param name="cryptoProvider">Cryptography algorithm</param>
 /// <returns>Encrypted text</returns>
 public static string Encrypt(string text, byte[] key, byte[] iv, SymmetricAlgorithm cryptoProvider)
 {
     //using (var cryptoProvider = Rijndael.Create())
     using (cryptoProvider)
     using (var memoryStream = new MemoryStream())
     using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, iv), CryptoStreamMode.Write))
     using (var writer = new StreamWriter(cryptoStream))
     {
         writer.Write(text);
         writer.Flush();
         cryptoStream.FlushFinalBlock();
         writer.Flush();
         return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
     }
 }
        public static byte[] Encrypt(string str, SymmetricAlgorithm key)
        {
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cs);

            sw.WriteLine(str);
            sw.Close();
            cs.Close();

            byte[] buffer = ms.ToArray();
            ms.Close();

            return buffer;
        }
        public 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("ryojvlzffalyglrj");
            byte[]       key   = Encoding.ASCII.GetBytes("hcxilkqbbffffeultgbskdmaunivmfuo");
            CryptoStream cs    = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),
                                                  CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);
            cs.Close();

            return(Convert.ToBase64String(ms.ToArray()));
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Constructor for AES class that generates the key and IV from salted passwords
        /// </summary>
        /// <param name="keyPassword">Password used to generate the key</param>
        /// <param name="IVPassword">Password used to generate the IV</param>
        /// <param name="salt">Salt used to secure the passwords</param>
        public AES(string keyPassword, string IVPassword, string salt)
        {
            // Initialize AESProvider with AES service provider
            AESProvider = new AesCryptoServiceProvider();

            // Initialize a hasher with the default MD5 algorithm
            MD5 md5 = System.Security.Cryptography.MD5.Create();

            // Generate the key and IV for AESProvider from hashed, salted passwords
            AESProvider.Key = md5.ComputeHash(UnicodeEncoding.Unicode.GetBytes(keyPassword + salt));
            AESProvider.IV = md5.ComputeHash(UnicodeEncoding.Unicode.GetBytes(IVPassword + salt));

            // Initialize cryptographic transformers from AESProvider
            encryptor = AESProvider.CreateEncryptor();
            decryptor = AESProvider.CreateDecryptor();
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Encrypts the specified plain text.
        /// </summary>
        /// <param name="plainText">The plain text.</param>
        /// <returns>The encrypted value as a byte array.</returns>
        public byte[] Encrypt(byte[] plainText)
        {
            using var stream = new MemoryStream();
            var iv        = Range.GetBytes(_credential.IvSize);
            var encryptor = _algorithm.CreateEncryptor(_credential.GetKey(), iv);

            stream.WriteCipherTextHeader(iv);

            using var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);

            cryptoStream.Write(plainText, 0, plainText.Length);

            stream.Flush();

            return(stream.ToArray());
        }
    /// <summary>Creates a new SymmetricEncryption handler for the passed in
    /// SymmetricAlgorithm.</summary>
    public SymmetricEncryption(SymmetricAlgorithm Algorithm)
    {
      if(Algorithm.Mode != CipherMode.CBC) {
        throw new Exception("SymmetricEncryption requires the symmetric algorithm to use CBC.");
      }

      rng = new RNGCryptoServiceProvider();
      _sa = Algorithm;
      // We take care of PKCS7 padding here due to issues in the underlying implementations...
      _sa.Padding = PaddingMode.None;
      BlockSizeByte = _sa.BlockSize / 8;
      // Match the same size as our Window size...
      _decryptors = new Cache(64);
      _enc_iv = new byte[BlockSizeByte];
      rng.GetBytes(_enc_iv);
      _enc = _sa.CreateEncryptor(_sa.Key, _enc_iv);
      _temp = new byte[BlockSizeByte];
    }
Ejemplo n.º 35
0
        public static string Encrypt(string PlainText)
        {
            byte[] PlainBytes = Encoding.UTF8.GetBytes(PlainText);

            System.Security.Cryptography.SymmetricAlgorithm Alg = System.Security.Cryptography.SymmetricAlgorithm.Create();

            MemoryStream MemStr = new MemoryStream();

            byte[] KeyBytes   = Encoding.ASCII.GetBytes(KEY);
            byte[] KeyIIBytes = Encoding.ASCII.GetBytes(KEYII);

            CryptoStream CryptStr = new CryptoStream(MemStr, Alg.CreateEncryptor(KeyBytes, KeyIIBytes), CryptoStreamMode.Write);

            CryptStr.Write(PlainBytes, 0, PlainText.Length);
            CryptStr.Close();

            return(Convert.ToBase64String(MemStr.ToArray()));
        }
Ejemplo n.º 36
0
        static byte[] Encrypt(object value, object key, bool decrypt, SymmetricAlgorithm alg)
        {
            int size = 0;

            foreach (var legal in alg.LegalKeySizes)
                size = Math.Max(size, legal.MaxSize);

            var k = new byte[size / 8];

            var keyBytes = ToByteArray(key);

            if (keyBytes.Length < k.Length)
            {
                var padded = new byte[k.Length];
                keyBytes.CopyTo(padded, 0);
                keyBytes = padded;
            }

            for (int i = 0; i < k.Length; i++)
                k[i] = keyBytes[i];

            try
            {
                alg.Key = k;
            }
            catch (CryptographicException)
            {
                ErrorLevel = 2;
                return new byte[] { };
            }

            var iv = new byte[alg.IV.Length];
            var hash = new SHA1Managed().ComputeHash(keyBytes, 0, iv.Length);

            for (int i = 0; i < Math.Min(iv.Length, hash.Length); i++)
                iv[i] = hash[i];

            alg.IV = iv;

            var trans = decrypt ? alg.CreateDecryptor() : alg.CreateEncryptor();
            var buffer = ToByteArray(value);
            var result = trans.TransformFinalBlock(buffer, 0, buffer.Length);
            return result;
        }
        private static string Encrypt(string Key, string IV, string DataToEncrypt)
        {
            //Initialize a encoder/decoder that obtains the bytes from a string
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            string EncryptKey = CheckLength(Key);
            string EncryptIV  = CheckLength(IV);
            string Data       = DataToEncrypt.ToString();

            byte[] BKey = new byte[16];
            BKey = ConvertToByte(EncryptKey);
            byte[] BIV = new byte[16];
            BIV = ConvertToByte(EncryptIV);
            byte[] BData = encoder.GetBytes(Data);
            // initialize the Algorithm object.
            System.Security.Cryptography.SymmetricAlgorithm myDES = System.Security.Cryptography.Rijndael.Create();
            //Set the key and IV.
            myDES.Key = BKey;
            myDES.IV  = BIV;
            //myDES.BlockSize = 512;
            // Create an encryptor object...
            ICryptoTransform encrypt = myDES.CreateEncryptor();

            // use the memory stream to store the cipher text...
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            // Use a cryptoSctream to encrypt the Data
            CryptoStream cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write);

            cs.Write(BData, 0, BData.Length);
            // Flush any residule in the final block
            cs.FlushFinalBlock();
            // get the output and trim the '\0' bytes
            byte[] bytOut = ms.GetBuffer();
            int    i      = bytOut.Length - 1;

            while (bytOut[i] == 0)
            {
                i--;
            }

            //Convert to Base64 because there is difficulty when it comes to normal characters using the normal string methods.
            string Result = System.Convert.ToBase64String(bytOut, 0, i + 1);

            return(Result);
        }
Ejemplo n.º 38
0
 private static byte[] EncryptBytes(SymmetricAlgorithm alg, byte[] message)
 {
     if ((message == null) || (message.Length == 0))
     {
         return message;
     }
     if (alg == null)
     {
         throw new ArgumentNullException("alg");
     }
     using (var stream = new MemoryStream())
     using (var encryptor = alg.CreateEncryptor())
     using (var encrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
     {
         encrypt.Write(message, 0, message.Length);
         encrypt.FlushFinalBlock();
         return stream.ToArray();
     }
 }
Ejemplo n.º 39
0
        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("lbavittzoaofgcqz");
            byte[]       key   = Encoding.ASCII.GetBytes("rymnwalaspjdbygwagsxhzzcroywhciu");
            CryptoStream cs    = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),
                                                  CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);

            cs.Close();

            return(Base32Encoding.ToString(ms.ToArray()));
        }
Ejemplo n.º 40
0
        private static byte[] Encrypt(string texto, SymmetricAlgorithm objCript)
        {
            MemoryStream ms = new MemoryStream();

            CryptoStream encStream = new CryptoStream(ms, objCript.CreateEncryptor(), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(encStream, Encoding.UTF8);

            sw.Write(texto);

            sw.Close();
            encStream.Close();

            byte[] buffer = ms.ToArray();

            ms.Close();

            return buffer;
        }
Ejemplo n.º 41
0
        private byte[] EncryptDecrypt(bool encrypt,
            SymmetricAlgorithm alg, byte[] key, byte[] iv, byte[] data)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] rgbKey = new PasswordDeriveBytes(key, _salt).GetBytes(24);
                byte[] rgbIV = new PasswordDeriveBytes(iv, _salt).GetBytes(24);
                using (CryptoStream cs = new CryptoStream(ms,
                    encrypt
                        ? alg.CreateEncryptor(rgbKey, rgbIV)
                        : alg.CreateDecryptor(rgbKey, rgbIV),
                    CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                    cs.Close();

                    return ms.ToArray();
                }
            }
        }
Ejemplo n.º 42
0
        internal WinzipAesCryptoStream(Stream stream, WinzipAesEncryptionData winzipAesEncryptionData, long length,
                                       CryptoMode mode)
        {
            this.mode = mode;
            this.stream = stream;
            totalBytesLeftToRead = length;

            hmac = new HMACSHA1(winzipAesEncryptionData.IvBytes);

            cipher = CreateCipher(winzipAesEncryptionData);

            var iv = new byte[BLOCK_SIZE_IN_BYTES];
            transform = cipher.CreateEncryptor(winzipAesEncryptionData.KeyBytes, iv);

            //if (_mode == CryptoMode.Encrypt)
            //{
            //    _iobuf = new byte[2048];
            //    _PendingWriteBlock = new byte[BLOCK_SIZE_IN_BYTES];
            //}
        }
Ejemplo n.º 43
0
        public static string EncryptString(string ClearText, string iv = "", string key = "")
        {
            iv  = (iv + Röschti).Substring(0, 16);
            key = (key + Bradwurscht).Substring(0, 32);
            byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            MemoryStream ms = new MemoryStream();

            byte[]       ba_rgbIV = Encoding.ASCII.GetBytes(iv);
            byte[]       ba_key   = Encoding.ASCII.GetBytes(key);
            CryptoStream cs       = new CryptoStream(ms, rijn.CreateEncryptor(ba_key, ba_rgbIV), CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);
            cs.Close();
            rijn.Dispose();
            rijn = null;

            return(Convert.ToBase64String(ms.ToArray()));
        }
Ejemplo n.º 44
0
    public static string EncryptString(string ClearText)
    {
        string theKey = SystemInfo.deviceUniqueIdentifier;

        byte[]             salt = new byte[] { 0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c };
        Rfc2898DeriveBytes pdb  = new Rfc2898DeriveBytes(theKey, salt);

        byte[] key = pdb.GetBytes(32);
        byte[] iv  = pdb.GetBytes(16);

        byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, iv), CryptoStreamMode.Write);

        cs.Write(clearTextBytes, 0, clearTextBytes.Length);
        cs.Close();

        return(Convert.ToBase64String(ms.ToArray()));
    }
Ejemplo n.º 45
0
		private string Roundtrip (SymmetricAlgorithm sa, CipherMode mode) 
		{
			sa.Key = GetKey (sa);
			sa.IV = GetIV (sa);
			sa.Mode = mode;

			// two full blocks
			int bs = (sa.BlockSize >> 3) * 2;
			byte[] data = new byte [bs]; // in bytes
			ICryptoTransform enc = sa.CreateEncryptor ();
			byte[] encdata = enc.TransformFinalBlock (data, 0, data.Length);
			string result = BitConverter.ToString (encdata);

			ICryptoTransform dec = sa.CreateDecryptor ();
			byte[] decdata = dec.TransformFinalBlock (encdata, 0, encdata.Length);

			for (int i = 0; i < bs; i++)
				Assert.AreEqual (data [i], decdata [i], i.ToString ());

			return result;
		}
Ejemplo n.º 46
0
        public static string EncryptString(string ClearText)
        {
            string retval;

            byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write))
                {
                    cs.Write(clearTextBytes, 0, clearTextBytes.Length);

                    cs.Close();
                }
                retval = Convert.ToBase64String(ms.ToArray());
            }

            return(retval);
        }
Ejemplo n.º 47
0
        public static string EncryptString(string ClearText, string Key)
        {
            byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);
            //byte[] clearTextBytes = Convert.FromBase64String(ClearText);
            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            MemoryStream ms = new MemoryStream();

            byte[]       rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj");
            byte[]       key   = Encoding.ASCII.GetBytes(CompleteKey32(Key));
            CryptoStream cs    = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),
                                                  CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);

            //ms.Position = 0;
            //StreamReader reader = new StreamReader(ms);
            cs.Close();
            //    return reader.ReadToEnd();
            //return Encoding.UTF8.GetString(ms.ToArray());
            return(Convert.ToBase64String(ms.ToArray()));
        }
Ejemplo n.º 48
0
        public static string Encrypt(string inputText)
        {
            if (String.IsNullOrWhiteSpace(inputText))
            {
                inputText = "";
            }

            byte[] clearTextBytes = Encoding.UTF8.GetBytes(inputText);

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            MemoryStream ms = new MemoryStream();

            byte[]       rgbIV = Encoding.ASCII.GetBytes(rgbIVValue);
            byte[]       key   = Encoding.ASCII.GetBytes(keyValue);
            CryptoStream cs    = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);

            cs.Close();

            return(Convert.ToBase64String(ms.ToArray()));
        }
Ejemplo n.º 49
0
        public static string AESEncrypt(string encryptStr, string encryptKey)
        {
            string result;

            if (string.IsNullOrWhiteSpace(encryptStr))
            {
                result = string.Empty;
            }
            else
            {
                encryptKey = StringHelper.SubString(encryptKey, 32);
                encryptKey = encryptKey.PadRight(32, ' ');
                System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm = System.Security.Cryptography.Rijndael.Create();
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(encryptStr);
                symmetricAlgorithm.Key = System.Text.Encoding.UTF8.GetBytes(encryptKey);
                symmetricAlgorithm.IV  = SecureHelper._aeskeys;
                byte[] inArray = null;
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytes, 0, bytes.Length);
                        cryptoStream.FlushFinalBlock();
                        inArray = memoryStream.ToArray();
                        cryptoStream.Close();
                        memoryStream.Close();
                    }
                }
                result = System.Convert.ToBase64String(inArray);
            }
            return(result);
        }
 public override ICryptoTransform CreateEncryptor()
 {
     return(m_impl.CreateEncryptor());
 }
Ejemplo n.º 51
0
 public static byte[] smethod_1(byte[] byte_0, string string_0)
 {
     System.Array.Resize <byte>(ref byte_0, byte_0.Length + 1);
     byte_0[byte_0.Length - 1] = (byte)new System.Random().Next(0, 255);
     System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm = System.Security.Cryptography.SymmetricAlgorithm.Create();
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     byte[] bytes = System.Text.Encoding.ASCII.GetBytes(string_0);
     byte[] rgbIV = bytes;
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(bytes, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(byte_0, 0, byte_0.Length);
     cryptoStream.Close();
     return(memoryStream.ToArray());
 }