Exemplo n.º 1
1
        public AesDecoderStream(Stream input, byte[] info, IPasswordProvider pass, long limit)
        {
            mStream = input;
            mLimit = limit;

            // The 7z AES encoder/decoder classes do not perform padding, instead they require the input stream to provide a multiple of 16 bytes.
            // If the exception below is thrown this means the 7z file is either corrupt or a newer 7z version has been published and we haven't updated yet.
            if (((uint)input.Length & 15) != 0)
                throw new NotSupportedException("7z requires AES streams to be properly padded.");

            int numCyclesPower;
            byte[] salt, seed;
            Init(info, out numCyclesPower, out salt, out seed);

            byte[] password = Encoding.Unicode.GetBytes(pass.CryptoGetTextPassword());
            byte[] key = InitKey(numCyclesPower, salt, password);

            using (var aes = Aes.Create())
            {
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.None;
                mDecoder = aes.CreateDecryptor(key, seed);
            }

            mBuffer = new byte[4 << 10];
        }
Exemplo n.º 2
1
 public AuthenticationHelper()
 {
     var rm = new RijndaelManaged();
     encryptor = rm.CreateEncryptor(key, vector);
     decryptor = rm.CreateDecryptor(key, vector);
     encoder = new UTF8Encoding();
 }
Exemplo n.º 3
1
 public AesEncryption(byte[] Key, byte[] Vector)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     this.EncryptorTransform = rijndaelManaged.CreateEncryptor(Key, Vector);
     this.DecryptorTransform = rijndaelManaged.CreateDecryptor(Key, Vector);
     this.UTFEncoder = new UTF8Encoding();
 }
Exemplo n.º 4
1
 // Methods
 public EncryptionHelper()
 {
     RijndaelManaged managed = new RijndaelManaged();
     this.EncryptorTransform = managed.CreateEncryptor(this.Key, this.Vector);
     this.DecryptorTransform = managed.CreateDecryptor(this.Key, this.Vector);
     this.UTFEncoder = new UTF8Encoding();
 }
Exemplo n.º 5
0
        public static void Init(GraphicsDevice g, SpriteBatch s, ContentManager c)
        {
            graphics = g;
            spriteBatch = s;
            content = c;
            font = content.Load<SpriteFont>("font\\CommonFont");

            Random rand = new Random(13562538);
            AesManaged aes = new AesManaged();
            byte[] b_key = new byte[32];
            byte[] b_iv = new byte[16];
            rand.NextBytes(b_key);
            rand.NextBytes(b_iv);
            aes.Key = b_key;
            aes.IV = b_iv;
            decryptor = aes.CreateDecryptor();

            state = State.Free;
            waitall = false;
            sleepTime = TimeSpan.Zero;

            charas = new Dictionary<string, TalkChara>();
            t_balloon = content.Load<Texture2D>("img\\face\\balloon");
            t_balloon2 = content.Load<Texture2D>("img\\face\\balloon2");
        }
Exemplo n.º 6
0
            /// <summary>
            /// Process the data with CryptoStream
            /// </summary>
            protected byte[] Process(byte[] data, int startIndex, int count, ICryptoTransform cryptor)
            {
                //
                // the memory stream granularity must match the block size
                // of the current cryptographic operation
                //
                int capacity = count;
                int mod = count % algorithm.BlockSize;
                if (mod > 0)
                {
                    capacity += (algorithm.BlockSize - mod);
                }

                MemoryStream memoryStream = new MemoryStream(capacity);

                CryptoStream cryptoStream = new CryptoStream(
                    memoryStream,
                    cryptor,
                    CryptoStreamMode.Write);

                cryptoStream.Write(data, startIndex, count);
                cryptoStream.FlushFinalBlock();

                cryptoStream.Close();
                cryptoStream = null;

                cryptor.Dispose();
                cryptor = null;

                return memoryStream.ToArray();
            }
Exemplo n.º 7
0
 public EncryptionFuncs()
 {
     var rm = new RijndaelManaged();
     encryptor = rm.CreateEncryptor(key, vector);
     decryptor = rm.CreateDecryptor(key, vector);
     encoder = new UTF8Encoding();
 }
Exemplo n.º 8
0
 public SimplerAES()
 {
     var rm = new RijndaelManaged();
     _encryptor = rm.CreateEncryptor(KEY, Vector);
     _decryptor = rm.CreateDecryptor(KEY, Vector);
     _encoder = new UTF8Encoding();
 }
        protected static byte[] ExecuteCryptoServiceProvider(byte[] data, ICryptoTransform cryptoTransform)
        {
            byte[] inArray;
            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream,
                    cryptoTransform, CryptoStreamMode.Write))
                {
                    try
                    {
                        cryptoStream.Write(data, 0, data.Length);
                        cryptoStream.FlushFinalBlock();
                    }
                    catch (Exception ex)
                    {
                        throw new CustomException<CryptoServiceExceptionArgs>(
                            new CryptoServiceExceptionArgs("Error while writing encrypted data to the stream: \n" +
                                                           ex.Message));
                    }
                    finally
                    {
                        cryptoStream.Dispose();
                    }
                }

                inArray = memoryStream.ToArray();
            }

            return inArray;
        }
        public NoPaddingTransformWrapper(ICryptoTransform symmetricAlgoTransform)
        {
            if (symmetricAlgoTransform == null)
                throw new ArgumentNullException("symmetricAlgoTransform");

            m_Transform = symmetricAlgoTransform;
        }
Exemplo n.º 11
0
 public AnvilEncryptor(byte[] k, byte[] v)
 {
     RijndaelManaged rm = new RijndaelManaged();
     encryptor = rm.CreateEncryptor(k, v);
     decryptor = rm.CreateDecryptor(k, v);
     encoder = new UTF8Encoding();
 }
Exemplo n.º 12
0
 public SimplerAES()
 {
     RijndaelManaged rm = new RijndaelManaged();
     encryptor = rm.CreateEncryptor(key, vector);
     decryptor = rm.CreateDecryptor(key, vector);
     encoder = new UTF8Encoding();
 }
Exemplo n.º 13
0
 public void SetUp()
 {
     using ( AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider() ) {
         m_Encryptor = aesAlg.CreateEncryptor();
         m_Decryptor = aesAlg.CreateDecryptor();
     }
 }
Exemplo n.º 14
0
 public SimpleAES(byte[] encryptionKey, byte[] encryptionVector)
 {
     var rm = new RijndaelManaged();
     _encryptor = rm.CreateEncryptor(encryptionKey, encryptionVector);
     _decryptor = rm.CreateDecryptor(encryptionKey, encryptionVector);
     _encoder = new UTF8Encoding();
 }
Exemplo n.º 15
0
	public AES()
	{
		RijndaelManaged rm = new RijndaelManaged();
		_encryptor = rm.CreateEncryptor(_key, _vector);
		_decryptor = rm.CreateDecryptor(_key, _vector);
		encoder = new UTF8Encoding();
	}
 public AesEncryption(byte[] key, byte[] vector)
 {
     var rm = new RijndaelManaged();
     _encryptor = rm.CreateEncryptor(key, vector);
     _decryptor = rm.CreateDecryptor(key, vector);
     _encoder = new UTF8Encoding();
 }
 public CryptographyService()
 {
     var rm = new RijndaelManaged();
     _encryptor = rm.CreateEncryptor(Key, Vector);
     _decryptor = rm.CreateDecryptor(Key, Vector);
     _encoder = new UTF8Encoding();
 }
Exemplo n.º 18
0
		public CryptoStream (Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
		{
			if ((mode == CryptoStreamMode.Read) && (!stream.CanRead)) {
				throw new ArgumentException (
					Locale.GetText ("Can't read on stream"));
			}
			if ((mode == CryptoStreamMode.Write) && (!stream.CanWrite)) {
				throw new ArgumentException (
					Locale.GetText ("Can't write on stream"));
			}
			_stream = stream;
			_transform = transform;
			_mode = mode;
			_disposed = false;
			if (transform != null) {
				if (mode == CryptoStreamMode.Read) {
					_currentBlock = new byte [transform.InputBlockSize];
					_workingBlock = new byte [transform.InputBlockSize];
				}
				else if (mode == CryptoStreamMode.Write) {
					_currentBlock = new byte [transform.OutputBlockSize];
					_workingBlock = new byte [transform.OutputBlockSize];
				}
			}
		}
Exemplo n.º 19
0
 public EncryptionHelper()
 {
     var rijndaelManaged = new RijndaelManaged();
     _encryptor = rijndaelManaged.CreateEncryptor(Key, Vector);
     _decryptor = rijndaelManaged.CreateDecryptor(Key, Vector);
     _utfEncoding = new UTF8Encoding();
 }
		public void CheckCBC(ICryptoTransform encryptor, ICryptoTransform decryptor, 
					   byte[] plaintext, byte[] expected) 
		{
	
			if ((plaintext.Length % encryptor.InputBlockSize) != 0) {
				throw new ArgumentException("Must have complete blocks");
			}
	
			byte[] ciphertext = new byte[plaintext.Length];
			for (int i=0; i < plaintext.Length; i += encryptor.InputBlockSize) {
				encryptor.TransformBlock(plaintext, i, encryptor.InputBlockSize, ciphertext, i);
			}
	
			for (int i=0; i<32; i++) {
				AssertEquals("CBC-" + i, expected[i], ciphertext[i]);
			}
	
			byte[] roundtrip = new byte[plaintext.Length];
			for (int i=0; i < ciphertext.Length; i += decryptor.InputBlockSize) {
				decryptor.TransformBlock(ciphertext, i, decryptor.InputBlockSize, roundtrip, i);
			}
	
			for (int i=0; i<32; i++) {
				AssertEquals("CBC-rt-" + i, roundtrip[i], plaintext[i]);
			}
	
		}
Exemplo n.º 21
0
 public ZipAESTransform(string key, byte[] saltBytes, int blockSize, bool writeMode)
 {
     if ((blockSize != ENCRYPT_BLOCK) && (blockSize != 0x20))
     {
         throw new Exception("Invalid blocksize " + blockSize + ". Must be 16 or 32.");
     }
     if (saltBytes.Length != (blockSize / PWD_VER_LENGTH))
     {
         throw new Exception(string.Concat(new object[] { "Invalid salt len. Must be ", blockSize / 2, " for blocksize ", blockSize }));
     }
     _blockSize = blockSize;
     _encryptBuffer = new byte[_blockSize];
     _encrPos = ENCRYPT_BLOCK;
     Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(key, saltBytes, KEY_ROUNDS);
     RijndaelManaged managed = new RijndaelManaged
     {
         Mode = CipherMode.ECB
     };
     _counterNonce = new byte[_blockSize];
     byte[] rgbKey = bytes.GetBytes(_blockSize);
     byte[] rgbIV = bytes.GetBytes(_blockSize);
     _encryptor = managed.CreateEncryptor(rgbKey, rgbIV);
     _pwdVerifier = bytes.GetBytes(2);
     _hmacsha1 = new HMACSHA1(rgbIV);
     _writeMode = writeMode;
 }
Exemplo n.º 22
0
        public override void init(int mode, byte[] key, byte[] iv)
        {
            m_mode = mode;
            m_rijndael = new RijndaelManaged();
            m_rijndael.Mode = CipherMode.CBC;
            m_rijndael.Padding = PaddingMode.None;

            byte[] tmp;
            if (iv.Length > m_ivsize)
            {
                tmp = new byte[m_ivsize];
                Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (key.Length > m_bsize)
            {
                tmp = new byte[m_bsize];
                Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }

            try
            {
                m_cipher = (mode == ENCRYPT_MODE
                    ? m_rijndael.CreateEncryptor(key, iv)
                    : m_rijndael.CreateDecryptor(key, iv)
                    );
            }
            catch (Exception)
            {
                m_cipher = null;
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// Initializes the static members of the EncryptionUtility class.
 /// </summary>
 static EncryptionUtility()
 {
     EncryptionUtilitySectionHandler encryptionUtilitySectionHandler = (EncryptionUtilitySectionHandler) ConfigurationManager.GetSection("sharpCore/encryption");
     encryptor = encryptionUtilitySectionHandler.SymmetricAlgorithm.CreateEncryptor(encryptionUtilitySectionHandler.Key, encryptionUtilitySectionHandler.InitializationVector);
     decryptor = encryptionUtilitySectionHandler.SymmetricAlgorithm.CreateDecryptor(encryptionUtilitySectionHandler.Key, encryptionUtilitySectionHandler.InitializationVector);
     encoding = encryptionUtilitySectionHandler.Encoding;
 }
Exemplo n.º 24
0
        public override void init(int mode, byte[] key, byte[] iv)
        {
            m_triDes = new TripleDESCryptoServiceProvider();
            m_triDes.Mode = CipherMode.CBC;
            m_triDes.Padding = PaddingMode.None;

            byte[] tmp;
            if (iv.Length > m_ivsize)
            {
                tmp = new byte[m_ivsize];
                Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (key.Length > m_bsize)
            {
                tmp = new byte[m_bsize];
                Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }

            try
            {
                m_cipher = (mode == ENCRYPT_MODE
                    ? m_triDes.CreateEncryptor(key, iv)
                    : m_triDes.CreateDecryptor(key, iv)
                    );
            }
            catch (Exception)
            {
                m_cipher = null;
            }
        }
Exemplo n.º 25
0
        public InteractiveCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, int bufferSizeInBlocks)
            : base(stream)
        {
            if (bufferSizeInBlocks < 0)
            {
                throw new ArgumentOutOfRangeException("bufferSizeInBlocks", bufferSizeInBlocks, "BufferSize can't be less than 0");
            }

            if (bufferSizeInBlocks > 255)
            {
                bufferSizeInBlocks = 255;
            }

            this.mode = mode;

            this.transform = transform;

            this.writeBuffer = new byte[2 + transform.InputBlockSize * bufferSizeInBlocks];
            this.writeBlockBuffer = new byte[transform.OutputBlockSize];

            this.readPreBuffer = new byte[transform.OutputBlockSize * 5];
            this.readBuffer = new byte[transform.InputBlockSize * 5];

            this.writeBufferCount = 2;
            this.readBufferCount = 0;
            this.readBufferIndex = 0;
        }
Exemplo n.º 26
0
        private static byte[] PerformRandomizedTest(ICryptoTransform expectedTransform, ICryptoTransform actualTransform,
                                                    byte[] vector)
        {
            using (var msExpected = new MemoryStream())
            using (var msActual = new MemoryStream())
            {
                using (var csExpected = new CryptoStream(msExpected, expectedTransform, CryptoStreamMode.Write))
                using (var csActual = new CryptoStream(msActual, actualTransform, CryptoStreamMode.Write))
                {
                    byte[] bufferToTransform = vector;
                    if (bufferToTransform == null)
                    {
                        int randomBytesToGenerate = _WeakRandom.Next(0, MaxEncryptedSizeInBytes);
                        bufferToTransform = new byte[randomBytesToGenerate];
                        _WeakRandom.NextBytes(bufferToTransform);
                    }
                    csExpected.Write(bufferToTransform, 0, bufferToTransform.Length);
                    csActual.Write(bufferToTransform, 0, bufferToTransform.Length);
                }

                byte[] expectedTransformResult = msExpected.ToArray();
                byte[] actualTransformResult = msActual.ToArray();

                ByteUtilities.AssertBytesEqual(expectedTransformResult, actualTransformResult);

                return expectedTransformResult;
            }
        }
Exemplo n.º 27
0
 public ZipAESTransform(string key, byte[] saltBytes, int blockSize, bool writeMode)
 {
     if ((blockSize != 0x10) && (blockSize != 0x20))
     {
         throw new Exception("Invalid blocksize " + blockSize + ". Must be 16 or 32.");
     }
     if (saltBytes.Length != (blockSize / 2))
     {
         throw new Exception(string.Concat(new object[] { "Invalid salt len. Must be ", blockSize / 2, " for blocksize ", blockSize }));
     }
     this._blockSize = blockSize;
     this._encryptBuffer = new byte[this._blockSize];
     this._encrPos = 0x10;
     Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(key, saltBytes, 0x3e8);
     RijndaelManaged managed = new RijndaelManaged {
         Mode = CipherMode.ECB
     };
     this._counterNonce = new byte[this._blockSize];
     byte[] rgbKey = bytes.GetBytes(this._blockSize);
     byte[] rgbIV = bytes.GetBytes(this._blockSize);
     this._encryptor = managed.CreateEncryptor(rgbKey, rgbIV);
     this._pwdVerifier = bytes.GetBytes(2);
     this._hmacsha1 = new HMACSHA1(rgbIV);
     this._writeMode = writeMode;
 }
Exemplo n.º 28
0
		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="key">Password string</param>
		/// <param name="saltBytes">Random bytes, length depends on encryption strength.
		/// 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes.</param>
		/// <param name="blockSize">The encryption strength, in bytes eg 16 for 128 bits.</param>
		/// <param name="writeMode">True when creating a zip, false when reading. For the AuthCode.</param>
		///
		public ZipAESTransform(string key, byte[] saltBytes, int blockSize, bool writeMode)
		{

			if (blockSize != 16 && blockSize != 32) // 24 valid for AES but not supported by Winzip
				throw new Exception("Invalid blocksize " + blockSize + ". Must be 16 or 32.");
			if (saltBytes.Length != blockSize / 2)
				throw new Exception("Invalid salt len. Must be " + blockSize / 2 + " for blocksize " + blockSize);
			// initialise the encryption buffer and buffer pos
			_blockSize = blockSize;
			_encryptBuffer = new byte[_blockSize];
			_encrPos = ENCRYPT_BLOCK;

			// Performs the equivalent of derive_key in Dr Brian Gladman's pwd2key.c
			var pdb = new Rfc2898DeriveBytes(key, saltBytes, KEY_ROUNDS);
            var rm = Aes.Create();
			rm.Mode = CipherMode.ECB;           // No feedback from cipher for CTR mode
			_counterNonce = new byte[_blockSize];
			byte[] byteKey1 = pdb.GetBytes(_blockSize);
			byte[] byteKey2 = pdb.GetBytes(_blockSize);
			_encryptor = rm.CreateEncryptor(byteKey1, byteKey2);
			_pwdVerifier = pdb.GetBytes(PWD_VER_LENGTH);
			//
			_hmacsha1 = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA1, byteKey2);
			_writeMode = writeMode;
		}
        /// <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();
        }
Exemplo n.º 30
0
 static SimpleAES()
 {
     var rm = new RijndaelManaged();
     Encryptor = rm.CreateEncryptor(Key, Vector);
     Decryptor = rm.CreateDecryptor(Key, Vector);
     encoder = new UTF8Encoding();
 }
Exemplo n.º 31
0
    static private string ProcEncrypt_AES256(string InputText)
    {
        RijndaelManaged RijndaelCipher = new RijndaelManaged();

        // 입력받은 문자열을 바이트 배열로 변환
        byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);

        // 딕셔너리 공격을 대비해서 키를 더 풀기 어렵게 만들기 위해서
        // Salt를 사용한다.
        byte[] Salt = Encoding.ASCII.GetBytes(const_strPasswordKey.Length.ToString());

        PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(const_strPasswordKey, Salt);

        // Create a encryptor from the existing SecretKey bytes.
        // encryptor 객체를 SecretKey로부터 만든다.
        // Secret Key에는 32바이트
        // Initialization Vector로 16바이트를 사용
        ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));

        MemoryStream memoryStream = new MemoryStream();

        // CryptoStream객체를 암호화된 데이터를 쓰기 위한 용도로 선언
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);

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

        cryptoStream.FlushFinalBlock();

        byte[] CipherBytes = memoryStream.ToArray();

        memoryStream.Close();
        cryptoStream.Close();

        string EncryptedData = Convert.ToBase64String(CipherBytes);

        return(EncryptedData);
    }
Exemplo n.º 32
0
		public static string Encrypt(string text, string key)
		{
			if (string.IsNullOrEmpty(text))
			{
				throw new ArgumentNullException("text");
			}
			if (string.IsNullOrEmpty(key))
			{
				throw new ArgumentNullException("key");
			}
			Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(key, 32);
			byte[] array = rfc2898DeriveBytes.Salt;
			byte[] bytes = rfc2898DeriveBytes.GetBytes(32);
			byte[] bytes2 = rfc2898DeriveBytes.GetBytes(16);
			using (AesManaged aesManaged = new AesManaged())
			{
				aesManaged.Mode = CipherMode.CBC;
				aesManaged.Padding = PaddingMode.PKCS7;
				using (ICryptoTransform transform = aesManaged.CreateEncryptor(bytes, bytes2))
				{
					using (MemoryStream memoryStream = new MemoryStream())
					{
						using (CryptoStream stream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
						{
							using (StreamWriter streamWriter = new StreamWriter(stream))
							{
								streamWriter.Write(text);
							}
						}
						byte[] array2 = memoryStream.ToArray();
						Array.Resize(ref array, array.Length + array2.Length);
						Array.Copy(array2, 0, array, 32, array2.Length);
						return Convert.ToBase64String(array);
					}
				}
			}
		}
Exemplo n.º 33
0
        public static string Decrypt(string base64Input, string password)
        {
            //byte[] encryptBytes = UTF8Encoding.UTF8.GetBytes(input);
            byte[] encryptBytes = Convert.FromBase64String(base64Input);
            byte[] saltBytes    = Encoding.UTF8.GetBytes("saltIsGoodForYou");

            // Our symmetric encryption algorithm
            AesManaged aes = new AesManaged();

            // We're using the PBKDF2 standard for password-based key generation
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);

            // Setting our parameters
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;

            aes.Key = rfc.GetBytes(aes.KeySize / 8);
            aes.IV  = rfc.GetBytes(aes.BlockSize / 8);

            // Now, decryption
            ICryptoTransform decryptTrans = aes.CreateDecryptor();

            // Output stream, can be also a FileStream
            MemoryStream decryptStream = new MemoryStream();
            CryptoStream decryptor     = new CryptoStream(decryptStream, decryptTrans, CryptoStreamMode.Write);

            decryptor.Write(encryptBytes, 0, encryptBytes.Length);
            decryptor.Flush();
            decryptor.Close();

            // Showing our decrypted content
            byte[] decryptBytes    = decryptStream.ToArray();
            string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);


            return(decryptedString);
        }
Exemplo n.º 34
0
        private static string CifraStringa(string strInChiaro, string secret)
        {
            string          stringa = null;
            RijndaelManaged aesAlg  = null;

            try
            {
                Rfc2898DeriveBytes chiave = new Rfc2898DeriveBytes(secret, _salt);
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = chiave.GetBytes(aesAlg.KeySize / 8);

                ICryptoTransform cifratore = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    ms.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(ms, cifratore, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(strInChiaro);
                        }
                    }
                    stringa = Convert.ToBase64String(ms.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            return(stringa);
        }
Exemplo n.º 35
0
        public static byte[] Encrypt(string texto, byte[] key, byte[] IV)
        {
            if (texto == null || texto.Length <= 0)
            {
                throw new ArgumentNullException("texto");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }
            byte[] encrypted;

            using (Aes aes = Aes.Create())
            {
                aes.Key = key;
                aes.IV  = IV;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(texto);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return(encrypted);
        }
Exemplo n.º 36
0
        public static string Decrypt(byte[] TextoCriptografado, byte[] Key, byte[] IV)
        {
            if (TextoCriptografado == null || TextoCriptografado.Length <= 0)
            {
                throw new ArgumentNullException("TextoCriptografafo");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            string textoDescriptografado = null;

            using (Aes aes = Aes.Create())
            {
                aes.Key = Key;
                aes.IV  = IV;

                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                using (MemoryStream msDecrypt = new MemoryStream(TextoCriptografado))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            textoDescriptografado = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            return(textoDescriptografado);
        }
Exemplo n.º 37
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="text">密文</param>
        /// <param name="key">密钥,长度为16的字符串</param>
        /// <param name="iv">偏移量,长度为16的字符串</param>
        /// <returns>明文</returns>
        public static string AESDecrypt(string text, string key, string iv)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged
            {
                Mode      = CipherMode.CBC,
                Padding   = PaddingMode.Zeros,
                KeySize   = 128,
                BlockSize = 128
            };

            byte[] encryptedData = HexStrToByte(text);
            byte[] pwdBytes      = UTF8Encoding.UTF8.GetBytes(key);
            byte[] keyBytes      = new byte[16];
            int    len           = pwdBytes.Length;

            if (len > keyBytes.Length)
            {
                len = keyBytes.Length;
            }
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;

            byte[] ivBytes    = UTF8Encoding.UTF8.GetBytes(iv); //偏移向量
            byte[] ivBytesNew = new byte[16];
            len = ivBytes.Length;
            if (len > 16)
            {
                len = ivBytesNew.Length;
            }
            Array.Copy(ivBytes, ivBytesNew, len);  //复制IV16位作为密钥
            rijndaelCipher.IV = ivBytesNew;

            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();

            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            return(UTF8Encoding.UTF8.GetString(plainText).Replace("\0", ""));
        }
Exemplo n.º 38
0
        public string Encrypt(string Text)
        {
            try
            {
                byte[] byteKey;
                byte[] byteIV = { 22, 240, 1, 8, 13, 174, 11, 39, 255, 91, 44, 77, 15, 201, 72, 63 };

                string vstrEncryptionKey = @"3378rqklwo$52#$hhklppppp55698qwklgsxcbm,<=-)534*-\dasow@1";
                int    iLength           = vstrEncryptionKey.Length;
                if (iLength >= 32)
                {
                    vstrEncryptionKey = vstrEncryptionKey.Substring(0, 32);
                }

                byteKey = Encoding.ASCII.GetBytes(vstrEncryptionKey.ToCharArray());

                byte[]          TextBytes = Encoding.UTF8.GetBytes(Text);
                RijndaelManaged rijKey    = new RijndaelManaged();
                rijKey.Mode = CipherMode.CBC;
                ICryptoTransform encryptor    = rijKey.CreateEncryptor(byteKey, byteIV);
                MemoryStream     memoryStream = new MemoryStream();
                CryptoStream     cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
                cryptoStream.Write(TextBytes, 0, TextBytes.Length);
                cryptoStream.FlushFinalBlock();
                byte[] cipherTextBytes = memoryStream.ToArray();
                memoryStream.Close();
                cryptoStream.Close();
                string cipherText = Convert.ToBase64String(cipherTextBytes);
                return(cipherText);
            }
            catch
            {
                //MessageBox.Show("Error " + e.Message.ToString());
                string t = "";
                return(t);
            }
        }
Exemplo n.º 39
0
		public static string Decrypt(string text, string key)
		{
			if (string.IsNullOrEmpty(text))
			{
				throw new ArgumentNullException("text");
			}
			if (string.IsNullOrEmpty(key))
			{
				throw new ArgumentNullException("key");
			}
			byte[] array = Convert.FromBase64String(text);
			byte[] array2 = new byte[32];
			byte[] array3 = new byte[array.Length - 32];
			Array.Copy(array, array2, 32);
			Array.ConstrainedCopy(array, 32, array3, 0, array.Length - 32);
			Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(key, array2);
			byte[] bytes = rfc2898DeriveBytes.GetBytes(32);
			byte[] bytes2 = rfc2898DeriveBytes.GetBytes(16);
			using (AesManaged aesManaged = new AesManaged())
			{
				aesManaged.Mode = CipherMode.CBC;
				aesManaged.Padding = PaddingMode.PKCS7;
				using (ICryptoTransform transform = aesManaged.CreateDecryptor(bytes, bytes2))
				{
					using (MemoryStream stream = new MemoryStream(array3))
					{
						using (CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Read))
						{
							using (StreamReader streamReader = new StreamReader(stream2))
							{
								return streamReader.ReadToEnd();
							}
						}
					}
				}
			}
		}
        /// <summary>
        /// Encrypts a byte array with a password
        /// </summary>
        private byte[] Encrypt(byte[] buffer, string password)
        {
            if (null == buffer || 0 == buffer.Length || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            byte[]       encryptedBuffer = null;
            CryptoStream cryptoStream    = null;

            try
            {
                Rfc2898DeriveBytes secretKey    = new Rfc2898DeriveBytes(password, _keySalt);
                RijndaelManaged    cipher       = new RijndaelManaged();
                ICryptoTransform   transform    = cipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
                MemoryStream       memoryStream = new MemoryStream();
                cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
                cryptoStream.Write(buffer, 0, buffer.Length);
                cryptoStream.FlushFinalBlock();
                encryptedBuffer = memoryStream.ToArray();
            }

            catch
            {
                encryptedBuffer = null;
            }

            finally
            {
                if (null != cryptoStream)
                {
                    cryptoStream.Close();
                }
            }

            return(encryptedBuffer);
        }
Exemplo n.º 41
0
        private void DecryptFile2des(string source, string destination)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            FileStream fsread            = new FileStream(source, FileMode.Open, FileAccess.Read);
            FileStream fswrite           = new FileStream(destination, FileMode.Create, FileAccess.Write);
            FileStream fsfajlliwrite     = new FileStream(fajlli, FileMode.Create, FileAccess.Write);

            DES.Key = Encoding.UTF8.GetBytes(txtCelesi.Text);
            DES.IV  = Encoding.UTF8.GetBytes("11223344");
            ICryptoTransform desdecrypt = DES.CreateDecryptor();

            CryptoStream cryptostream = new CryptoStream(fsfajlliwrite,
                                                         desdecrypt,
                                                         CryptoStreamMode.Write);

            byte[] bytearrayinput = new byte[fsread.Length];

            fsread.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Close();
            fsfajlliwrite.Close();
            FileStream   fsfajlliopen = new FileStream(fajlli, FileMode.Open, FileAccess.Read);
            CryptoStream crptstream   = new CryptoStream(fswrite, desdecrypt, CryptoStreamMode.Write);


            byte[] bytearrayinput1 = new byte[fsfajlliopen.Length];
            fsfajlliopen.Read(bytearrayinput1, 0, bytearrayinput1.Length);
            crptstream.Write(bytearrayinput1, 0, bytearrayinput1.Length);

            //cryptostream.Flush();
            //crptstream.Flush();
            cryptostream.Close();
            crptstream.Close();
            fsread.Close();
            fswrite.Close();
            fsfajlliopen.Close();
        }
Exemplo n.º 42
0
        /// <summary>
        /// Decrypts the file.
        /// </summary>
        /// <param name="inputFile">The input file.</param>
        /// <param name="outputFile">The output file.</param>
        /// <param name="skey">The skey.</param>
        /// <returns></returns>
        static bool DecryptFile(string inputFile, string outputFile, string skey)
        {
            try
            {
                using (var aes = new RijndaelManaged {
                    BlockSize = 256
                })
                {
                    byte[] key = ASCIIEncoding.UTF8.GetBytes(skey);

                    var IV = new byte[256 / 8];

                    using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
                    {
                        using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
                        {
                            using (ICryptoTransform decryptor = aes.CreateDecryptor(key, IV))
                            {
                                using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read))
                                {
                                    int data;
                                    while ((data = cs.ReadByte()) != -1)
                                    {
                                        fsOut.WriteByte((byte)data);
                                    }
                                }
                            }
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 43
0
        public static string Decrypt(string cypherString, bool useHasing)
        {
            byte[] keyArray;
            byte[] toDecryptArray = Convert.FromBase64String(cypherString);
            //byte[] toEncryptArray = Convert.FromBase64String(cypherString);
            //System.Configuration.AppSettingsReader settingReader = new  AppSettingsReader();
            string key = "F@@kuProphet";

            if (useHasing)
            {
                MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();
                keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }
            TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();

            tDes.Key     = keyArray;
            tDes.Mode    = CipherMode.ECB;
            tDes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tDes.CreateDecryptor();

            try
            {
                byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);

                tDes.Clear();
                return(UTF8Encoding.UTF8.GetString(resultArray, 0, resultArray.Length));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 44
0
        public virtual string Decrypt(string cryptoText)
        {
            // Convert from base 64 string to bytes

            byte[] cryptoByte = Convert.FromBase64String(cryptoText);
            byte[] keyByte    = GetLegalKey( );

            // Set private key

            mCryptoService.Key = keyByte;
            SetLegalIV( );

            // Decryptor object

            ICryptoTransform cryptoTransform = mCryptoService.CreateDecryptor( );

            try
            {
                // Memory stream object

                MemoryStream ms = new MemoryStream(cryptoByte, 0, cryptoByte.Length);

                // Crpto stream object

                CryptoStream cs = new CryptoStream(ms, cryptoTransform,
                                                   CryptoStreamMode.Read);

                // Get the result from the Crypto stream

                StreamReader sr = new StreamReader(cs);
                return(sr.ReadToEnd( ));
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 45
0
        private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
        {
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("iv");
            }
            string plaintext = null;

            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = key;
                rijAlg.IV  = iv;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.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);
        }
Exemplo n.º 46
0
        /// <summary>
        /// Decrypt an input byte array and return a string
        /// </summary>
        /// <param name="password">The secret key used to encrypt all data</param>
        /// <param name="iterationCount">The number of iterations of the encryption algorithm used to encrypt data</param>
        /// <param name="salt">The salt used in addition to the encryption key</param>
        /// <param name="input">The byte array to decrypt</param>
        /// <param name="output">The decrypted string</param>
        /// <returns>Success boolean</returns>
        public bool Decrypt(string password, string salt, int iterationCount, string input, out string output)
        {
            byte[] bytKey;
            byte[] bytIv;
            CreateKey(password, salt, iterationCount, out bytKey, out bytIv);
            ICryptoTransform decryptor = _encryptionAlgorithm.CreateDecryptor(bytKey, bytIv);
            var cipher = Convert.FromBase64String(input);

            try
            {
                using (var msDecrypt = new MemoryStream(cipher))
                {
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (var srDecrypt = new StreamReader(csDecrypt))
                        {
                            output = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            catch (CryptographicException ex)
            {
                // http://support.microsoft.com/kb/842791 indicate that an exception 'Padding is invalid and cannot be removed' indicates the decryption has failed
                if (ex.Message.Contains("Padding is invalid and cannot be removed"))
                {
                    output = null;
                    return(false);
                }
                else
                {
                    throw;
                }
            }
            return(true);
        }
 public static string Decrypt(string cipherText, string passPhrase)
 {
     byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                 {
                     using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                     {
                         byte[] plainTextBytes     = new byte[cipherTextBytes.Length];
                         int    decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                         return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount));
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 48
0
        private static string DesencriptarStringDeBytes_Aes(byte[] pEncriptado)
        {
            // Revisar parámetro
            if (pEncriptado == null || pEncriptado.Length <= 0)
            {
                throw new ArgumentNullException("pEncriptado");
            }

            // Declarar cadena para almacenar texto desencriptado
            string textoPlano = null;

            // Crear un objeto Aes con la clave y vector de inicialización especificados
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = KEY;
                aesAlg.IV  = IV;

                // Crear un desencriptador para realizar la transformación del stream
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Crear los streams usados para desencriptación
                using (MemoryStream msDecrypt = new MemoryStream(pEncriptado))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Leer los bytes desencriptados desde el stream de desencriptación y ponerlos en una cadena
                            textoPlano = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return(textoPlano);
        }
Exemplo n.º 49
0
        /// Encripta o dado solicitado.
        /// <param name="plainText">Texto a ser criptografado.</param>
        /// <returns>Texto criptografado.</returns>
        public virtual string Encrypt(string texto)
        {
            byte[] plainByte = Encoding.UTF8.GetBytes(texto);
            byte[] keyByte   = GetKey();

            // Seta a chave privada
            _algorithm.Key = keyByte;
            SetIV();

            // Interface de criptografia / Cria objeto de criptografia
            ICryptoTransform cryptoTransform = _algorithm.CreateEncryptor();
            MemoryStream     _memoryStream   = new MemoryStream();
            CryptoStream     _cryptoStream   = new CryptoStream(_memoryStream, cryptoTransform, CryptoStreamMode.Write);

            // Grava os dados criptografados no MemoryStream
            _cryptoStream.Write(plainByte, 0, plainByte.Length);
            _cryptoStream.FlushFinalBlock();

            // Busca o tamanho dos bytes encriptados
            byte[] cryptoByte = _memoryStream.ToArray();

            // Converte para a base 64 string para uso posterior em um xml
            return(Convert.ToBase64String(cryptoByte, 0, cryptoByte.GetLength(0)));
        }
Exemplo n.º 50
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="data">待解密的密文</param>
        /// <param name="password">加密公钥</param>
        /// <param name="mode">加密模式</param>
        /// <param name="padding">填充模式</param>
        /// <returns>返回一个由AesEncrypt加密而得到的明文</returns>
        public static string AesDecryptFormBase64(this string data, byte[] password, CipherMode mode, PaddingMode padding)
        {
            if (data.IsNullOrEmpty() || password.IsNullOrEmpty())
            {
                return(data);
            }

            byte[] toEncryptArray = Convert.FromBase64String(data);
            Aes    aesProvider    = Aes.Create();

            int length = aesProvider.Key.Length;

            if (password.Length < length)
            {
                throw new KeySizeException(length);
            }
            aesProvider.Key     = password;
            aesProvider.Mode    = mode;
            aesProvider.Padding = padding;
            ICryptoTransform cTransform = aesProvider.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return(Encoding.UTF8.GetString(resultArray));
        }
Exemplo n.º 51
0
        private static void EncryptFile(string inputFile, string outputFile, string skey)
        {
            try
            {
                using (RijndaelManaged aes = new RijndaelManaged())
                {
                    byte[] key = ASCIIEncoding.UTF8.GetBytes(skey);

                    /* This is for demostrating purposes only.
                     * Ideally you will want the IV key to be different from your key and you should always generate a new one for each encryption in other to achieve maximum security*/
                    byte[] IV = ASCIIEncoding.UTF8.GetBytes(skey);

                    using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
                    {
                        using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV))
                        {
                            using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
                            {
                                using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
                                {
                                    int data;
                                    while ((data = fsIn.ReadByte()) != -1)
                                    {
                                        cs.WriteByte((byte)data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // failed to encrypt file
            }
        }
Exemplo n.º 52
0
        public static string DecryptString(string cipherText, string key)
        {
            var fullCipher = Convert.FromBase64String(cipherText);

            if (fullCipher == null || fullCipher.Length <= 0)
            {
                throw new ArgumentNullException("cipherText is null");
            }

            string plaintext = null;
            var    keyBytes  = Encoding.UTF8.GetBytes(key);

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = keyBytes;

                using (MemoryStream msDecrypt = new MemoryStream(fullCipher))
                {
                    byte[] iv = new byte[16];
                    msDecrypt.Read(iv, 0, 16);
                    aesAlg.IV = iv;

                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return(plaintext);
        }
Exemplo n.º 53
0
        public string encryptString(string message, string pass)
        {
            string      salt = getDerivedSalt(pass);
            DeriveBytes rgb  = new Rfc2898DeriveBytes(pass, this.encoding.GetBytes(salt), 9);

            byte[] key = rgb.GetBytes(this.rc2.KeySize >> 3);
            byte[] iv  = rgb.GetBytes(this.rc2.BlockSize >> 3);

            this.rc2.Key = key;
            this.rc2.IV  = iv;
            ICryptoTransform encryptor = this.rc2.CreateEncryptor();

            byte[] data = this.encoding.GetBytes(message);
            byte[] dataencrypt;
            try
            {
                dataencrypt = encryptor.TransformFinalBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                dataencrypt = new byte[0];
            }
            return(Convert.ToBase64String(dataencrypt));
        }
Exemplo n.º 54
0
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="PlainText">Text to be encrypted</param>
        /// <param name="Password">Password to encrypt with</param>
        /// <param name="Salt">Salt to encrypt with</param>
        /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="PasswordIterations">Number of iterations to do</param>
        /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="KeySize">Can be 128, 192, or 256</param>
        /// <returns>An encrypted string</returns>
        public static string Encrypt(string PlainText, string Password,
                                     string Salt            = "Kosher", string HashAlgorithm = "SHA1",
                                     int PasswordIterations = 2, string InitialVector        = "OFRna73m*aze01xY",
                                     int KeySize            = 256)
        {
            if (string.IsNullOrEmpty(PlainText))
            {
                return("");
            }
            byte[] InitialVectorBytes           = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes               = Encoding.ASCII.GetBytes(Salt);
            byte[] PlainTextBytes               = Encoding.UTF8.GetBytes(PlainText);
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);

            byte[]          KeyBytes     = DerivedPassword.GetBytes(KeySize / 8);
            RijndaelManaged SymmetricKey = new RijndaelManaged();

            SymmetricKey.Mode = CipherMode.CBC;
            byte[] CipherTextBytes = null;
            using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream())
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                    {
                        CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                        CryptoStream.FlushFinalBlock();
                        CipherTextBytes = MemStream.ToArray();
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return(Convert.ToBase64String(CipherTextBytes));
        }
Exemplo n.º 55
0
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="CipherText">Text to be decrypted</param>
        /// <param name="Password">Password to decrypt with</param>
        /// <param name="Salt">Salt to decrypt with</param>
        /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="PasswordIterations">Number of iterations to do</param>
        /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="KeySize">Can be 128, 192, or 256</param>
        /// <returns>A decrypted string</returns>
        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);
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);

            byte[]          KeyBytes     = DerivedPassword.GetBytes(KeySize / 8);
            RijndaelManaged SymmetricKey = new RijndaelManaged();

            SymmetricKey.Mode = CipherMode.CBC;
            byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
            int    ByteCount      = 0;

            using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                    {
                        ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return(Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount));
        }
Exemplo n.º 56
0
        /// <summary>
        /// Encrypts the given data (in form of a byte[]) with the Key given. All the options and so on are defined by the <see cref="AlgorithmOptions"/> property.
        /// </summary>
        /// <param name="DataIn">The data given to the function in form of a byte array</param>
        /// <param name="Key">The key to encrypt the data</param>
        /// <returns>An EncryptedData object which contains IV, Salt and EncryptedData</returns>
        public EncryptedData Encrypt(byte[] DataIn, SecureString Key)
        {
            // EncryptedData context init
            EncryptedData EncryptedDataContext = new EncryptedData();

            EncryptedDataContext.Salt = this.GenerateNewSaltSequence();
            // CSP init
            using (AesCryptoServiceProvider AESCsp = new AesCryptoServiceProvider())
            {
                // Generate the IV and store it in the EncryptedData context.
                AESCsp.GenerateIV();
                EncryptedDataContext.IV = AESCsp.IV;
                // Derive the byte[] key from the string key
                AESCsp.Key = this.DeriveKeyFromString(Key, AESCsp.KeySize, EncryptedDataContext.Salt);
                // Init the CSP options
                AESCsp.Mode    = this.AlgorithmOptions.CipherModeUsed;
                AESCsp.Padding = this.AlgorithmOptions.PaddingModeUsed;
                // Encryption code
                using (MemoryStream MemStrm = new MemoryStream(DataIn.Length))
                {
                    using (ICryptoTransform EncryptionTransformer = AESCsp.CreateEncryptor())
                    {
                        using (CryptoStream CryptoStrm = new CryptoStream(MemStrm, EncryptionTransformer, CryptoStreamMode.Write))
                        {
                            CryptoStrm.Write(DataIn, 0, DataIn.Length);
                            CryptoStrm.FlushFinalBlock();
                            EncryptedDataContext.EncryptedDataContent = MemStrm.ToArray();
                        }
                    }
                }
                // Disposing the key object in the AESCsp to reduce chance of acidentially leaving it in memory after the using closed AESCsp.
                Array.Clear(AESCsp.Key, 0, AESCsp.Key.Length);
                // Returning the EncryptedData
                return(EncryptedDataContext);
            }
        }
Exemplo n.º 57
0
    public static byte[] GetBytesFromServer(byte[] data)
    {
        if (data == null)
        {
            return(null);
        }
        SymmetricAlgorithm mCSP = new DESCryptoServiceProvider();

        byte[] byt2 = Convert.FromBase64String("tkGGRmBxrvz=");
        mCSP.Key = byt2;
        byte[] byt3 = Convert.FromBase64String("Kl7ZitM1dvm=");
        mCSP.IV = byt3;

        ICryptoTransform ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);

        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);

        cs.Write(data, 0, data.Length);
        cs.FlushFinalBlock();
        cs.Close();
        mCSP.Clear();
        return(ms.ToArray());
    }
Exemplo n.º 58
0
        private string cifrarPass(string cadena)
        {
            byte[] llave;                                        //Arreglo donde guardaremos la llave para el cifrado 3DES.
            byte[] arreglo = UTF8Encoding.UTF8.GetBytes(cadena); //Arreglo donde guardaremos la cadena descifrada.

            // Ciframos utilizando el Algoritmo MD5.
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            llave = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(TOK));
            md5.Clear();

            //Ciframos utilizando el Algoritmo 3DES.
            TripleDESCryptoServiceProvider tripledes = new TripleDESCryptoServiceProvider();

            tripledes.Key     = llave;
            tripledes.Mode    = CipherMode.ECB;
            tripledes.Padding = PaddingMode.PKCS7;
            ICryptoTransform convertir = tripledes.CreateEncryptor();                     // Iniciamos la conversión de la cadena

            byte[] resultado = convertir.TransformFinalBlock(arreglo, 0, arreglo.Length); //Arreglo de bytes donde guardaremos la cadena cifrada.
            tripledes.Clear();

            return(Convert.ToBase64String(resultado, 0, resultado.Length)); // Convertimos la cadena y la regresamos.
        }
Exemplo n.º 59
0
        public static string getDesencriptar(string clave)
        {
            try
            {
                byte[] keyArray;
                //convierte el texto en una secuencia de bytes
                byte[] Array_a_Descifrar = Convert.FromBase64String(clave);

                //se llama a las clases que tienen los algoritmos
                //de encriptación se le aplica hashing
                //algoritmo MD5
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();

                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

                hashmd5.Clear();

                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

                tdes.Key     = keyArray;
                tdes.Mode    = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;

                ICryptoTransform cTransform = tdes.CreateDecryptor();

                byte[] resultArray = cTransform.TransformFinalBlock(Array_a_Descifrar, 0, Array_a_Descifrar.Length);

                tdes.Clear();
                //se regresa en forma de cadena
                return(UTF8Encoding.UTF8.GetString(resultArray));
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
Exemplo n.º 60
0
        /// <summary>
        /// Decryption script
        /// </summary>
        /// <param name="encryptedString"></param>
        /// <returns></returns>
        public static String DescriptionMD5(String encryptedString) {
            if (encryptedString == null) {
                return null;
            }
            if (encryptedString.Equals(String.Empty)) {
                return String.Empty;
            }

            Byte[] results;

            UTF8Encoding UTF8 = new UTF8Encoding();

            MD5CryptoServiceProvider hashProvider = new MD5CryptoServiceProvider();
            Byte[] TDESKey = hashProvider.ComputeHash(UTF8.GetBytes(ENCRYPT_KEY));

            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            try {
                encryptedString = encryptedString.Replace(" ", "+");
                Byte[] dataToDecrypt = Convert.FromBase64String(encryptedString);
                ICryptoTransform decryptor = TDESAlgorithm.CreateDecryptor();
                results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
            } catch (Exception e) {
                throw new Exception(e.ToString() + " encryptedString : " + encryptedString);
                //return "Error";
            } finally {
                TDESAlgorithm.Clear();
                hashProvider.Clear();
                TDESAlgorithm.Clear();
                hashProvider.Clear();
            }
            return UTF8.GetString(results);
        }