Inheritance: ICipherParameters
Example #1
0
 /** Creates a new instance of AESCipher */
 public AESCipherCBCnoPad(bool forEncryption, byte[] key)
 {
     IBlockCipher aes = new AesFastEngine();
     cbc = new CbcBlockCipher(aes);
     KeyParameter kp = new KeyParameter(key);
     cbc.Init(forEncryption, kp);
 }
Example #2
0
		public override void PerformTest()
		{
			byte[] key = Hex.Decode("9661410AB797D8A9EB767C21172DF6C7");
			byte[] iv = Hex.Decode("4B5C2F003E67F39557A8D26F3DA2B155");
			ICipherParameters kp = new KeyParameter(key);
			ICipherParameters kpwiv = new ParametersWithIV(kp, iv);

			VmpcKsa3Engine engine = new VmpcKsa3Engine();

			try
			{
				engine.Init(true, kp);
				Fail("Init failed to throw expected exception");
			}
			catch (ArgumentException)
			{
				// Expected
			}

			engine.Init(true, kpwiv);
			checkEngine(engine);

			engine.Reset();
			byte[] output = checkEngine(engine);

			engine.Init(false, kpwiv);
			byte[] recovered = new byte[output.Length];
			engine.ProcessBytes(output, 0, output.Length, recovered, 0);

			if (!Arrays.AreEqual(input, recovered))
			{
				Fail("decrypted bytes differ from original bytes");
			}
		}
        public void DecodeCryptogram(string key)
        {
            byte[] result = new byte[cryptogramByte.Count];
            byte[] pass = Encoding.ASCII.GetBytes(key);

            try
            {
            RC4Engine rc4 = new RC4Engine();
            KeyParameter keyParam = new KeyParameter(pass);
            rc4.Init(true, keyParam);
            rc4.ProcessBytes(cryptogramByte.ToArray(), 0, cryptogramByte.Count, result, 0);
            }
            catch (Exception e)
            {
            Console.WriteLine(e.Message);
            }

            if (CheckDecryptedText(result))
            {
            Console.Write("klucz: " + key + ": ");

            foreach (var c in result)
            {
                if (c != 0)
                {
                    Console.Write((char)c);
                }
            }
            Console.WriteLine();
            }
        }
Example #4
0
		public override void PerformTest()
		{
			ICipherParameters kp = new KeyParameter(
				Hex.Decode("9661410AB797D8A9EB767C21172DF6C7"));
			ICipherParameters kpwiv = new ParametersWithIV(kp,
				Hex.Decode("4B5C2F003E67F39557A8D26F3DA2B155"));

            int offset = 117;
            byte[] m = new byte[512];
			for (int i = 0; i < 256; i++)
			{
				m[offset + i] = (byte)i;
			}

            VmpcMac mac = new VmpcMac();
			mac.Init(kpwiv);

			mac.BlockUpdate(m, offset, 256);

			byte[] output = new byte[20];
			mac.DoFinal(output, 0);

			if (!Arrays.AreEqual(output, output1))
			{
				Fail("Fail",
					Hex.ToHexString(output1),
					Hex.ToHexString(output));
			}
		}
        /// <exception cref="IOException"></exception>
        public Chacha20Poly1305(TlsContext context)
        {
            if (!TlsUtilities.IsTlsV12(context))
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.context = context;

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, 64);

            KeyParameter client_write_key = new KeyParameter(key_block, 0, 32);
            KeyParameter server_write_key = new KeyParameter(key_block, 32, 32);

            this.encryptCipher = new ChaChaEngine(20);
            this.decryptCipher = new ChaChaEngine(20);

            KeyParameter encryptKey, decryptKey;
            if (context.IsServer)
            {
                encryptKey = server_write_key;
                decryptKey = client_write_key;
            }
            else
            {
                encryptKey = client_write_key;
                decryptKey = server_write_key;
            }

            byte[] dummyNonce = new byte[8];

            this.encryptCipher.Init(true, new ParametersWithIV(encryptKey, dummyNonce));
            this.decryptCipher.Init(false, new ParametersWithIV(decryptKey, dummyNonce));
        }
Example #6
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);
			}
		}
        protected virtual ParametersWithIV CreateParametersWithIV(KeyParameter key,
			byte[] buf, ref int off, int len)
		{
			ParametersWithIV ivParams = new ParametersWithIV(key, buf, off, len);
			off += len;
			return ivParams;
		}
		public void Init(
			bool				forWrapping,
			ICipherParameters	parameters)
		{
			this.forWrapping = forWrapping;

			if (parameters is ParametersWithRandom)
			{
				parameters = ((ParametersWithRandom) parameters).Parameters;
			}

			if (parameters is KeyParameter)
			{
				this.param = (KeyParameter) parameters;
			}
			else if (parameters is ParametersWithIV)
			{
				ParametersWithIV pIV = (ParametersWithIV) parameters;
				byte[] iv = pIV.GetIV();

				if (iv.Length != 8)
					throw new ArgumentException("IV length not equal to 8", "parameters");

				this.iv = iv;
				this.param = (KeyParameter) pIV.Parameters;
			}
			else
			{
				// TODO Throw an exception for bad parameters?
			}
		}
		public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
		{
			byte[] keyBytes = contentEncryptionKey.GetKey();

			string rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID);
			IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName);

			// Note: In Java build, the IV is automatically generated in JCE layer
			int ivLength = Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16;
			byte[] iv = new byte[ivLength];
			random.NextBytes(iv);

			ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv);
			keyWrapper.Init(true, new ParametersWithRandom(parameters, random));
        	Asn1OctetString encryptedKey = new DerOctetString(
				keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

			DerSequence seq = new DerSequence(
				new DerObjectIdentifier(keyEncryptionKeyOID),
				new DerOctetString(iv));

			AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(
				PkcsObjectIdentifiers.IdAlgPwriKek, seq);

			return new RecipientInfo(new PasswordRecipientInfo(
				keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey));
		}
        private byte[] GenerateDerivedKey(
            int dkLen)
        {
            int     hLen = hMac.GetMacSize();
            int     l = (dkLen + hLen - 1) / hLen;
            byte[]  iBuf = new byte[4];
            byte[]  outBytes = new byte[l * hLen];
            int     outPos = 0;

            ICipherParameters param = new KeyParameter(mPassword);

            hMac.Init(param);

            for (int i = 1; i <= l; i++)
            {
                // Increment the value in 'iBuf'
                int pos = 3;
                while (++iBuf[pos] == 0)
                {
                    --pos;
                }

                F(mSalt, mIterationCount, iBuf, outBytes, outPos);
                outPos += hLen;
            }

            return outBytes;
        }
 private IBufferedCipher CreateRijndael(WinzipAesEncryptionData winzipAesEncryptionData)
 {
     var blockCipher = new BufferedBlockCipher(new RijndaelEngine());
     var param = new KeyParameter(winzipAesEncryptionData.KeyBytes);
     blockCipher.Init(true, param);
     return blockCipher;
 }
Example #12
0
 /**
  * Base constructor.
  *
  * @param key key to be used by underlying cipher
  * @param macSize macSize in bits
  * @param nonce nonce to be used
  * @param associatedText associated text, if any
  */
 public CcmParameters(KeyParameter key, int macSize, byte[] nonce, byte[] associatedText)
 {
     this.key = key;
     this.nonce = nonce;
     this.macSize = macSize;
     this.associatedText = associatedText;
 }
Example #13
0
        private byte[] Hash()
        {
            byte[] array = DataConverter.BigEndian.GetBytes(block);
            ICipherParameters param = new KeyParameter(password);

            hMac.Init(param);
            hMac.BlockUpdate(salt, 0, salt.Length);

            hMac.BlockUpdate(array, 0, array.Length);
            byte[] array2 = new byte[20];
            hMac.DoFinal(array2, 0);

            hMac.Init(param);

            byte[] array3 = new byte[20];
            Buffer.BlockCopy(array2, 0, array3, 0, 20);
            int num = 2;
            while (num <= (long)((ulong)iterations))
            {
                hMac.BlockUpdate(array2, 0, array2.Length);
                hMac.DoFinal(array2, 0);
                for (int i = 0; i < 20; i++)
                {
                    array3[i] ^= array2[i];
                }
                num++;
            }
            block += 1u;
            return array3;
        }
Example #14
0
		private static ParametersWithIV CreateParametersWithIV(KeyParameter key,
			byte[] buf, ref int off, int len)
		{
			ParametersWithIV ivParams = new ParametersWithIV(key, buf, off, len);
			off += len;
			return ivParams;
		}
Example #15
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);
 }
		/**
		 * Base constructor.
		 * 
		 * @param key key to be used by underlying cipher
		 * @param macSize macSize in bits
		 * @param nonce nonce to be used
		 * @param associatedText associated text, if any
		 */
		public CcmParameters(
			KeyParameter	key,
			int				macSize,
			byte[]			nonce,
			byte[]			associatedText)
			: base(key, macSize, nonce, associatedText)
		{
		}
Example #17
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);
 }
		private void checkKeyParameter(
			KeyParameter	key,
			Type			expectedType,
			byte[]			expectedBytes)
		{
			Assert.IsTrue(expectedType.IsInstanceOfType(key));
			Assert.IsTrue(Arrays.AreEqual(expectedBytes, key.GetKey()));
		}
Example #19
0
        /// <exception cref="IOException"></exception>
        public TlsAeadCipher(TlsContext context, IAeadBlockCipher clientWriteCipher, IAeadBlockCipher serverWriteCipher,
            int cipherKeySize, int macSize)
        {
            if (!TlsUtilities.IsTlsV12(context))
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.context = context;
            this.macSize = macSize;

            // NOTE: Valid for RFC 5288/6655 ciphers but may need review for other AEAD ciphers
            this.nonce_explicit_length = 8;

            // TODO SecurityParameters.fixed_iv_length
            int fixed_iv_length = 4;

            int key_block_size = (2 * cipherKeySize) + (2 * fixed_iv_length);

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);

            int offset = 0;

            KeyParameter client_write_key = new KeyParameter(key_block, offset, cipherKeySize);
            offset += cipherKeySize;
            KeyParameter server_write_key = new KeyParameter(key_block, offset, cipherKeySize);
            offset += cipherKeySize;
            byte[] client_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;
            byte[] server_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;

            if (offset != key_block_size)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            KeyParameter encryptKey, decryptKey;
            if (context.IsServer)
            {
                this.encryptCipher = serverWriteCipher;
                this.decryptCipher = clientWriteCipher;
                this.encryptImplicitNonce = server_write_IV;
                this.decryptImplicitNonce = client_write_IV;
                encryptKey = server_write_key;
                decryptKey = client_write_key;
            }
            else
            {
                this.encryptCipher = clientWriteCipher;
                this.decryptCipher = serverWriteCipher;
                this.encryptImplicitNonce = client_write_IV;
                this.decryptImplicitNonce = server_write_IV;
                encryptKey = client_write_key;
                decryptKey = server_write_key;
            }

            byte[] dummyNonce = new byte[fixed_iv_length + nonce_explicit_length];

            this.encryptCipher.Init(true, new AeadParameters(encryptKey, 8 * macSize, dummyNonce));
            this.decryptCipher.Init(false, new AeadParameters(decryptKey, 8 * macSize, dummyNonce));
        }
Example #20
0
//		protected CipherTest(
//			SimpleTest[]	tests)
//		{
//			_tests = tests;
//		}

		protected CipherTest(
			SimpleTest[]	tests,
			IBlockCipher	engine,
			KeyParameter	validKey)
		{
			_tests = tests;
			_engine = engine;
			_validKey = validKey;
		}
		private void initCipher(bool forEncryption, IBlockCipher cipher,
								byte[] key_block, int key_size, int key_offset, int iv_offset)
		{
			KeyParameter key_parameter = new KeyParameter(key_block, key_offset,
				key_size);
			ParametersWithIV parameters_with_iv = new ParametersWithIV(
				key_parameter, key_block, iv_offset, cipher.GetBlockSize());
			cipher.Init(forEncryption, parameters_with_iv);
		}
Example #22
0
 static JwtKey LoadSymmetricKey(byte[] keyBytes)
 {
     ICipherParameters key = new KeyParameter(keyBytes);
     return new JwtKey
     {
         PrivateKey = key,
         PublicKey = key,
     };
 }
 internal PbeMethod(
     SymmetricKeyAlgorithmTag  encAlgorithm,
     S2k                       s2k,
     KeyParameter              key)
 {
     this.encAlgorithm = encAlgorithm;
     this.s2k = s2k;
     this.key = key;
 }
Example #24
0
        static DataDecoder()
        {
            byte[] bKey = System.Text.Encoding.ASCII.GetBytes("Implict error #56");
            var tiger = new TigerDigest();
            tiger.BlockUpdate(bKey, 0, bKey.Length);

            var bb = new byte[24];
            tiger.DoFinal(bb, 0);

            Key = new KeyParameter(bb);
        }
Example #25
0
        public void ThreadRun()
        {
            int i = 0;
            byte[] clearText = new byte[kryptogram.Length];
            string czescKlucza1 = "";
            while (i <= szukaj.max)
            {
                i = szukaj.wykonane();

                if (i <= szukaj.max)
                {
                    czescKlucza1 = i.ToString("X");
                    while (czescKlucza1.Length < 8)
                    {
                        czescKlucza1 = "0" + czescKlucza1;
                    }

                    String klucz = czescKlucza1.ToLower() + czescKlucza2;
                    try
                    {
                        RC4Engine rc4 = new RC4Engine();
                        KeyParameter keyParam = new KeyParameter(System.Text.Encoding.ASCII.GetBytes(klucz));
                        rc4.Init(false, keyParam);
                        rc4.ProcessBytes(kryptogram, 0, kryptogram.Length, clearText, 0);

                    }
                    catch (Exception e)
                    {

                    }
                    bool zgodne = true;
                    for (int j = 0; j < clearText.Length; j++)
                    {
                        if (!alfabet.lista_znakow.Contains((char)clearText[j]))
                        {
                            zgodne = false;
                        }
                    }
                    //jeśli znalazl dobry klucz
                    if (zgodne)
                    {
                        Console.Write("Wiadomosc : ");
                        foreach (byte x in clearText)
                        {
                            Console.Write("{0} ", (char)x);
                        }
                        Console.WriteLine("");
                        Console.WriteLine(" klucz: {0}",klucz);
                        szukaj.ileZrobiono = szukaj.max;
                    }

                }
            }
        }
Example #26
0
		/**
		* Generate a new instance of an TlsMac.
		*
		* @param digest    The digest to use.
		* @param key_block A byte-array where the key for this mac is located.
		* @param offset    The number of bytes to skip, before the key starts in the buffer.
		* @param len       The length of the key.
		*/
		internal TlsMac(
			IDigest	digest,
			byte[]	key_block,
			int		offset,
			int		len)
		{
			this.mac = new HMac(digest);
			KeyParameter param = new KeyParameter(key_block, offset, len);
			this.mac.Init(param);
			this.seqNo = 0;
		}
		public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
		{
			byte[] keyBytes = contentEncryptionKey.GetKey();

            IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id);
			keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
        	Asn1OctetString encryptedKey = new DerOctetString(
				keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

			return new RecipientInfo(new KekRecipientInfo(kekIdentifier, keyEncryptionAlgorithm, encryptedKey));
		}
Example #28
0
 public override ICipherParameters GenParam()
 {
     string pass = SafeUtil.GenPass(_Uk.TbPass.Text, _Uk.TbPass.MaxLength);
     ICipherParameters param = new KeyParameter(Encoding.Default.GetBytes(pass));
     if (_Uk.TbSalt.Visible)
     {
         pass = SafeUtil.GenPass(_Uk.TbSalt.Text, _Uk.TbSalt.MaxLength);
         param = new ParametersWithIV(param, Encoding.Default.GetBytes(pass));
     }
     return param;
 }
        /**
         * Construct a X9.31 secure random generator using the passed in engine and key. If predictionResistant is true the
         * generator will be reseeded on each request.
         *
         * @param engine a block cipher to use as the operator.
         * @param key the block cipher key to initialise engine with.
         * @param predictionResistant true if engine to be reseeded on each use, false otherwise.
         * @return a SecureRandom.
         */
        public X931SecureRandom Build(IBlockCipher engine, KeyParameter key, bool predictionResistant)
        {
            if (mDateTimeVector == null)
            {
                mDateTimeVector = new byte[engine.GetBlockSize()];
                Pack.UInt64_To_BE((ulong)DateTimeUtilities.CurrentUnixMs(), mDateTimeVector, 0);
            }

            engine.Init(true, key);

            return new X931SecureRandom(mRandom, new X931Rng(engine, mDateTimeVector, mEntropySourceProvider.Get(engine.GetBlockSize() * 8)), predictionResistant);
        }
Example #30
0
        /// <exception cref="IOException"></exception>
        public Chacha20Poly1305(TlsContext context)
        {
            if (!TlsUtilities.IsTlsV12(context))
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.context = context;

            int cipherKeySize = 32;
            // TODO SecurityParameters.fixed_iv_length
            int fixed_iv_length = 12;
            // TODO SecurityParameters.record_iv_length = 0

            int key_block_size = (2 * cipherKeySize) + (2 * fixed_iv_length);

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);

            int offset = 0;

            KeyParameter client_write_key = new KeyParameter(key_block, offset, cipherKeySize);
            offset += cipherKeySize;
            KeyParameter server_write_key = new KeyParameter(key_block, offset, cipherKeySize);
            offset += cipherKeySize;
            byte[] client_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;
            byte[] server_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
            offset += fixed_iv_length;

            if (offset != key_block_size)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.encryptCipher = new ChaCha7539Engine();
            this.decryptCipher = new ChaCha7539Engine();

            KeyParameter encryptKey, decryptKey;
            if (context.IsServer)
            {
                encryptKey = server_write_key;
                decryptKey = client_write_key;
                this.encryptIV = server_write_IV;
                this.decryptIV = client_write_IV;
            }
            else
            {
                encryptKey = client_write_key;
                decryptKey = server_write_key;
                this.encryptIV = client_write_IV;
                this.decryptIV = server_write_IV;
            }

            this.encryptCipher.Init(true, new ParametersWithIV(encryptKey, encryptIV));
            this.decryptCipher.Init(false, new ParametersWithIV(decryptKey, decryptIV));
        }
        /// <summary>
        /// Calculates the 64 byte checksum in accordance with HMAC-SHA512
        /// </summary>
        /// <param name="input">The bytes to derive the checksum from</param>
        /// <param name="offset">Where to start calculating checksum in the input bytes</param>
        /// <param name="length">Length of buytes to use to calculate checksum</param>
        /// <param name="hmacKey">HMAC Key used to generate the checksum (note differing HMAC Keys provide unique checksums)</param>
        /// <returns></returns>
        public static byte[] HmacSha512Digest(byte[] input, int offset, int length, byte[] hmacKey)
        {
            byte[] output = new byte[64];
            HMac   _hmacsha512Obj;

            _hmacsha512Obj = new HMac(new Sha512Digest());
            ICipherParameters param = new Org.BouncyCastle.Crypto.Parameters.KeyParameter(hmacKey);

            _hmacsha512Obj.Init(param);
            _hmacsha512Obj.BlockUpdate(input, offset, length);
            _hmacsha512Obj.DoFinal(output, 0);
            return(output);
        }
Example #32
0
        /// <summary>
        /// 哈希计算
        /// </summary>
        /// <param name="data">输入字符串</param>
        /// <param name="key">密钥KEY</param>
        /// <param name="algorithm">密文算法,参考Algorithms.cs中提供的HMac algorithm</param>
        /// <returns>哈希值</returns>
        public static byte[] Compute(string data, string key, string algorithm)
        {
            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            var keyParameter = new Org.BouncyCastle.Crypto.Parameters.KeyParameter(Encoding.UTF8.GetBytes(key));
            var input        = Encoding.UTF8.GetBytes(data);
            var mac          = MacUtilities.GetMac(algorithm);

            mac.Init(keyParameter);
            mac.BlockUpdate(input, 0, input.Length);
            return(MacUtilities.DoFinal(mac));
        }
Example #33
0
 public FpeParameters(KeyParameter key, int radix, byte[] tweak) : this(key, radix, tweak, false)
 {
 }
Example #34
0
 /**
  * Base constructor.
  *
  * @param key key to be used by underlying cipher
  * @param macSize macSize in bits
  * @param nonce nonce to be used
  */
 public AeadParameters(KeyParameter key, int macSize, byte[] nonce)
     : this(key, macSize, nonce, null)
 {
 }
Example #35
0
 public CcmParameters(KeyParameter key, int macSize, byte[] nonce, byte[] associatedText) : base(key, macSize, nonce, associatedText)
 {
 }
Example #36
0
 public TweakableBlockCipherParameters(KeyParameter key, byte[] tweak)
 {
     this.key   = key;
     this.tweak = Arrays.Clone(tweak);
 }