Inheritance: Org.BouncyCastle.Crypto.BufferedBlockCipher
Exemplo n.º 1
0
        private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
        {
            try
            {
                _cipher = _padding == null ?
                          new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding);

                int paddingchar = 16 - key.Length;

                for (int i = 0; i < paddingchar; i++)
                {
                    key += " ";
                }
                key = key.Substring(0, 16);

                byte[] keyByte = _encoding.GetBytes(key);


                _cipher.Init(forEncrypt, new KeyParameter(keyByte));
                return(_cipher.DoFinal(input));
            }
            catch (Org.BouncyCastle.Crypto.CryptoException ex)
            {
                // throw new CryptoException(ex);
            }
            return(null);
        }
Exemplo n.º 2
0
 private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
 {
     _cipher = _padding == null ? new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding);
     byte[] keyByte = _encoding.GetBytes(key);
     _cipher.Init(forEncrypt, new KeyParameter(keyByte));
     return _cipher.DoFinal(input);
 }
Exemplo n.º 3
0
		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);
			}
		}
Exemplo n.º 4
0
 private static byte[] Decrypt(byte[] bytes, byte[] key)
 {
     var engine = new BlowfishEngine();
     var chiper = new PaddedBufferedBlockCipher(engine);
     var keyParameter = new KeyParameter(key);
     chiper.Init(false, keyParameter);
     return chiper.DoFinal(bytes);
 }
Exemplo n.º 5
0
 /** Creates a new instance of AESCipher */
 public AESCipher(bool forEncryption, byte[] key, byte[] iv) {
     IBlockCipher aes = new AesFastEngine();
     IBlockCipher cbc = new CbcBlockCipher(aes);
     bp = new PaddedBufferedBlockCipher(cbc);
     KeyParameter kp = new KeyParameter(key);
     ParametersWithIV piv = new ParametersWithIV(kp, iv);
     bp.Init(forEncryption, piv);
 }
        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);
        }
Exemplo n.º 7
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="forEncrypt"></param>
 /// <param name="input"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 /// <exception cref="CryptoException"></exception>
 private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
 {
     try
     {
         _cipher = _padding == null ? new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding);
         byte[] keyByte = _encoding.GetBytes(key);
         _cipher.Init(forEncrypt, new KeyParameter(keyByte));
         return _cipher.DoFinal(input);
     }
     catch (Org.BouncyCastle.Crypto.CryptoException ex)
     {
         throw new CryptoException("BCEngine CryptoException", ex);
     }
 }
Exemplo n.º 8
0
        public override void PerformTest()
        {
            BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEngine()));
            SimpleTest test = new PbeTest(this, 0, cipher, sample1, 64);

            test.PerformTest();

            cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEdeEngine()));
            test = new PbeTest(this, 1, cipher, sample2, 192);

            test.PerformTest();

            cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new RC2Engine()));
            test = new PbeTest(this, 2, cipher, sample3, 0);

            test.PerformTest();

            //
            // RFC 3211 tests
            //
            char[] password = "******".ToCharArray();
            PbeParametersGenerator generator = new Pkcs5S2ParametersGenerator();

            byte[] salt = Hex.Decode("1234567878563412");

            generator.Init(
                PbeParametersGenerator.Pkcs5PasswordToBytes(password),
                salt,
                5);

            if (!AreEqual(((KeyParameter)generator.GenerateDerivedParameters("DES", 64)).GetKey(),
                Hex.Decode("d1daa78615f287e6")))
            {
                Fail("64 test failed");
            }

            password = "******".ToCharArray();

            generator.Init(
                PbeParametersGenerator.Pkcs5PasswordToBytes(password),
                salt,
                500);

            if (!AreEqual(((KeyParameter)generator.GenerateDerivedParameters("DESEDE", 192)).GetKey(),
                Hex.Decode("6a8970bf68c92caea84a8df28510858607126380cc47ab2d")))
            {
                Fail("192 test failed");
            }
        }
Exemplo n.º 9
0
        public void doTestPadding(
			IBlockCipherPadding  padding,
			SecureRandom        rand,
			byte[]              ffVector,
			byte[]              ZeroVector)
        {
            PaddedBufferedBlockCipher    cipher = new PaddedBufferedBlockCipher(new DesEngine(), padding);
            KeyParameter                 key = new KeyParameter(Hex.Decode("0011223344556677"));

            //
            // ff test
            //
            byte[]    data = { (byte)0xff, (byte)0xff, (byte)0xff, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0 };

            if (ffVector != null)
            {
                padding.AddPadding(data, 3);

                if (!AreEqual(data, ffVector))
                {
                    Fail("failed ff test for " + padding.PaddingName);
                }
            }

            //
            // zero test
            //
            if (ZeroVector != null)
            {
                data = new byte[8];
                padding.AddPadding(data, 4);

                if (!AreEqual(data, ZeroVector))
                {
                    Fail("failed zero test for " + padding.PaddingName);
                }
            }

            for (int i = 1; i != 200; i++)
            {
                data = new byte[i];

                rand.NextBytes(data);

                blockCheck(cipher, padding, key, data);
            }
        }
Exemplo n.º 10
0
        public static AesEncyrption getInstance()
        {


            if (instance == null)
            {

                try
                {
                    if (string.IsNullOrEmpty(_encryptionKey))
                    {
                        Initalize();
                    }
                    AesEncyrption bcEngine = new AesEncyrption();
                    KeyParameter keyParam = new KeyParameter(Encoding.UTF8.GetBytes(_encryptionKey));
                    ICipherParameters param = new ParametersWithIV(keyParam, iv);

                    //create decrypt/encryptor cipher
                    IBlockCipherPadding padding = new Pkcs7Padding();
                    BufferedBlockCipher decrypt = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), padding);
                    decrypt.Reset();
                    decrypt.Init(false, param);
                    bcEngine.setDecryptCipher(decrypt);

                    BufferedBlockCipher encrypt = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), padding);
                    encrypt.Reset();
                    encrypt.Init(true, param);
                    bcEngine.setEncryptCipher(encrypt);

                    instance = bcEngine;
                }
                catch (Exception)
                {

                    throw;
                }



            }
            return instance;

        }
Exemplo n.º 11
0
 /// <summary>
 /// Symmetric encryption with AES/CBC/PKCS7.
 /// </summary>
 /// <param name="message">Message to be encrypted.</param>
 /// <param name="key">Private key for use with encryption.</param>
 /// <returns>Message in cipher text.</returns>
 public static byte[] Encrypt( byte[] message, byte[] key )
 {
     PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CbcBlockCipher( new AesEngine() ), new Pkcs7Padding() );
     cipher.Init( true, new KeyParameter( key ) );
     return cipher.DoFinal( message );
 }
Exemplo n.º 12
0
 /// <summary>
 /// Symmetric decryption with AES/CBC/PKCS7.
 /// </summary>
 /// <param name="cipherText">Message to be decrypted.</param>
 /// <param name="key">Private key for use with decryption.</param>
 /// <returns>Plain text message.</returns>
 public static byte[] Decrypt( byte[] cipherText, byte[] key )
 {
     PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CbcBlockCipher( new AesEngine() ), new Pkcs7Padding() );
     cipher.Init( false, new KeyParameter( key ) );
     return cipher.DoFinal( cipherText );
 }
Exemplo n.º 13
0
		/// <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);
		}
Exemplo n.º 14
0
		/// <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);
		}
Exemplo n.º 15
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();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Encapsulates the specified links into a CCF container.
        /// </summary>
        /// <param name="name">The name of the package.</param>
        /// <param name="links">The links.</param>
        /// <returns>
        /// CCF container.
        /// </returns>
        public static byte[] CreateCCF(string name, string[] links)
        {
            var sb = new StringBuilder();

            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.Append("<CryptLoad>");
            sb.Append("<Package service=\"\" name=\"" + name + "\" url=\"Directlinks\">");

            foreach (var link in links)
            {
                sb.Append("<Download Url=\"" + link + "\">");
                sb.Append("<Url>" + link + "</Url>");
              //sb.Append("<FileName></FileName>");
              //sb.Append("<FileSize></FileSize>");
                sb.Append("</Download>");
            }

            sb.Append("</Package>");
            sb.Append("</CryptLoad>");

            var aes = new AesEngine();
            var cbc = new CbcBlockCipher(aes);
            var pk7 = new Pkcs7Padding();
            var pad = new PaddedBufferedBlockCipher(cbc, pk7);

            pad.Init(true, new ParametersWithIV(new KeyParameter(CCFKey), CCFIV));

            return pad.DoFinal(Encoding.UTF8.GetBytes(sb.ToString()));
        }
Exemplo n.º 17
0
        /// <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);
        }
Exemplo n.º 18
0
        private void EncryptDataAes256CbcPkcs7(byte[] dataToEncrypt)
        {
            if (_key != null && _key.Length != 32)
                throw new Exception("Explicit data encryption key is not of required length for encryption method");
            
            if (_key == null)
            {
                // No explicit key was provided, we're going to generate our own.
                _key = new byte[32];
                RandomUtil.SecureRandomBc.NextBytes(_key);
            }

            _iv = new byte[16];
            RandomUtil.SecureRandomBc.NextBytes(_iv);

            var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesFastEngine()), new Pkcs7Padding());
            cipher.Init(true, new ParametersWithIV(new KeyParameter(_key), _iv));

            _data = cipher.DoFinal(dataToEncrypt);
        }
Exemplo n.º 19
0
        /// <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);
        }
Exemplo n.º 20
0
        private void StaticTest()
        {
            FpCurve curve = new FpCurve(
                new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
                new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
                new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
                new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDH",
                new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
                parameters);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDH",
                curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q
                parameters);

            AsymmetricCipherKeyPair p1 = new AsymmetricCipherKeyPair(pubKey, priKey);
            AsymmetricCipherKeyPair p2 = new AsymmetricCipherKeyPair(pubKey, priKey);

            //
            // stream test
            //
            IesEngine i1 = new IesEngine(
                new ECDHBasicAgreement(),
                new Kdf2BytesGenerator(new Sha1Digest()),
                new HMac(new Sha1Digest()));
            IesEngine i2 = new IesEngine(
                new ECDHBasicAgreement(),
                new Kdf2BytesGenerator(new Sha1Digest()),
                new HMac(new Sha1Digest()));
            byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
            IesParameters p = new IesParameters(d, e, 64);

            i1.Init(true, p1.Private, p2.Public, p);
            i2.Init(false, p2.Private, p1.Public, p);

            byte[] message = Hex.Decode("1234567890abcdef");

            byte[] out1 = i1.ProcessBlock(message, 0, message.Length);

            if (!AreEqual(out1, Hex.Decode("2442ae1fbf90dd9c06b0dcc3b27e69bd11c9aee4ad4cfc9e50eceb44")))
            {
                Fail("stream cipher test failed on enc");
            }

            byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length);

            if (!AreEqual(out2, message))
            {
                Fail("stream cipher test failed");
            }

            //
            // twofish with CBC
            //
            BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
                new CbcBlockCipher(new TwofishEngine()));
            BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
                new CbcBlockCipher(new TwofishEngine()));
            i1 = new IesEngine(
                new ECDHBasicAgreement(),
                new Kdf2BytesGenerator(new Sha1Digest()),
                new HMac(new Sha1Digest()),
                c1);
            i2 = new IesEngine(
                new ECDHBasicAgreement(),
                new Kdf2BytesGenerator(new Sha1Digest()),
                new HMac(new Sha1Digest()),
                c2);
            d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
            p = new IesWithCipherParameters(d, e, 64, 128);

            i1.Init(true, p1.Private, p2.Public, p);
            i2.Init(false, p2.Private, p1.Public, p);

            message = Hex.Decode("1234567890abcdef");

            out1 = i1.ProcessBlock(message, 0, message.Length);

            if (!AreEqual(out1, Hex.Decode("2ea288651e21576215f2424bbb3f68816e282e3931b44bd1c429ebdb5f1b290cf1b13309")))
            {
                Fail("twofish cipher test failed on enc");
            }

            out2 = i2.ProcessBlock(out1, 0, out1.Length);

            if (!AreEqual(out2, message))
            {
                Fail("twofish cipher test failed");
            }
        }
Exemplo n.º 21
0
        /// <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;
        }
Exemplo n.º 22
0
		private void DoTest(
			AsymmetricCipherKeyPair	p1,
			AsymmetricCipherKeyPair	p2)
		{
			//
			// stream test
			//
			IesEngine i1 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()));
			IesEngine i2 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()));
			byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
			byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
			IesParameters  p = new IesParameters(d, e, 64);

			i1.Init(true, p1.Private, p2.Public, p);
			i2.Init(false, p2.Private, p1.Public, p);

			byte[] message = Hex.Decode("1234567890abcdef");

			byte[] out1 = i1.ProcessBlock(message, 0, message.Length);

			byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length);

			if (!AreEqual(out2, message))
			{
				Fail("stream cipher test failed");
			}

			//
			// twofish with CBC
			//
			BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
				new CbcBlockCipher(new TwofishEngine()));
			BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
				new CbcBlockCipher(new TwofishEngine()));
			i1 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()),
				c1);
			i2 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()),
				c2);
			d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
			e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
			p = new IesWithCipherParameters(d, e, 64, 128);

			i1.Init(true, p1.Private, p2.Public, p);
			i2.Init(false, p2.Private, p1.Public, p);

			message = Hex.Decode("1234567890abcdef");

			out1 = i1.ProcessBlock(message, 0, message.Length);

			out2 = i2.ProcessBlock(out1, 0, out1.Length);

			if (!AreEqual(out2, message))
			{
				Fail("twofish cipher test failed");
			}
		}
Exemplo n.º 23
0
        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");
            }
        }
Exemplo n.º 24
0
		private void process()
		{
			/* 
			* Setup the DESede cipher engine, create a PaddedBufferedBlockCipher
			* in CBC mode.
			*/
			cipher = new PaddedBufferedBlockCipher(
				new CbcBlockCipher(new DesEdeEngine()));

			/*
			* The input and output streams are currently set up
			* appropriately, and the key bytes are ready to be
			* used.
			*
			*/

			if (encrypt)
			{
				performEncrypt(key);
			}
			else
			{
				performDecrypt(key);
			}

			// after processing clean up the files
			try
			{
				inStr.Close();
				outStr.Flush();
				outStr.Close();
			}
			catch (IOException)
			{
			}
		}
Exemplo n.º 25
0
		/// <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);
		}
Exemplo n.º 26
0
        private static Stream CreateStream(Stream s, bool bEncrypt, byte[] pbKey, byte[] pbIV)
        {
            StandardAesEngine.ValidateArguments(s, bEncrypt, pbKey, pbIV);

            byte[] pbLocalIV = new byte[16];
            Array.Copy(pbIV, pbLocalIV, 16);

            byte[] pbLocalKey = new byte[32];
            Array.Copy(pbKey, pbLocalKey, 32);

            #if !KeePassRT
            RijndaelManaged r = new RijndaelManaged();
            if(r.BlockSize != 128) // AES block size
            {
                Debug.Assert(false);
                r.BlockSize = 128;
            }

            r.IV = pbLocalIV;
            r.KeySize = 256;
            r.Key = pbLocalKey;
            r.Mode = m_rCipherMode;
            r.Padding = m_rCipherPadding;

            ICryptoTransform iTransform = (bEncrypt ? r.CreateEncryptor() : r.CreateDecryptor());
            Debug.Assert(iTransform != null);
            if(iTransform == null) throw new SecurityException("Unable to create Rijndael transform!");

            return new CryptoStream(s, iTransform, bEncrypt ? CryptoStreamMode.Write :
                CryptoStreamMode.Read);
            #else
            AesEngine aes = new AesEngine();
            CbcBlockCipher cbc = new CbcBlockCipher(aes);
            PaddedBufferedBlockCipher bc = new PaddedBufferedBlockCipher(cbc,
                new Pkcs7Padding());
            KeyParameter kp = new KeyParameter(pbLocalKey);
            ParametersWithIV prmIV = new ParametersWithIV(kp, pbLocalIV);
            bc.Init(bEncrypt, prmIV);

            IBufferedCipher cpRead = (bEncrypt ? null : bc);
            IBufferedCipher cpWrite = (bEncrypt ? bc : null);
            return new CipherStream(s, cpRead, cpWrite);
            #endif
        }
Exemplo n.º 27
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());
        }
Exemplo n.º 28
0
        /// <summary>
        /// Encapsulates the specified links into a DLC container.
        /// </summary>
        /// <param name="name">The name of the package.</param>
        /// <param name="links">The links.</param>
        /// <returns>
        /// Base-64-encoded DLC container.
        /// </returns>
        public static string CreateDLC(string name, string[] links)
        {
            var sb = new StringBuilder();

            sb.Append("<dlc>");
            sb.Append("<header>");
            sb.Append("<generator>");
            sb.Append("<app>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("RS TV Show Tracker")) + "</app>");
            sb.Append("<version>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("1.0")) + "</version>");
            sb.Append("<url>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("http://lab.rolisoft.net/")) + "</url>");
            sb.Append("</generator>");
            sb.Append("<dlcxmlversion>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("20_02_2008")) + "</dlcxmlversion>");
            sb.Append("</header>");
            sb.Append("<content>");
            sb.Append("<package name=\"" + Convert.ToBase64String(Encoding.UTF8.GetBytes(name)) + "\">");

            foreach (var link in links)
            {
                sb.Append("<file>");
                sb.Append("<url>" + Convert.ToBase64String(Encoding.UTF8.GetBytes(link)) + "</url>");
              //sb.Append("<filename></filename>");
              //sb.Append("<size></size>");
                sb.Append("</file>");
            }

            sb.Append("</package>");
            sb.Append("</content>");
            sb.Append("</dlc>");

            var xml = Convert.ToBase64String(Encoding.UTF8.GetBytes(sb.ToString()));
            var key = BitConverter.ToString(new SHA256CryptoServiceProvider().ComputeHash(BitConverter.GetBytes(DateTime.Now.ToBinary()))).Replace("-", string.Empty).Substring(0, 16);

            var srv = Utils.GetURL(DLCCrypt, "&data=" + key + "&lid=" + Convert.ToBase64String(Encoding.UTF8.GetBytes("http://lab.rolisoft.net/_3600")) + "&version=1.0&client=rstvshowtracker");
            var rcr = Regex.Match(srv, @"<rc>(.+)</rc>");

            if (!rcr.Groups[1].Success)
            {
                throw new Exception("The jDownloader DLC encryption service did not return an encryption key.");
            }

            var enc = rcr.Groups[1].Value;

            var aes = new AesEngine();
            var cbc = new CbcBlockCipher(aes);
            var zbp = new ZeroBytePadding();
            var pad = new PaddedBufferedBlockCipher(cbc, zbp);

            pad.Init(true, new ParametersWithIV(new KeyParameter(Encoding.ASCII.GetBytes(key)), Encoding.ASCII.GetBytes(key)));

            var xm2 = Convert.ToBase64String(pad.DoFinal(Encoding.ASCII.GetBytes(xml)));

            return xm2 + enc;
        }
Exemplo n.º 29
0
		/// <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);
		}
Exemplo n.º 30
0
		private void StaticTest()
		{
			FpCurve curve = new FpCurve(
				new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
				new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
				new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b

			ECDomainParameters parameters = new ECDomainParameters(
				curve,
				curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
				new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n

			ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
				"ECDH",
				new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
				parameters);

			ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
				"ECDH",
				curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q
				parameters);

			AsymmetricCipherKeyPair p1 = new AsymmetricCipherKeyPair(pubKey, priKey);
			AsymmetricCipherKeyPair p2 = new AsymmetricCipherKeyPair(pubKey, priKey);

			//
			// stream test
			//
			IesEngine i1 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()));
			IesEngine i2 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()));
			byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
			byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
			IesParameters p = new IesParameters(d, e, 64);

			i1.Init(true, p1.Private, p2.Public, p);
			i2.Init(false, p2.Private, p1.Public, p);

			byte[] message = Hex.Decode("1234567890abcdef");

			byte[] out1 = i1.ProcessBlock(message, 0, message.Length);

			if (!AreEqual(out1, Hex.Decode("468d89877e8238802403ec4cb6b329faeccfa6f3a730f2cdb3c0a8e8")))
			{
				Fail("stream cipher test failed on enc");
			}

			byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length);

			if (!AreEqual(out2, message))
			{
				Fail("stream cipher test failed");
			}

			//
			// twofish with CBC
			//
			BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
				new CbcBlockCipher(new TwofishEngine()));
			BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
				new CbcBlockCipher(new TwofishEngine()));
			i1 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()),
				c1);
			i2 = new IesEngine(
				new ECDHBasicAgreement(),
				new Kdf2BytesGenerator(new Sha1Digest()),
				new HMac(new Sha1Digest()),
				c2);
			d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
			e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
			p = new IesWithCipherParameters(d, e, 64, 128);

			i1.Init(true, p1.Private, p2.Public, p);
			i2.Init(false, p2.Private, p1.Public, p);

			message = Hex.Decode("1234567890abcdef");

			out1 = i1.ProcessBlock(message, 0, message.Length);

			if (!AreEqual(out1, Hex.Decode("b8a06ea5c2b9df28b58a0a90a734cde8c9c02903e5c220021fe4417410d1e53a32a71696")))
			{
				Fail("twofish cipher test failed on enc");
			}

			out2 = i2.ProcessBlock(out1, 0, out1.Length);

			if (!AreEqual(out2, message))
			{
				Fail("twofish cipher test failed");
			}
		}
        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();
        }