コード例 #1
0
		public void Init(
			ICipherParameters parameters)
		{
			Reset();
			buf = new byte[blockSize];
			if (parameters is ParametersWithSBox)
			{
				ParametersWithSBox param = (ParametersWithSBox)parameters;

				//
				// Set the S-Box
				//
				param.GetSBox().CopyTo(this.S, 0);

				//
				// set key if there is one
				//
				if (param.Parameters != null)
				{
					workingKey = generateWorkingKey(((KeyParameter)param.Parameters).GetKey());
				}
			}
			else if (parameters is KeyParameter)
			{
				workingKey = generateWorkingKey(((KeyParameter)parameters).GetKey());
			}
			else
			{
				throw new ArgumentException("invalid parameter passed to Gost28147 init - "
					+ parameters.GetType().Name);
			}
		}
コード例 #2
0
ファイル: PssSigner.cs プロジェクト: nicecai/iTextSharp-4.1.6
		public virtual void Init(
			bool				forSigning,
			ICipherParameters	parameters)
		{
			if (parameters is ParametersWithRandom)
			{
				ParametersWithRandom p = (ParametersWithRandom) parameters;

				parameters = p.Parameters;
				random = p.Random;
			}
			else
			{
				if (forSigning)
				{
					random = new SecureRandom();
				}
			}

			cipher.Init(forSigning, parameters);

			RsaKeyParameters kParam;
			if (parameters is RsaBlindingParameters)
			{
				kParam = ((RsaBlindingParameters) parameters).PublicKey;
			}
			else
			{
				kParam = (RsaKeyParameters) parameters;
			}

			emBits = kParam.Modulus.BitLength - 1;

			block = new byte[(emBits + 7) / 8];
		}
コード例 #3
0
ファイル: DesSsh1Engine.cs プロジェクト: dlech/SshAgentLib
        public void Init(bool encrypting, ICipherParameters parameters)
        {
            if (!(parameters is KeyParameter))
              {
            throw new ArgumentException("Invalid parameter passed to "+
              "DesSsh1Engine init - " + parameters.GetType());
              }

              this.encrypting = encrypting;

              byte[] passphraseKey = (parameters as KeyParameter).GetKey();
              if (passphraseKey.Length !=16)
              {
            throw new ArgumentException("key size different than 16 bytes");
              }

              byte[] keyPart1 = new byte[8];
              byte[] keyPart2 = new byte[8];

              Array.Copy(passphraseKey, keyPart1, 8);
              Array.Copy(passphraseKey, 8, keyPart2, 0, 8);

              desEngine1 = new CbcBlockCipher(new DesEngine());
              desEngine2 = new CbcBlockCipher(new DesEngine());
              desEngine3 = new CbcBlockCipher(new DesEngine());

              desEngine1.Init(encrypting, new KeyParameter(keyPart1));
              desEngine2.Init(!encrypting, new KeyParameter(keyPart2));
              desEngine3.Init(encrypting, new KeyParameter(keyPart1));
        }
コード例 #4
0
        /**
         * Initialise the signer for signing or verification.
         *
         * @param forSigning true if for signing, false otherwise
         * @param param necessary parameters.
         */
        public void Init(
            bool				forSigning,
            ICipherParameters	parameters)
        {
            this.forSigning = forSigning;
            AsymmetricKeyParameter k;

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

            if (forSigning && !k.IsPrivate)
                throw new InvalidKeyException("Signing requires private key.");

            if (!forSigning && k.IsPrivate)
                throw new InvalidKeyException("Verification requires public key.");

            Reset();

            rsaEngine.Init(forSigning, parameters);
        }
コード例 #5
0
ファイル: RC532Engine.cs プロジェクト: KimikoMuffin/bc-csharp
		/**
        * initialise a RC5-32 cipher.
        *
        * @param forEncryption whether or not we are for encryption.
        * @param parameters the parameters required to set up the cipher.
        * @exception ArgumentException if the parameters argument is
        * inappropriate.
        */
        public virtual void Init(
            bool				forEncryption,
            ICipherParameters	parameters)
        {
            if (typeof(RC5Parameters).IsInstanceOfType(parameters))
            {
                RC5Parameters p = (RC5Parameters)parameters;

                _noRounds = p.Rounds;

                SetKey(p.GetKey());
            }
            else if (typeof(KeyParameter).IsInstanceOfType(parameters))
            {
                KeyParameter p = (KeyParameter)parameters;

                SetKey(p.GetKey());
            }
            else
            {
                throw new ArgumentException("invalid parameter passed to RC532 init - " + Platform.GetTypeName(parameters));
            }

            this.forEncryption = forEncryption;
        }
コード例 #6
0
ファイル: ECNRSigner.cs プロジェクト: htlp/itextsharp
		public void Init(
			bool				forSigning,
			ICipherParameters	parameters)
		{
			this.forSigning = forSigning;

			if (forSigning)
			{
				if (parameters is ParametersWithRandom)
				{
					ParametersWithRandom rParam = (ParametersWithRandom) parameters;

					this.random = rParam.Random;
					parameters = rParam.Parameters;
				}
				else
				{
					this.random = new SecureRandom();
				}

				if (!(parameters is ECPrivateKeyParameters))
					throw new InvalidKeyException("EC private key required for signing");

				this.key = (ECPrivateKeyParameters) parameters;
			}
			else
			{
				if (!(parameters is ECPublicKeyParameters))
					throw new InvalidKeyException("EC public key required for verification");

				this.key = (ECPublicKeyParameters) parameters;
			}
		}
コード例 #7
0
        /**
        * initialise a DESede cipher.
        *
        * @param forEncryption whether or not we are for encryption.
        * @param parameters the parameters required to set up the cipher.
        * @exception ArgumentException if the parameters argument is
        * inappropriate.
        */
        public override void Init(
            bool				forEncryption,
            ICipherParameters	parameters)
        {
            if (!(parameters is KeyParameter))
                throw new ArgumentException("invalid parameter passed to DESede init - " + parameters.GetType().ToString());

            byte[] keyMaster = ((KeyParameter)parameters).GetKey();
            if (keyMaster.Length != 24 && keyMaster.Length != 16)
                throw new ArgumentException("key size must be 16 or 24 bytes.");

            this.forEncryption = forEncryption;

            byte[] key1 = new byte[8];
            Array.Copy(keyMaster, 0, key1, 0, key1.Length);
            workingKey1 = GenerateWorkingKey(forEncryption, key1);

            byte[] key2 = new byte[8];
            Array.Copy(keyMaster, 8, key2, 0, key2.Length);
            workingKey2 = GenerateWorkingKey(!forEncryption, key2);

            if (keyMaster.Length == 24)
            {
                byte[] key3 = new byte[8];
                Array.Copy(keyMaster, 16, key3, 0, key3.Length);
                workingKey3 = GenerateWorkingKey(forEncryption, key3);
            }
            else        // 16 byte key
            {
                workingKey3 = workingKey1;
            }
        }
コード例 #8
0
        /**
        * Initialise the cipher and, possibly, the initialisation vector (IV).
        * If an IV isn't passed as part of the parameter, the IV will be all zeros.
        * An IV which is too short is handled in FIPS compliant fashion.
        *
        * @param forEncryption if true the cipher is initialised for
        *  encryption, if false for decryption.
        * @param param the key and other data required by the cipher.
        * @exception ArgumentException if the parameters argument is
        * inappropriate.
        */
        public void Init(
            bool				forEncryption, //ignored by this OFB mode
            ICipherParameters	parameters)
        {
			if (parameters is ParametersWithIV)
            {
                ParametersWithIV ivParam = (ParametersWithIV)parameters;
                byte[] iv = ivParam.GetIV();

                if (iv.Length < IV.Length)
                {
                    // prepend the supplied IV with zeros (per FIPS PUB 81)
                    Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
                    for (int i = 0; i < IV.Length - iv.Length; i++)
                    {
                        IV[i] = 0;
                    }
                }
                else
                {
                    Array.Copy(iv, 0, IV, 0, IV.Length);
                }

				parameters = ivParam.Parameters;
            }

			Reset();

			cipher.Init(true, parameters);
        }
コード例 #9
0
        /**
        * initialise a SKIPJACK cipher.
        *
        * @param forEncryption whether or not we are for encryption.
        * @param parameters the parameters required to set up the cipher.
        * @exception ArgumentException if the parameters argument is
        * inappropriate.
        */
        public virtual void Init(
            bool				forEncryption,
            ICipherParameters	parameters)
        {
            if (!(parameters is KeyParameter))
	            throw new ArgumentException("invalid parameter passed to SKIPJACK init - " + parameters.GetType().ToString());

			byte[] keyBytes = ((KeyParameter)parameters).GetKey();

            this.encrypting = forEncryption;
            this.key0 = new int[32];
            this.key1 = new int[32];
            this.key2 = new int[32];
            this.key3 = new int[32];

            //
            // expand the key to 128 bytes in 4 parts (saving us a modulo, multiply
            // and an addition).
            //
            for (int i = 0; i < 32; i ++)
            {
                key0[i] = keyBytes[(i * 4) % 10] & 0xff;
                key1[i] = keyBytes[(i * 4 + 1) % 10] & 0xff;
                key2[i] = keyBytes[(i * 4 + 2) % 10] & 0xff;
                key3[i] = keyBytes[(i * 4 + 3) % 10] & 0xff;
            }
        }
コード例 #10
0
        /**
        * initialise the ElGamal engine.
        *
        * @param forEncryption true if we are encrypting, false otherwise.
        * @param param the necessary ElGamal key parameters.
        */
        public void Init(
            bool				forEncryption,
            ICipherParameters	parameters)
        {
            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom p = (ParametersWithRandom) parameters;

                this.key = (ElGamalKeyParameters) p.Parameters;
                this.random = p.Random;
            }
            else
            {
                this.key = (ElGamalKeyParameters) parameters;
                this.random = new SecureRandom();
            }

            this.forEncryption = forEncryption;
            this.bitSize = key.Parameters.P.BitLength;

            if (forEncryption)
            {
                if (!(key is ElGamalPublicKeyParameters))
                {
                    throw new ArgumentException("ElGamalPublicKeyParameters are required for encryption.");
                }
            }
            else
            {
                if (!(key is ElGamalPrivateKeyParameters))
                {
                    throw new ArgumentException("ElGamalPrivateKeyParameters are required for decryption.");
                }
            }
        }
コード例 #11
0
		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?
			}
		}
コード例 #12
0
ファイル: GOST3410Signer.cs プロジェクト: hjgode/iTextSharpCF
        public void Init(
			bool				forSigning,
			ICipherParameters	parameters)
        {
            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    ParametersWithRandom rParam = (ParametersWithRandom)parameters;

                    this.random = rParam.Random;
            //					this.key = (Gost3410PrivateKeyParameters)rParam.Parameters;
                    parameters = rParam.Parameters;
                }
                else
                {
                    this.random = new SecureRandom();
            //					this.key = (Gost3410PrivateKeyParameters)parameters;
                }

                if (!(parameters is Gost3410PrivateKeyParameters))
                    throw new InvalidKeyException("GOST3410 private key required for signing");

                this.key = (Gost3410PrivateKeyParameters) parameters;
            }
            else
            {
                if (!(parameters is Gost3410PublicKeyParameters))
                    throw new InvalidKeyException("GOST3410 public key required for signing");

                this.key = (Gost3410PublicKeyParameters) parameters;
            }
        }
コード例 #13
0
ファイル: RSA.cs プロジェクト: will14smith/Crypto
        public void Init(ICipherParameters parameters)
        {
            var pubKeyParams = parameters as PublicKeyParameter;
            if (pubKeyParams != null)
            {
                SecurityAssert.SAssert(pubKeyParams.Key is RSAPublicKey);

                pub = (RSAPublicKey)pubKeyParams.Key;

                return;
            }

            var privKeyParams = parameters as PrivateKeyParameter;
            if (privKeyParams != null)
            {
                SecurityAssert.SAssert(privKeyParams.Key is RSAPrivateKey);

                priv = (RSAPrivateKey)privKeyParams.Key;
                pub = (RSAPublicKey)priv.PublicKey;

                return;
            }

            throw new InvalidCastException();
        }
コード例 #14
0
        public virtual void Init(
            bool				forEncryption,
            ICipherParameters	parameters)
        {
            this.forEncryption = forEncryption;

            if (parameters is AeadParameters)
            {
                AeadParameters param = (AeadParameters) parameters;

                nonce = param.GetNonce();
                initialAssociatedText = param.GetAssociatedText();
                macSize = param.MacSize / 8;
                keyParam = param.Key;
            }
            else if (parameters is ParametersWithIV)
            {
                ParametersWithIV param = (ParametersWithIV) parameters;

                nonce = param.GetIV();
                initialAssociatedText = null;
                macSize = macBlock.Length / 2;
                keyParam = param.Parameters;
            }
            else
            {
                throw new ArgumentException("invalid parameters passed to CCM");
            }

            if (nonce == null || nonce.Length < 7 || nonce.Length > 13)
            {
                throw new ArgumentException("nonce must have length from 7 to 13 octets");
            }
        }
コード例 #15
0
		/**
		* initialise a Salsa20 cipher.
		*
		* @param forEncryption whether or not we are for encryption.
		* @param params the parameters required to set up the cipher.
		* @exception ArgumentException if the params argument is
		* inappropriate.
		*/
		public void Init(
			bool				forEncryption, 
			ICipherParameters	parameters)
		{
			/* 
			* Salsa20 encryption and decryption is completely
			* symmetrical, so the 'forEncryption' is 
			* irrelevant. (Like 90% of stream ciphers)
			*/

			ParametersWithIV ivParams = parameters as ParametersWithIV;

			if (ivParams == null)
				throw new ArgumentException("Salsa20 Init requires an IV", "parameters");

			byte[] iv = ivParams.GetIV();

			if (iv == null || iv.Length != 8)
				throw new ArgumentException("Salsa20 requires exactly 8 bytes of IV");

			KeyParameter key = ivParams.Parameters as KeyParameter;

			if (key == null)
				throw new ArgumentException("Salsa20 Init requires a key", "parameters");

			workingKey = key.GetKey();
			workingIV = iv;

			setKey(workingKey, workingIV);
		}
コード例 #16
0
ファイル: NullEngine.cs プロジェクト: htlp/itextsharp
		public void Init(
			bool				forEncryption,
			ICipherParameters	parameters)
		{
			// we don't mind any parameters that may come in
			initialised = true;
		}
コード例 #17
0
ファイル: DHAgreement.cs プロジェクト: htlp/itextsharp
		public void Init(
			ICipherParameters parameters)
		{
			AsymmetricKeyParameter kParam;
			if (parameters is ParametersWithRandom)
			{
				ParametersWithRandom rParam = (ParametersWithRandom)parameters;

				this.random = rParam.Random;
				kParam = (AsymmetricKeyParameter)rParam.Parameters;
			}
			else
			{
				this.random = new SecureRandom();
				kParam = (AsymmetricKeyParameter)parameters;
			}

			if (!(kParam is DHPrivateKeyParameters))
			{
				throw new ArgumentException("DHEngine expects DHPrivateKeyParameters");
			}

			this.key = (DHPrivateKeyParameters)kParam;
			this.dhParams = key.Parameters;
		}
コード例 #18
0
ファイル: ECDsaSigner.cs プロジェクト: woutersmit/NBitcoin
        public virtual void Init(bool forSigning, ICipherParameters parameters)
        {
            SecureRandom providedRandom = null;

            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    ParametersWithRandom rParam = (ParametersWithRandom)parameters;

                    providedRandom = rParam.Random;
                    parameters = rParam.Parameters;
                }

                if (!(parameters is ECPrivateKeyParameters))
                    throw new InvalidKeyException("EC private key required for signing");

                this.key = (ECPrivateKeyParameters)parameters;
            }
            else
            {
                if (!(parameters is ECPublicKeyParameters))
                    throw new InvalidKeyException("EC public key required for verification");

                this.key = (ECPublicKeyParameters)parameters;
            }

            this.random = InitSecureRandom(forSigning && !kCalculator.IsDeterministic, providedRandom);
        }
コード例 #19
0
        public ParametersWithSalt(ICipherParameters parameters, byte[] salt, int saltOff, int saltLen)
        {
            this.salt = new byte[saltLen];
            this.parameters = parameters;

            Array.Copy(salt, saltOff, this.salt, 0, saltLen);
        }
コード例 #20
0
		public void Init(
			bool				forSigning,
			ICipherParameters	parameters)
		{
			this.forSigning = forSigning;

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

			if (forSigning && !k.IsPrivate)
			{
				throw new InvalidKeyException("Signing Requires Private Key.");
			}

			if (!forSigning && k.IsPrivate)
			{
				throw new InvalidKeyException("Verification Requires Public Key.");
			}

			Reset();

			dsaSigner.Init(forSigning, parameters);
		}
コード例 #21
0
ファイル: HMac.cs プロジェクト: VimalKumarS/mono-tls
        public void Init(
            ICipherParameters parameters)
        {
            digest.Reset();

            byte[] key = ((KeyParameter)parameters).GetKey();
			int keyLength = key.Length;

            if (keyLength > blockLength)
            {
                digest.BlockUpdate(key, 0, key.Length);
                digest.DoFinal(inputPad, 0);

				keyLength = digestSize;
            }
            else
            {
				Array.Copy(key, 0, inputPad, 0, keyLength);
            }

			Array.Clear(inputPad, keyLength, blockLength - keyLength);
            Array.Copy(inputPad, 0, outputPad, 0, blockLength);

			xor(inputPad, IPAD);
			xor(outputPad, OPAD);

			// Initialise the digest
			digest.BlockUpdate(inputPad, 0, inputPad.Length);
        }
コード例 #22
0
		public ParametersWithSBox(
			ICipherParameters parameters,
			byte[] sBox)
		{
			this.parameters = parameters;
			this.sBox = sBox;
		}
コード例 #23
0
        /**
        * Initialise the cipher and, possibly, the initialisation vector (IV).
        * If an IV isn't passed as part of the parameter, the IV will be all zeros.
        *
        * @param forEncryption if true the cipher is initialised for
        *  encryption, if false for decryption.
        * @param param the key and other data required by the cipher.
        * @exception ArgumentException if the parameters argument is
        * inappropriate.
        */
        public void Init(
            bool forEncryption,
            ICipherParameters parameters)
        {
            bool oldEncrypting = this.encrypting;

            this.encrypting = forEncryption;

            if (parameters is ParametersWithIV)
            {
                ParametersWithIV ivParam = (ParametersWithIV)parameters;
                byte[]      iv = ivParam.GetIV();

                if (iv.Length != blockSize)
                {
                    throw new ArgumentException("initialisation vector must be the same length as block size");
                }

                Array.Copy(iv, 0, IV, 0, iv.Length);

				parameters = ivParam.Parameters;
            }

			Reset();

            // if null it's an IV changed only.
            if (parameters != null)
            {
                cipher.Init(encrypting, parameters);
            }
            else if (oldEncrypting != encrypting)
            {
                throw new ArgumentException("cannot change encrypting state without providing key.");
            }
        }
コード例 #24
0
        /**
        * Initialise a HC-256 cipher.
        *
        * @param forEncryption whether or not we are for encryption. Irrelevant, as
        *                      encryption and decryption are the same.
        * @param params        the parameters required to set up the cipher.
        * @throws ArgumentException if the params argument is
        *                                  inappropriate (ie. the key is not 256 bit long).
        */
        public void Init(
            bool				forEncryption,
            ICipherParameters	parameters)
        {
            ICipherParameters keyParam = parameters;

            if (parameters is ParametersWithIV)
            {
                iv = ((ParametersWithIV)parameters).GetIV();
                keyParam = ((ParametersWithIV)parameters).Parameters;
            }
            else
            {
                iv = new byte[0];
            }

            if (keyParam is KeyParameter)
            {
                key = ((KeyParameter)keyParam).GetKey();
                Init();
            }
            else
            {
                throw new ArgumentException(
                    "Invalid parameter passed to HC256 init - " + parameters.GetType().Name,
                    "parameters");
            }

            initialised = true;
        }
コード例 #25
0
		public void Init(
			bool				forEncryption, 
			ICipherParameters	parameters)
		{
			/* 
			 * Salsa20 encryption and decryption is completely
			 * symmetrical, so the 'forEncryption' is 
			 * irrelevant. (Like 90% of stream ciphers)
			 */

			ParametersWithIV ivParams = parameters as ParametersWithIV;

			if (ivParams == null)
				throw new ArgumentException(AlgorithmName + " Init requires an IV", "parameters");

			byte[] iv = ivParams.GetIV();

			if (iv == null || iv.Length != NonceSize)
				throw new ArgumentException(AlgorithmName + " requires exactly " + NonceSize + " bytes of IV");

			KeyParameter key = ivParams.Parameters as KeyParameter;

			if (key == null)
				throw new ArgumentException(AlgorithmName + " Init requires a key", "parameters");

			SetKey(key.GetKey(), iv);
			Reset();
			initialised = true;
		}
コード例 #26
0
ファイル: SignatureWriter.cs プロジェクト: VahidN/PdfReport
 /// <summary>
 /// CustomPdfReader to be able to work with streams.
 /// </summary>
 public CustomPdfReader(Stream isp, X509Certificate certificate, ICipherParameters certificateKey)
 {
     this.certificate = certificate;
     this.certificateKey = certificateKey;
     tokens = new PRTokeniser(new RandomAccessFileOrArray(isp));
     ReadPdf();
 }
コード例 #27
0
		/**
        * Initialise the cipher and, possibly, the initialisation vector (IV).
        * If an IV isn't passed as part of the parameter, the IV will be all zeros.
        * An IV which is too short is handled in FIPS compliant fashion.
        *
        * @param param the key and other data required by the cipher.
        * @exception ArgumentException if the parameters argument is
        * inappropriate.
        */
		public void Init(
			bool				forEncryption,
            ICipherParameters	parameters)
        {
			if (parameters is ParametersWithIV)
            {
                ParametersWithIV ivParam = (ParametersWithIV)parameters;
                byte[] iv = ivParam.GetIV();

                if (iv.Length < IV.Length)
                {
                    Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
                }
                else
                {
                    Array.Copy(iv, 0, IV, 0, IV.Length);
                }

				parameters = ivParam.Parameters;
            }

			Reset();

			cipher.Init(true, parameters);
        }
コード例 #28
0
        public void Init(bool forSigning, ICipherParameters parameters)
        {
            if (forSigning)
            {
                if (parameters is ParametersWithRandom)
                {
                    var rParam = (ParametersWithRandom)parameters;

                    _random = rParam.Random;
                    parameters = rParam.Parameters;
                }
                else
                {
                    _random = new SecureRandom();
                }

                if (!(parameters is DsaPrivateKeyParameters))
                    throw new InvalidKeyException("DSA private key required for signing");

                _key = (DsaPrivateKeyParameters)parameters;
            }
            else
            {
                if (!(parameters is DsaPublicKeyParameters))
                    throw new InvalidKeyException("DSA public key required for verification");

                _key = (DsaPublicKeyParameters)parameters;
            }
        }
コード例 #29
0
		internal KeyParameter UnwrapKey(ICipherParameters key)
		{
			byte[] encryptedKey = info.EncryptedKey.GetOctets();
            string keyExchangeAlgorithm = GetExchangeEncryptionAlgorithmName(keyEncAlg.Algorithm);

			try
			{
				IWrapper keyWrapper = WrapperUtilities.GetWrapper(keyExchangeAlgorithm);
				keyWrapper.Init(false, key);

				// FIXME Support for MAC algorithm parameters similar to cipher parameters
				return ParameterUtilities.CreateKeyParameter(
					GetContentAlgorithmName(), keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length));
			}
			catch (SecurityUtilityException e)
			{
				throw new CmsException("couldn't create cipher.", e);
			}
			catch (InvalidKeyException e)
			{
				throw new CmsException("key invalid in message.", e);
			}
//			catch (IllegalBlockSizeException e)
			catch (DataLengthException e)
			{
				throw new CmsException("illegal blocksize in message.", e);
			}
//			catch (BadPaddingException e)
			catch (InvalidCipherTextException e)
			{
				throw new CmsException("bad padding in message.", e);
			}
		}
コード例 #30
0
        /// <summary>
        /// Initialise the signer for signing or verification.
        /// </summary>
        /// <param name="forSigning"></param>
        /// <param name="parameters"></param>        
        /// <exception cref="InvalidKeyException">
        /// Signing Requires Private Key.
        /// or
        /// Verification Requires Public Key.
        /// </exception>
        public void Init(bool forSigning, ICipherParameters parameters)
        {
            _forSigning = forSigning;

            IAsymmetricKeyParameter k;

            var parametersWithRandom = parameters as ParametersWithRandom;
            if (parametersWithRandom != null)
            {
                k = (AsymmetricKeyParameter)parametersWithRandom.Parameters;
            }
            else
            {
                k = (AsymmetricKeyParameter)parameters;
            }

            if (forSigning && !k.IsPrivate)
                throw new InvalidKeyException("Signing Requires Private Key.");

            if (!forSigning && k.IsPrivate)
                throw new InvalidKeyException("Verification Requires Public Key.");

            this.Reset();

            _dsaSigner.Init(forSigning, parameters);
        }
コード例 #31
0
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.IO.IOException"/>
        protected internal virtual void Sign(String src, String name, String dest, X509Certificate[] chain, ICipherParameters
                                             pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle
                                             rectangleForNewField, bool setReuseAppearance, bool isAppendMode, int certificationLevel, float?fontSize
                                             )
        {
            PdfReader          reader     = new PdfReader(src);
            StampingProperties properties = new StampingProperties();

            if (isAppendMode)
            {
                properties.UseAppendMode();
            }
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), properties);

            signer.SetCertificationLevel(certificationLevel);
            // Creating the appearance
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location
                                                                                                              ).SetReuseAppearance(setReuseAppearance);

            if (rectangleForNewField != null)
            {
                appearance.SetPageRect(rectangleForNewField);
            }
            if (fontSize != null)
            {
                appearance.SetLayer2FontSize((float)fontSize);
            }
            signer.SetFieldName(name);
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            signer.SignDetached(pks, chain, null, null, null, 0, subfilter);
        }
コード例 #32
0
 // TODO improve testing, e.g. check ID. For not at least we assert that exception is not thrown
 /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
 /// <exception cref="System.IO.IOException"/>
 protected internal virtual void Sign(String src, String name, String dest, X509Certificate[] chain, ICipherParameters
                                      pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle
                                      rectangleForNewField, bool setReuseAppearance, bool isAppendMode)
 {
     Sign(src, name, dest, chain, pk, digestAlgorithm, subfilter, reason, location, rectangleForNewField, setReuseAppearance
          , isAppendMode, PdfSigner.NOT_CERTIFIED, null);
 }
コード例 #33
0
        public static ICipherParameters GenerateCipherParameters(
            string algorithm,
            char[]          password,
            bool wrongPkcs12Zero,
            Asn1Encodable pbeParameters)
        {
            string mechanism = (string)algorithms[algorithm.ToUpperInvariant()];

            byte[] keyBytes       = null;
            byte[] salt           = null;
            int    iterationCount = 0;

            if (IsPkcs12(mechanism))
            {
                Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters);
                salt           = pbeParams.GetIV();
                iterationCount = pbeParams.Iterations.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero);
            }
            else if (IsPkcs5Scheme2(mechanism))
            {
                // See below
            }
            else
            {
                PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters);
                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            }

            ICipherParameters parameters = null;

            if (IsPkcs5Scheme2(mechanism))
            {
                PbeS2Parameters     s2p       = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object());
                AlgorithmIdentifier encScheme = s2p.EncryptionScheme;
                DerObjectIdentifier encOid    = encScheme.ObjectID;
                Asn1Object          encParams = encScheme.Parameters.ToAsn1Object();

                // TODO What about s2p.KeyDerivationFunc.ObjectID?
                Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object());

                byte[] iv;
                if (encOid.Equals(PkcsObjectIdentifiers.RC2Cbc))                 // PKCS5.B.2.3
                {
                    RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(encParams);
                    iv = rc2Params.GetIV();
                }
                else
                {
                    iv = Asn1OctetString.GetInstance(encParams).GetOctets();
                }

                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);

                int keyLength = pbeParams.KeyLength != null
                                        ?       pbeParams.KeyLength.IntValue * 8
                                        :       GeneratorUtilities.GetDefaultKeySize(encOid);

                PbeParametersGenerator gen = MakePbeGenerator(
                    (string)algorithmType[mechanism], null, keyBytes, salt, iterationCount);

                parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength);

                if (iv != null)
                {
                    // FIXME? OpenSSL weirdness with IV of zeros (for ECB keys?)
                    if (Arrays.AreEqual(iv, new byte[iv.Length]))
                    {
                        //Console.Error.Write("***** IV all 0 (length " + iv.Length + ") *****");
                    }
                    else
                    {
                        parameters = new ParametersWithIV(parameters, iv);
                    }
                }
            }
            else if (mechanism.StartsWith("PBEwithSHA-1"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-1and128bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 40);
                }
                else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 192, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 40, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithSHA-256"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithMD5"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithMD5andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithMD2"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount);
                if (mechanism.Equals("PBEwithMD2andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD2andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
            }
            else if (mechanism.StartsWith("PBEwithHmac"))
            {
                string  digestName = mechanism.Substring("PBEwithHmac".Length);
                IDigest digest     = DigestUtilities.GetDigest(digestName);

                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount);

                int bitLen = digest.GetDigestSize() * 8;
                parameters = generator.GenerateDerivedMacParameters(bitLen);
            }

            Array.Clear(keyBytes, 0, keyBytes.Length);

            return(FixDesParity(mechanism, parameters));
        }
コード例 #34
0
 public static void InitSign(this ISigner signer, ICipherParameters pk)
 {
     signer.Init(true, pk);
 }
コード例 #35
0
 /**
  * initialise the underlying cipher.
  *
  * @param forEncryption true if we are setting up for encryption, false otherwise.
  * @param param the necessary parameters for the underlying cipher to be initialised.
  */
 public void Init(
     bool forEncryption,
     ICipherParameters parameters)
 {
     cipher.Init(forEncryption, parameters);
 }
コード例 #36
0
 public void CalculateAgreement(ICipherParameters publicKey, byte[] buf, int off)
 {
     privateKey.GenerateSecret((X25519PublicKeyParameters)publicKey, buf, off);
 }
コード例 #37
0
 public void Init(ICipherParameters parameters)
 {
     this.privateKey = (X25519PrivateKeyParameters)parameters;
 }
コード例 #38
0
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            //IL_0065: Unknown result type (might be due to invalid IL or missing references)
            //IL_00b9: Unknown result type (might be due to invalid IL or missing references)
            //IL_00fd: Unknown result type (might be due to invalid IL or missing references)
            //IL_0132: Unknown result type (might be due to invalid IL or missing references)
            bool flag = this.forEncryption;

            this.forEncryption = forEncryption;
            macBlock           = null;
            byte[]       array;
            KeyParameter keyParameter;

            if (parameters is AeadParameters)
            {
                AeadParameters aeadParameters = (AeadParameters)parameters;
                array = aeadParameters.GetNonce();
                initialAssociatedText = aeadParameters.GetAssociatedText();
                int num = aeadParameters.MacSize;
                if (num < 64 || num > 128 || num % 8 != 0)
                {
                    throw new ArgumentException(string.Concat((object)"Invalid value for MAC size: ", (object)num));
                }
                macSize      = num / 8;
                keyParameter = aeadParameters.Key;
            }
            else
            {
                if (!(parameters is ParametersWithIV))
                {
                    throw new ArgumentException("invalid parameters passed to OCB");
                }
                ParametersWithIV parametersWithIV = (ParametersWithIV)parameters;
                array = parametersWithIV.GetIV();
                initialAssociatedText = null;
                macSize      = 16;
                keyParameter = (KeyParameter)parametersWithIV.Parameters;
            }
            hashBlock = new byte[16];
            mainBlock = new byte[forEncryption ? 16 : (16 + macSize)];
            if (array == null)
            {
                array = new byte[0];
            }
            if (array.Length > 15)
            {
                throw new ArgumentException("IV must be no more than 15 bytes");
            }
            if (keyParameter != null)
            {
                hashCipher.Init(forEncryption: true, keyParameter);
                mainCipher.Init(forEncryption, keyParameter);
                KtopInput = null;
            }
            else if (flag != forEncryption)
            {
                throw new ArgumentException("cannot change encrypting state without providing key.");
            }
            L_Asterisk = new byte[16];
            hashCipher.ProcessBlock(L_Asterisk, 0, L_Asterisk, 0);
            L_Dollar = OCB_double(L_Asterisk);
            L        = Platform.CreateArrayList();
            L.Add((object)OCB_double(L_Dollar));
            int num2 = ProcessNonce(array);
            int num3 = num2 % 8;
            int num4 = num2 / 8;

            if (num3 == 0)
            {
                global::System.Array.Copy((global::System.Array)Stretch, num4, (global::System.Array)OffsetMAIN_0, 0, 16);
            }
            else
            {
                for (int i = 0; i < 16; i++)
                {
                    uint num5 = Stretch[num4];
                    uint num6 = Stretch[++num4];
                    OffsetMAIN_0[i] = (byte)((num5 << num3) | (num6 >> 8 - num3));
                }
            }
            hashBlockPos   = 0;
            mainBlockPos   = 0;
            hashBlockCount = 0L;
            mainBlockCount = 0L;
            OffsetHASH     = new byte[16];
            Sum            = new byte[16];
            global::System.Array.Copy((global::System.Array)OffsetMAIN_0, 0, (global::System.Array)OffsetMAIN, 0, 16);
            Checksum = new byte[16];
            if (initialAssociatedText != null)
            {
                ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
            }
        }
コード例 #39
0
        protected Stream Open(
            Stream outStr,
            AlgorithmIdentifier macAlgId,
            ICipherParameters cipherParameters,
            Asn1EncodableVector recipientInfos)
        {
            try
            {
                //
                // ContentInfo
                //
                BerSequenceGenerator cGen = new BerSequenceGenerator(outStr);

                cGen.AddObject(CmsObjectIdentifiers.AuthenticatedData);

                //
                // Authenticated Data
                //
                BerSequenceGenerator authGen = new BerSequenceGenerator(
                    cGen.GetRawOutputStream(), 0, true);

                authGen.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));

                Stream        authRaw  = authGen.GetRawOutputStream();
                Asn1Generator recipGen = _berEncodeRecipientSet
                                        ?       (Asn1Generator) new BerSetGenerator(authRaw)
                                        :       new DerSetGenerator(authRaw);

                foreach (Asn1Encodable ae in recipientInfos)
                {
                    recipGen.AddObject(ae);
                }

                recipGen.Close();

                authGen.AddObject(macAlgId);

                BerSequenceGenerator eiGen = new BerSequenceGenerator(authRaw);
                eiGen.AddObject(CmsObjectIdentifiers.Data);

                Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
                    eiGen.GetRawOutputStream(), 0, false, _bufferSize);

                IMac mac = MacUtilities.GetMac(macAlgId.Algorithm);
                // TODO Confirm no ParametersWithRandom needed
                mac.Init(cipherParameters);
                Stream mOut = new TeeOutputStream(octetOutputStream, new MacOutputStream(mac));

                return(new CmsAuthenticatedDataOutputStream(mOut, mac, cGen, authGen, eiGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }
        }
コード例 #40
0
 internal ParametersWithRounds(ICipherParameters parameters, int rounds)
 {
     this.parameters = parameters;
     this.rounds     = rounds;
 }
コード例 #41
0
 public ParametersWithID(ICipherParameters parameters,
                         byte[] id)
     : this(parameters, id, 0, id.Length)
 {
 }
コード例 #42
0
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            KeyParameter initKeyParam;

            byte[]            initNonce;
            ICipherParameters chacha20Params;

            if (parameters is AeadParameters)
            {
                AeadParameters aeadParams = (AeadParameters)parameters;

                int macSizeBits = aeadParams.MacSize;
                if ((MacSize * 8) != macSizeBits)
                {
                    throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
                }

                initKeyParam   = aeadParams.Key;
                initNonce      = aeadParams.GetNonce();
                chacha20Params = new ParametersWithIV(initKeyParam, initNonce);

                this.mInitialAad = aeadParams.GetAssociatedText();
            }
            else if (parameters is ParametersWithIV)
            {
                ParametersWithIV ivParams = (ParametersWithIV)parameters;

                initKeyParam   = (KeyParameter)ivParams.Parameters;
                initNonce      = ivParams.GetIV();
                chacha20Params = ivParams;

                this.mInitialAad = null;
            }
            else
            {
                throw new ArgumentException("invalid parameters passed to ChaCha20Poly1305", "parameters");
            }

            // Validate key
            if (null == initKeyParam)
            {
                if (State.Uninitialized == mState)
                {
                    throw new ArgumentException("Key must be specified in initial init");
                }
            }
            else
            {
                if (KeySize != initKeyParam.GetKey().Length)
                {
                    throw new ArgumentException("Key must be 256 bits");
                }
            }

            // Validate nonce
            if (null == initNonce || NonceSize != initNonce.Length)
            {
                throw new ArgumentException("Nonce must be 96 bits");
            }

            // Check for encryption with reused nonce
            if (State.Uninitialized != mState && forEncryption && Arrays.AreEqual(mNonce, initNonce))
            {
                if (null == initKeyParam || Arrays.AreEqual(mKey, initKeyParam.GetKey()))
                {
                    throw new ArgumentException("cannot reuse nonce for ChaCha20Poly1305 encryption");
                }
            }

            if (null != initKeyParam)
            {
                Array.Copy(initKeyParam.GetKey(), 0, mKey, 0, KeySize);
            }

            Array.Copy(initNonce, 0, mNonce, 0, NonceSize);

            mChacha20.Init(true, chacha20Params);

            this.mState = forEncryption ? State.EncInit : State.DecInit;

            Reset(true, false);
        }
コード例 #43
0
 /// <exception cref="Org.BouncyCastle.Security.Certificates.CertificateEncodingException"/>
 public TestCrlClient(X509Certificate caCert, ICipherParameters caPrivateKey)
 {
     this.crlBuilder   = new TestCrlBuilder(caCert, DateTimeUtil.GetCurrentUtcTime().AddDays(-1));
     this.caPrivateKey = caPrivateKey;
 }
コード例 #44
0
 public ParametersWithID(ICipherParameters parameters,
                         byte[] id, int idOff, int idLen)
 {
     this.parameters = parameters;
     this.id         = Arrays.CopyOfRange(id, idOff, idOff + idLen);
 }
コード例 #45
0
ファイル: Ssl3Mac.cs プロジェクト: jkloop45/Payment
        public virtual void Init(ICipherParameters parameters)
        {
            secret = Arrays.Clone(((KeyParameter)parameters).GetKey());

            Reset();
        }
コード例 #46
0
 public PubSecHandlerUsingAes256(PdfDictionary encryptionDictionary, ICipherParameters certificateKey, X509Certificate
                                 certificate, bool encryptMetadata)
     : base(encryptionDictionary, certificateKey, certificate, encryptMetadata)
 {
 }
コード例 #47
0
 private void ClearEncryptionParams()
 {
     this.password       = null;
     this.certificate    = null;
     this.certificateKey = null;
 }
コード例 #48
0
 /// <exception cref="Org.BouncyCastle.Security.Certificates.CertificateEncodingException"/>
 public TestCrlClient(TestCrlBuilder crlBuilder, ICipherParameters caPrivateKey)
 {
     this.crlBuilder   = crlBuilder;
     this.caPrivateKey = caPrivateKey;
 }
コード例 #49
0
        public void Init(bool forEncryption, ICipherParameters parameters)
        {
            this.forEncryption = forEncryption;

            KeyParameter engineParam;

            if (parameters is AeadParameters)
            {
                AeadParameters param = (AeadParameters)parameters;

                byte[] iv   = param.GetNonce();
                int    diff = IV.Length - iv.Length;
                Array.Copy(iv, 0, IV, diff, iv.Length);
                Array.Clear(IV, 0, diff);

                initialAssociatedText = param.GetAssociatedText();

                int macSizeBits = param.MacSize;

                if (macSizeBits < 64 || macSizeBits > cipher.GetBlockSize() * 8 || macSizeBits % 8 != 0)
                {
                    throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
                }

                macSize     = macSizeBits / 8;
                engineParam = param.Key;


                if (initialAssociatedText != null)
                {
                    ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
                }
            }
            else if (parameters is ParametersWithIV)
            {
                ParametersWithIV param = (ParametersWithIV)parameters;

                byte[] iv   = param.GetIV();
                int    diff = IV.Length - iv.Length;
                Array.Copy(iv, 0, IV, diff, iv.Length);
                Array.Clear(IV, 0, diff);


                initialAssociatedText = null;

                macSize = cipher.GetBlockSize();

                engineParam = param.Parameters as KeyParameter;
            }
            else
            {
                throw new ArgumentException("invalid parameters passed to GCM");
            }

            this.macBlock = new byte[cipher.GetBlockSize()];


            ctrCipher.Init(true, new ParametersWithIV(engineParam, IV));

            cipher.Init(true, engineParam);
        }
コード例 #50
0
 public CmsDeferredSigner(ICipherParameters pk, X509Certificate[] chain)
 {
     this.pk    = pk;
     this.chain = chain;
 }
コード例 #51
0
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            bool oldForEncryption = this.forEncryption;

            this.forEncryption = forEncryption;
            this.macBlock      = null;

            KeyParameter keyParameter;

            byte[] N;
            if (parameters is AeadParameters)
            {
                AeadParameters aeadParameters = (AeadParameters)parameters;

                N = aeadParameters.GetNonce();
                initialAssociatedText = aeadParameters.GetAssociatedText();

                int macSizeBits = aeadParameters.MacSize;
                if (macSizeBits < 64 || macSizeBits > 128 || macSizeBits % 8 != 0)
                {
                    throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
                }

                macSize      = macSizeBits / 8;
                keyParameter = aeadParameters.Key;
            }
            else if (parameters is ParametersWithIV)
            {
                ParametersWithIV parametersWithIV = (ParametersWithIV)parameters;

                N = parametersWithIV.GetIV();
                initialAssociatedText = null;
                macSize      = 16;
                keyParameter = (KeyParameter)parametersWithIV.Parameters;
            }
            else
            {
                throw new ArgumentException("invalid parameters passed to OCB");
            }

            this.hashBlock = new byte[16];
            this.mainBlock = new byte[forEncryption ? BLOCK_SIZE : (BLOCK_SIZE + macSize)];

            if (N == null)
            {
                N = new byte[0];
            }

            if (N.Length > 15)
            {
                throw new ArgumentException("IV must be no more than 15 bytes");
            }

            /*
             * KEY-DEPENDENT INITIALISATION
             */

            if (keyParameter != null)
            {
                // hashCipher always used in forward mode
                hashCipher.Init(true, keyParameter);
                mainCipher.Init(forEncryption, keyParameter);
                KtopInput = null;
            }
            else if (oldForEncryption != forEncryption)
            {
                throw new ArgumentException("cannot change encrypting state without providing key.");
            }

            this.L_Asterisk = new byte[16];
            hashCipher.ProcessBlock(L_Asterisk, 0, L_Asterisk, 0);

            this.L_Dollar = OCB_double(L_Asterisk);

            this.L = Platform.CreateArrayList();
            this.L.Add(OCB_double(L_Dollar));

            /*
             * NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALISATION
             */

            int bottom = ProcessNonce(N);

            int bits = bottom % 8, bytes = bottom / 8;

            if (bits == 0)
            {
                Array.Copy(Stretch, bytes, OffsetMAIN_0, 0, 16);
            }
            else
            {
                for (int i = 0; i < 16; ++i)
                {
                    uint b1 = Stretch[bytes];
                    uint b2 = Stretch[++bytes];
                    this.OffsetMAIN_0[i] = (byte)((b1 << bits) | (b2 >> (8 - bits)));
                }
            }

            this.hashBlockPos = 0;
            this.mainBlockPos = 0;

            this.hashBlockCount = 0;
            this.mainBlockCount = 0;

            this.OffsetHASH = new byte[16];
            this.Sum        = new byte[16];
            Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
            this.Checksum = new byte[16];

            if (initialAssociatedText != null)
            {
                ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
            }
        }
コード例 #52
0
 /// <summary>Defines the certificate which will be used if the document is encrypted with public key encryption.
 ///     </summary>
 public virtual ReaderProperties SetPublicKeySecurityParams(X509Certificate certificate, ICipherParameters
                                                            certificateKey)
 {
     ClearEncryptionParams();
     this.certificate    = certificate;
     this.certificateKey = certificateKey;
     return(this);
 }
コード例 #53
0
        private void doTestException(
            string name,
            int ivLength)
        {
            try
            {
                byte[] key128 =
                {
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143,
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143
                };

                byte[] key256 =
                {
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143,
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143,
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143,
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143
                };

                byte[] keyBytes;
                if (name.Equals("HC256"))
                {
                    keyBytes = key256;
                }
                else
                {
                    keyBytes = key128;
                }

                KeyParameter cipherKey = ParameterUtilities.CreateKeyParameter(name, keyBytes);

                ICipherParameters cipherParams = cipherKey;
                if (ivLength > 0)
                {
                    cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]);
                }

                IBufferedCipher ecipher = CipherUtilities.GetCipher(name);
                ecipher.Init(true, cipherParams);

                byte[] cipherText = new byte[0];
                try
                {
                    // According specification Method engineUpdate(byte[] input,
                    // int inputOffset, int inputLen, byte[] output, int
                    // outputOffset)
                    // throws ShortBufferException - if the given output buffer is
                    // too
                    // small to hold the result
                    ecipher.ProcessBytes(new byte[20], 0, 20, cipherText, 0);

//					Fail("failed exception test - no ShortBufferException thrown");
                    Fail("failed exception test - no DataLengthException thrown");
                }
//				catch (ShortBufferException e)
                catch (DataLengthException)
                {
                    // ignore
                }

                // NB: The lightweight engine doesn't take public/private keys
//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher(name);
//
//					//                Key k = new PublicKey()
//					//                {
//					//
//					//                    public string getAlgorithm()
//					//                    {
//					//                        return "STUB";
//					//                    }
//					//
//					//                    public string getFormat()
//					//                    {
//					//                        return null;
//					//                    }
//					//
//					//                    public byte[] getEncoded()
//					//                    {
//					//                        return null;
//					//                    }
//					//
//					//                };
//					IAsymmetricKeyParameter k = new AsymmetricKeyParameter(false);
//					c.Init(true, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for public key");
//				}
//				catch (InvalidKeyException)
//				{
//					// okay
//				}
//
//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher(name);
//
//					//				Key k = new PrivateKey()
//					//                {
//					//
//					//                    public string getAlgorithm()
//					//                    {
//					//                        return "STUB";
//					//                    }
//					//
//					//                    public string getFormat()
//					//                    {
//					//                        return null;
//					//                    }
//					//
//					//                    public byte[] getEncoded()
//					//                    {
//					//                        return null;
//					//                    }
//					//
//					//                };
//
//					IAsymmetricKeyParameter k = new AsymmetricKeyParameter(true);
//					c.Init(false, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for private key");
//				}
//				catch (InvalidKeyException)
//				{
//					// okay
//				}
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }
        }
コード例 #54
0
 public override void Init(bool forEncryption, ICipherParameters parameters)
 {
     this.forEncryption = forEncryption;
     throw Platform.CreateNotImplementedException("IES");
 }
コード例 #55
0
 private static void SetSigCryptoFromCipherParam(PdfSignatureAppearance sigAppearance, ICipherParameters key, X509Certificate[] chain)
 {
     sigAppearance.SetCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
 }
コード例 #56
0
        private void doRunTest(
            string name,
            int ivLength)
        {
            string lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789";

            string baseName = name;

            if (name.IndexOf('/') >= 0)
            {
                baseName = name.Substring(0, name.IndexOf('/'));
            }

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(baseName);

            IBufferedCipher inCipher  = CipherUtilities.GetCipher(name);
            IBufferedCipher outCipher = CipherUtilities.GetCipher(name);
            KeyParameter    key       = ParameterUtilities.CreateKeyParameter(baseName, kGen.GenerateKey());
            MemoryStream    bIn       = new MemoryStream(Encoding.ASCII.GetBytes(lCode), false);
            MemoryStream    bOut      = new MemoryStream();

            // In the Java build, this IV would be implicitly created and then retrieved with getIV()
            ICipherParameters cipherParams = key;

            if (ivLength > 0)
            {
                cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]);
            }

            inCipher.Init(true, cipherParams);

            // TODO Should we provide GetIV() method on IBufferedCipher?
            //if (inCipher.getIV() != null)
            //{
            //	outCipher.Init(false, new ParametersWithIV(key, inCipher.getIV()));
            //}
            //else
            //{
            //	outCipher.Init(false, key);
            //}
            outCipher.Init(false, cipherParams);

            CipherStream cIn  = new CipherStream(bIn, inCipher, null);
            CipherStream cOut = new CipherStream(bOut, null, outCipher);

            int c;

            while ((c = cIn.ReadByte()) >= 0)
            {
                cOut.WriteByte((byte)c);
            }

            cIn.Close();

            cOut.Flush();
            cOut.Close();

            byte[] bs  = bOut.ToArray();
            string res = Encoding.ASCII.GetString(bs, 0, bs.Length);

            if (!res.Equals(lCode))
            {
                Fail("Failed - decrypted data doesn't match.");
            }
        }
コード例 #57
0
 public abstract void Init(bool forEncryption, ICipherParameters parameters);
コード例 #58
0
        //internal static IDigest GetPrf(AlgorithmIdentifier algID)
        //{
        //    string digestName = (string)PrfDigests[algID];

        //    return DigestUtilities.GetDigest(digestName);
        //}

        //internal static IWrapper CreateRfc3211Wrapper(DerObjectIdentifier algorithm)
        //{
        //    if (NistObjectIdentifiers.IdAes128Cbc.Equals(algorithm)
        //        || NistObjectIdentifiers.IdAes192Cbc.Equals(algorithm)
        //        || NistObjectIdentifiers.IdAes256Cbc.Equals(algorithm))
        //    {
        //        return new Rfc3211WrapEngine(new AesEngine());
        //    }
        //    else if (PkcsObjectIdentifiers.DesEde3Cbc.Equals(algorithm))
        //    {
        //        return new Rfc3211WrapEngine(new DesEdeEngine());
        //    }
        //    else if (OiwObjectIdentifiers.DesCbc.Equals(algorithm))
        //    {
        //        return new Rfc3211WrapEngine(new DesEngine());
        //    }
        //    else if (PkcsObjectIdentifiers.RC2Cbc.Equals(algorithm))
        //    {
        //        return new Rfc3211WrapEngine(new RC2Engine());
        //    }
        //    else
        //    {
        //        throw new CmsException("cannot recognise wrapper: " + algorithm);
        //    }
        //}

        public static object CreateContentCipher(bool forEncryption, ICipherParameters encKey,
                                                 AlgorithmIdentifier encryptionAlgID)
        {
            return(CipherFactory.CreateContentCipher(forEncryption, encKey, encryptionAlgID));
        }
コード例 #59
0
 public ParametersWithRandom(
     ICipherParameters parameters)
     : this(parameters, new SecureRandom())
 {
 }
コード例 #60
0
 public void Init(ICipherParameters parameters)
 {
 }