ProcessBytes() public method

public ProcessBytes ( byte input, int inOff, int length, byte output, int outOff ) : int
input byte
inOff int
length int
output byte
outOff int
return int
コード例 #1
0
ファイル: PaddingTest.cs プロジェクト: randombit/hacrypto
		private void blockCheck(
			PaddedBufferedBlockCipher   cipher,
			IBlockCipherPadding          padding,
			KeyParameter                key,
			byte[]                      data)
		{
			byte[]  outBytes = new byte[data.Length + 8];
			byte[]  dec = new byte[data.Length];

			try
			{
				cipher.Init(true, key);

				int    len = cipher.ProcessBytes(data, 0, data.Length, outBytes, 0);

				len += cipher.DoFinal(outBytes, len);

				cipher.Init(false, key);

				int    decLen = cipher.ProcessBytes(outBytes, 0, len, dec, 0);

				decLen += cipher.DoFinal(dec, decLen);

				if (!AreEqual(data, dec))
				{
					Fail("failed to decrypt - i = " + data.Length + ", padding = " + padding.PaddingName);
				}
			}
			catch (Exception e)
			{
				Fail("Exception - " + e.ToString(), e);
			}
		}
コード例 #2
0
        private static string Cipher(bool encrypt, byte[] key, byte[] data)
        {
            PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cipherEngine, padding);
            cipher.Init(encrypt, new KeyParameter(key));

            int size = cipher.GetOutputSize(data.Length);
            byte[] result = new byte[size];
            int position = cipher.ProcessBytes(data, 0, data.Length, result, 0);
            cipher.DoFinal(result, position);

            return encrypt ? BitConverter.ToString(result).Replace("-", String.Empty).ToLower() : encoding.GetString(result);
        }
コード例 #3
0
ファイル: Authenticator.cs プロジェクト: kgdyinpv/WinAuth7
		/// <summary>
		/// Decrypt a hex-coded string using our MD5 or PBKDF2 generated key
		/// </summary>
		/// <param name="data">data string to be decrypted</param>
		/// <param name="key">decryption key</param>
		/// <param name="PBKDF2">flag to indicate we are using PBKDF2 to generate derived key</param>
		/// <returns>hex coded decrypted string</returns>
		public static string Decrypt(string data, string password, bool PBKDF2)
		{
			byte[] key;
			byte[] saltBytes = Authenticator.StringToByteArray(data.Substring(0, SALT_LENGTH * 2));

			if (PBKDF2 == true)
			{
				// extract the salt from the data
				byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

				// build our PBKDF2 key
#if NETCF
			PBKDF2 kg = new PBKDF2(passwordBytes, saltbytes, 2000);
#else
				Rfc2898DeriveBytes kg = new Rfc2898DeriveBytes(passwordBytes, saltBytes, PBKDF2_ITERATIONS);
#endif
				key = kg.GetBytes(PBKDF2_KEYSIZE);
			}
			else
			{
				// extract the salt from the data
				byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
				key = new byte[saltBytes.Length + passwordBytes.Length];
				Array.Copy(saltBytes, key, saltBytes.Length);
				Array.Copy(passwordBytes, 0, key, saltBytes.Length, passwordBytes.Length);
				// build out combined key
				SHA256Managed md5 =new SHA256Managed();
				key = md5.ComputeHash(key);
			}

			// extract the actual data to be decrypted
			byte[] inBytes = Authenticator.StringToByteArray(data.Substring(SALT_LENGTH * 2));

			// get cipher
			BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding());
			cipher.Init(false, new KeyParameter(key));

			// decrypt the data
			int osize = cipher.GetOutputSize(inBytes.Length);
			byte[] outBytes = new byte[osize];
			try
			{
				int olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);
				olen += cipher.DoFinal(outBytes, olen);
				if (olen < osize)
				{
					byte[] t = new byte[olen];
					Array.Copy(outBytes, 0, t, 0, olen);
					outBytes = t;
				}
			}
			catch (Exception)
			{
				// an exception is due to bad password
				throw new BadPasswordException();
			}

			// return encoded string
			return Authenticator.ByteArrayToString(outBytes);
		}
コード例 #4
0
ファイル: Authenticator.cs プロジェクト: kgdyinpv/WinAuth7
		/// <summary>
		/// Encrypt a string with a given key
		/// </summary>
		/// <param name="plain">data to encrypt - hex representation of byte array</param>
		/// <param name="key">key to use to encrypt</param>
		/// <returns>hex coded encrypted string</returns>
		public static string Encrypt(string plain, string password)
		{
			byte[] inBytes = Authenticator.StringToByteArray(plain);
			byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

			// build a new salt
			RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider();
			byte[] saltbytes = new byte[SALT_LENGTH];
			rg.GetBytes(saltbytes);
			string salt = Authenticator.ByteArrayToString(saltbytes);

			// build our PBKDF2 key
#if NETCF
			PBKDF2 kg = new PBKDF2(passwordBytes, saltbytes, PBKDF2_ITERATIONS);
#else
			Rfc2898DeriveBytes kg = new Rfc2898DeriveBytes(passwordBytes, saltbytes, PBKDF2_ITERATIONS);
#endif
			byte[] key = kg.GetBytes(PBKDF2_KEYSIZE);

			// get our cipher
			BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding());
			cipher.Init(true, new KeyParameter(key));

			// encrypt data
			int osize = cipher.GetOutputSize(inBytes.Length);
			byte[] outBytes = new byte[osize];
			int olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);
			olen += cipher.DoFinal(outBytes, olen);
			if (olen < osize)
			{
				byte[] t = new byte[olen];
				Array.Copy(outBytes, 0, t, 0, olen);
				outBytes = t;
			}

			// return encoded byte->hex string
			return salt + Authenticator.ByteArrayToString(outBytes);
		}
コード例 #5
0
ファイル: Authenticator.cs プロジェクト: Felluz/winauth
		/// <summary>
		/// Decrypt a hex-encoded string with a byte array key
		/// </summary>
		/// <param name="data">hex-encoded string</param>
		/// <param name="key">key for decryption</param>
		/// <returns>hex-encoded plain text</returns>
		public static string Decrypt(string data, byte[] key)
		{
			// the actual data to be decrypted
			byte[] inBytes = Authenticator.StringToByteArray(data);

			// get cipher
			BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding());
			cipher.Init(false, new KeyParameter(key));

			// decrypt the data
			int osize = cipher.GetOutputSize(inBytes.Length);
			byte[] outBytes = new byte[osize];
			try
			{
				int olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);
				olen += cipher.DoFinal(outBytes, olen);
				if (olen < osize)
				{
					byte[] t = new byte[olen];
					Array.Copy(outBytes, 0, t, 0, olen);
					outBytes = t;
				}
			}
			catch (Exception)
			{
				// an exception is due to bad password
				throw new BadPasswordException();
			}

			// return encoded string
			return Authenticator.ByteArrayToString(outBytes);
		}
コード例 #6
0
ファイル: Authenticator.cs プロジェクト: Felluz/winauth
		/// <summary>
		/// Encrypt a string with a byte array key
		/// </summary>
		/// <param name="plain">data to encrypt - hex representation of byte array</param>
		/// <param name="passwordBytes">key to use to encrypt</param>
		/// <returns>hex coded encrypted string</returns>
		public static string Encrypt(string plain, byte[] key)
		{
			byte[] inBytes = Authenticator.StringToByteArray(plain);

			// get our cipher
			BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding());
			cipher.Init(true, new KeyParameter(key));

			// encrypt data
			int osize = cipher.GetOutputSize(inBytes.Length);
			byte[] outBytes = new byte[osize];
			int olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);
			olen += cipher.DoFinal(outBytes, olen);
			if (olen < osize)
			{
				byte[] t = new byte[olen];
				Array.Copy(outBytes, 0, t, 0, olen);
				outBytes = t;
			}

			// return encoded byte->hex string
			return Authenticator.ByteArrayToString(outBytes);
		}
コード例 #7
0
ファイル: EncryptedData.cs プロジェクト: bowmark/allauth.lib
        /// <summary>
        /// Decrypt AES256-CBC with PKCS7 padding data
        /// </summary>
        /// <param name="encryptionKey"></param>
        /// <param name="encryptedDataStream"></param>
        /// <param name="outputStream"></param>
        private static void DecryptDataAes256CbcPkcs7(
            byte[] encryptionKey, Stream encryptedDataStream, Stream outputStream)
        {
            if (encryptionKey.Length != 32)
                throw new Exception("AES256 encryption key not of expected length");

            var iv = new byte[16];
            var ivBytesRead = encryptedDataStream.Read(iv, 0, 16);
            if (ivBytesRead != 16)
                throw new Exception("Unexpected IV");

            // The rest of the data stream is the encrypted data itself.

            var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesFastEngine()), new Pkcs7Padding());
            cipher.Init(false, new ParametersWithIV(new KeyParameter(encryptionKey), iv));
            
            while (true)
            {
                var buffer = new byte[4096];
                var dataBytesRead = encryptedDataStream.Read(buffer, 0, 4096);
                if (dataBytesRead == 0)
                    break;
                
                var processedBytes = cipher.ProcessBytes(buffer, 0, dataBytesRead);
                if (processedBytes != null)
                    outputStream.Write(processedBytes, 0, processedBytes.Length);
            }
            var finalBytes = cipher.DoFinal();
            outputStream.Write(finalBytes, 0, finalBytes.Length);
        }
コード例 #8
0
        /// <summary>
        /// Encrypts using AES256Cbc and a password
        /// </summary>
        /// <param name="password"></param>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public static byte[] Encrypt(string plainText, string password)
        {
            // If text to encrypt is null, return null
            if (string.IsNullOrWhiteSpace(plainText))
            {
                return null;
            }

            // Generate a random salt
            var saltBytes = GenerateSalt();

            //create cipher engine
            var cipher = new PaddedBufferedBlockCipher(
                new CbcBlockCipher(
                    new AesEngine()));

            //get the key parameters from the password
            var key = GenerateKey(password, saltBytes);

            //initialize for encryption with the key
            cipher.Init(true, key);

            // Convert plain text string to bytes
            var plainBytes = Encoding.UTF8.GetBytes(plainText);

            MemoryStream cipherStream;
            //process the input
            using (cipherStream = new MemoryStream())
            {
                //write iv
                cipherStream.Write(key.GetIV(), 0, key.GetIV().Length);
                //write salt
                cipherStream.Write(saltBytes, 0, saltBytes.Length);

                byte[] outputBytes;
                //get output
                outputBytes = cipher.ProcessBytes(plainBytes);

                if (outputBytes != null)
                {
                    //write the data to the stream
                    cipherStream.Write(outputBytes, 0, outputBytes.Length);
                }

                //do the final block
                outputBytes = cipher.DoFinal();

                if (outputBytes != null)
                {
                    //write the data to the stream
                    cipherStream.Write(outputBytes, 0, outputBytes.Length);
                }

            }

            //return the bytes
            return cipherStream.ToArray();
        }
コード例 #9
0
        /// <summary>
        /// Decrypts cypher data
        /// </summary>
        /// <param name="cipherData"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string Decrypt(byte[] cipherData, string password)
        {
            // If there is no cipher data, return null
            if (cipherData == null)
            {
                return null;
            }

            //extract the iv and salt
            byte[] ivBytes = new byte[IV_LENGTH];
            byte[] saltBytes = new byte[SALT_LENGTH];
            byte[] cipherBytes = new byte[cipherData.Length - (ivBytes.Length + saltBytes.Length)];

            //process the input
            using (var cipherStream = new MemoryStream(cipherData))
            {
                //read iv
                cipherStream.Read(ivBytes, 0, ivBytes.Length);
                //read salt
                cipherStream.Read(saltBytes, 0, saltBytes.Length);
                //read cipher bytes
                cipherStream.Read(cipherBytes, 0, cipherBytes.Length);

            }

            //create cipher engine
            var cipher = new PaddedBufferedBlockCipher(
                new CbcBlockCipher(
                    new AesEngine()));

            //get the key parameters from the password
            var key = GenerateKey(password, saltBytes, ivBytes);

            //initialize for decryption with the key
            cipher.Init(false, key);

            MemoryStream plainStream;
            //process the input
            using (plainStream = new MemoryStream())
            {
                byte[] outputBytes;
                //get output
                outputBytes = cipher.ProcessBytes(cipherBytes);

                if (outputBytes != null)
                {
                    //write the data to the stream
                    plainStream.Write(outputBytes, 0, outputBytes.Length);
                }

                //do the final block
                outputBytes = cipher.DoFinal();

                if (outputBytes != null)
                {
                    //write the data to the stream
                    plainStream.Write(outputBytes, 0, outputBytes.Length);
                }

            }


            return Encoding.UTF8.GetString(plainStream.ToArray());
        }
コード例 #10
0
ファイル: Cryptographer.cs プロジェクト: hakandilek/keysmith
        /// <summary>
        /// The encrypt.
        /// </summary>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string Encrypt(string data, SecretKey key)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(data);

            // Setup the DESede cipher engine, create a PaddedBufferedBlockCipher in CBC mode.
            byte[] keyBytes = key.GetBytes();
            var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEdeEngine()));

            // initialise the cipher with the key bytes, for encryption
            cipher.Init(true, new KeyParameter(keyBytes));

            int inBlockSize = bytes.Length;
            int outBlockSize = cipher.GetOutputSize(inBlockSize);

            var inblock = bytes;
            var outblock = new byte[outBlockSize];

            cipher.ProcessBytes(inblock, 0, inBlockSize, outblock, 0);
            cipher.DoFinal(outblock, 0);

            return Convert.ToBase64String(outblock);
        }
コード例 #11
0
ファイル: Cryptographer.cs プロジェクト: hakandilek/keysmith
        /// <summary>
        /// The decrypt.
        /// </summary>
        /// <param name="encrypted">
        /// The encrypted.
        /// </param>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string Decrypt(string encrypted, SecretKey key)
        {
            byte[] bytes = Convert.FromBase64String(encrypted);
            byte[] keyBytes = key.GetBytes();

            // initialise the cipher for decryption
            var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEdeEngine()));
            cipher.Init(false, new KeyParameter(keyBytes));

            int inBlockSize = bytes.Length;
            int outBlockSize = cipher.GetOutputSize(inBlockSize);

            var inblock = bytes;
            var outblock = new byte[outBlockSize];

            cipher.ProcessBytes(inblock, 0, inBlockSize, outblock, 0);
            cipher.DoFinal(outblock, 0);

            var clear = this.ToUTF8String(outblock);
            return clear;
        }
コード例 #12
0
ファイル: SerpentTest.cs プロジェクト: KimikoMuffin/bc-csharp
        private void DoCbc(byte[] key, byte[] iv, byte[] pt, byte[] expected)
        {
            PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new CbcBlockCipher(new SerpentEngine()), new Pkcs7Padding());

            byte[] ct = new byte[expected.Length];

            c.Init(true, new ParametersWithIV(new KeyParameter(key), iv));

            int l = c.ProcessBytes(pt, 0, pt.Length, ct, 0);

            c.DoFinal(ct, l);

            if (!Arrays.AreEqual(expected, ct))
            {
                Fail("CBC test failed");
            }
        }
コード例 #13
0
        private void EncryptUsingBC(Stream istream, Stream ostream, byte[] iv, bool forEncryption)
        {
            var padding = ((TypeWrapper) BlockCipherModel.Padding).Instance<IBlockCipherPadding>();
            var engine = BlockCipherModel.Engine.Instance<IBlockCipher>();
            var mode = ((TypeWrapper) BlockCipherModel.Mode).Instance<IBlockCipher>(engine);
            var cipher = new PaddedBufferedBlockCipher(mode, padding);
            var buf = new byte[16]; //input buffer
            var obuf = new byte[512]; //output buffer

            int noBytesRead; //number of bytes read from input
            int noBytesProcessed ; //number of bytes processed
            var p = new ParametersWithIV(new KeyParameter(PbkdfModel.Key), iv);
            cipher.Init(forEncryption, p);
            // Buffer used to transport the bytes from one stream to another

            while ((noBytesRead = istream.Read(buf, 0, Blocksize)) > 0)
            {
                //System.out.println(noBytesRead +" bytes read");

                noBytesProcessed =
                    cipher.ProcessBytes(buf, 0, noBytesRead, obuf, 0);
                //System.out.println(noBytesProcessed +" bytes processed");
                ostream.Write(obuf, 0, noBytesProcessed);
            }

            //System.out.println(noBytesRead +" bytes read");
            noBytesProcessed = cipher.DoFinal(obuf, 0);

            //System.out.println(noBytesProcessed +" bytes processed");
            ostream.Write(obuf, 0, noBytesProcessed);

            ostream.Flush();
        }