/**
		* Construct a KDF Parameters generator.
		*
		* @param counterStart value of counter.
		* @param digest the digest to be used as the source of derived keys.
		*/
		protected BaseKdfBytesGenerator(
			int     counterStart,
			IDigest  digest)
		{
			this.counterStart = counterStart;
			this.digest = digest;
		}
Exemplo n.º 2
0
 /// <summary>
 /// Initialize this class
 /// </summary>
 /// 
 /// <param name="Parameters">The cipher parameters</param>
 /// <param name="Info">The predefined nonce value</param>
 public KobaraImaiCipher(MPKCParameters Parameters, byte[] Info = null)
 {
     if (Info != null)
         KobaraImaiCipher.MPKCINFO = Info;
     _cipherParams = Parameters;
     _dgtEngine = GetDigest(Parameters.Digest);
 }
Exemplo n.º 3
0
		/// <summary>
		/// Generate a signer for the with either implicit or explicit trailers
		/// for ISO9796-2.
		/// </summary>
		/// <param name="cipher">base cipher to use for signature creation/verification</param>
		/// <param name="digest">digest to use.</param>
		/// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param>
		public Iso9796d2Signer(
			IAsymmetricBlockCipher	cipher,
			IDigest					digest,
			bool					isImplicit)
		{
			this.cipher = cipher;
			this.digest = digest;

			if (isImplicit)
			{
				trailer = TrailerImplicit;
			}
			else
			{
				if (digest is Sha1Digest)
				{
					trailer = TrailerSha1;
				}
				else if (digest is RipeMD160Digest)
				{
					trailer = TrailerRipeMD160;
				}
				else if (digest is RipeMD128Digest)
				{
					trailer = TrailerRipeMD128;
				}
				else
				{
					throw new System.ArgumentException("no valid trailer for digest");
				}
			}
		}
Exemplo n.º 4
0
 /// <summary>Basic constructor</summary>
 /// <param name="cipher">the asymmetric cipher to use.</param>
 /// <param name="digest">the digest to use.</param>
 /// <param name="salt">the fixed salt to be used.</param>
 public PssSigner(
     IAsymmetricBlockCipher cipher,
     IDigest digest,
     byte[] salt)
     : this(cipher, digest, digest, digest, salt.Length, salt, TrailerImplicit)
 {
 }
 /**
  * Processes the client's credentials. If valid the shared secret is generated and returned.
  * @param clientA The client's credentials
  * @return A shared secret BigInteger
  * @throws CryptoException If client's credentials are invalid
  */
 public virtual BigInteger CalculateSecret(IDigest digest, BigInteger clientA)
 {
     this.A = Srp6Utilities.ValidatePublicValue(param.N, clientA);
     this.u = Srp6Utilities.CalculateU(digest, param.N, A, pubB);
     this.S = v.ModPow(u, param.N).Multiply(A).Mod(param.N).ModPow(privB, param.N);
     return S;
 }
        /// <summary>
        /// Generate a signer for the with either implicit or explicit trailers
        /// for ISO9796-2.
        /// </summary>
        /// <param name="cipher">base cipher to use for signature creation/verification</param>
        /// <param name="digest">digest to use.</param>
        /// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param>
        public Iso9796d2Signer(
            IAsymmetricBlockCipher	cipher,
            IDigest					digest,
            bool					isImplicit)
        {
            this.cipher = cipher;
            this.digest = digest;

            if (isImplicit)
            {
                trailer = TrailerImplicit;
            }
            else
            {
                string digestName = digest.AlgorithmName;

                if (trailerMap.Contains(digestName))
                {
                    trailer = (int)trailerMap[digest.AlgorithmName];
                }
                else
                {
                    throw new System.ArgumentException("no valid trailer for digest");
                }
            }
        }
Exemplo n.º 7
0
		/// <summary>
		/// Encode the stream with the given digest.
		/// </summary>
		/// <param name="data">The byte array to be encoded.</param>
		/// <param name="digest">The digest to be used.</param>
		/// <returns>Hashed value of the byte array as a hex string.</returns>
		private static string Encode(byte[] data, IDigest digest)
		{
			digest.BlockUpdate(data, 0, data.Length);
			byte[] output = new byte[digest.GetDigestSize()];
			digest.DoFinal (output, 0);
			return Hex.Encode(output);
		}
		public Gost3410DigestSigner(
			IDsa	signer,
			IDigest	digest)
		{
			this.dsaSigner = signer;
			this.digest = digest;
		}
Exemplo n.º 9
0
	    /**
	     * Initialises the client to begin new authentication attempt
	     * @param N The safe prime associated with the client's verifier
	     * @param g The group parameter associated with the client's verifier
	     * @param digest The digest algorithm associated with the client's verifier
	     * @param random For key generation
	     */
	    public virtual void Init(BigInteger N, BigInteger g, IDigest digest, SecureRandom random)
	    {
	        this.N = N;
	        this.g = g;
	        this.digest = digest;
	        this.random = random;
	    }
Exemplo n.º 10
0
 public OaepEncoding(
     IAsymmetricBlockCipher	cipher,
     IDigest					hash,
     byte[]					encodingParams)
     : this(cipher, hash, hash, encodingParams)
 {
 }
Exemplo n.º 11
0
        public GenericSigner(
			IAsymmetricBlockCipher	engine,
			IDigest					digest)
        {
            this.engine = engine;
            this.digest = digest;
        }
 private DeferredHash(byte prfHashAlgorithm, IDigest prfHash)
 {
     this.mBuf = null;
     this.mHashes = Platform.CreateHashtable();
     this.mPrfHashAlgorithm = prfHashAlgorithm;
     mHashes[prfHashAlgorithm] = prfHash;
 }
Exemplo n.º 13
0
        /**
         * Base constructor.
         *
         * @param baseDigest underlying digest to use.
         * @exception IllegalArgumentException if baseDigest is null
         */
        public NonMemoableDigest(IDigest baseDigest)
        {
            if (baseDigest == null)
                throw new ArgumentNullException("baseDigest");

            this.mBaseDigest = baseDigest;
        }
Exemplo n.º 14
0
		/// <summary>Basic constructor</summary>
		/// <param name="cipher">the asymmetric cipher to use.</param>
		/// <param name="digest">the digest to use.</param>
		/// <param name="saltLen">the length of the salt to use (in bytes).</param>
		public PssSigner(
			IAsymmetricBlockCipher	cipher,
			IDigest					digest,
			int						saltLen)
			: this(cipher, digest, saltLen, TrailerImplicit)
		{
		}
Exemplo n.º 15
0
        public TlsStreamCipher(TlsClientContext context, IStreamCipher encryptCipher,
            IStreamCipher decryptCipher, IDigest writeDigest, IDigest readDigest, int cipherKeySize)
        {
            this.context = context;
            this.encryptCipher = encryptCipher;
            this.decryptCipher = decryptCipher;

            int prfSize = (2 * cipherKeySize) + writeDigest.GetDigestSize()
                + readDigest.GetDigestSize();

            SecurityParameters securityParameters = context.SecurityParameters;

            byte[] keyBlock = TlsUtilities.PRF(securityParameters.masterSecret, "key expansion",
                TlsUtilities.Concat(securityParameters.serverRandom, securityParameters.clientRandom),
                prfSize);

            int offset = 0;

            // Init MACs
            writeMac = CreateTlsMac(writeDigest, keyBlock, ref offset);
            readMac = CreateTlsMac(readDigest, keyBlock, ref offset);

            // Build keys
            KeyParameter encryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize);
            KeyParameter decryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize);

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

            // Init Ciphers
            encryptCipher.Init(true, encryptKey);
            decryptCipher.Init(false, decryptKey);
        }
Exemplo n.º 16
0
        protected virtual TlsMac CreateTlsMac(IDigest digest, byte[] buf, ref int off)
		{
			int len = digest.GetDigestSize();
			TlsMac mac = new TlsMac(digest, buf, off, len);
			off += len;
			return mac;
		}
Exemplo n.º 17
0
		public RsaDigestSigner(
			IDigest digest)
        {
            this.digest = digest;

			algId = new AlgorithmIdentifier( (DerObjectIdentifier)oidMap[digest.AlgorithmName] , DerNull.Instance);
        }
Exemplo n.º 18
0
		public DsaDigestSigner(
			IDsa	signer,
			IDigest	digest)
        {
            this.digest = digest;
            this.dsaSigner = signer;
        }
Exemplo n.º 19
0
        /**
	     * Construct a SP800-90A Hash DRBG.
	     * <p>
	     * Minimum entropy requirement is the security strength requested.
	     * </p>
	     * @param digest  source digest to use for DRB stream.
	     * @param securityStrength security strength required (in bits)
	     * @param entropySource source of entropy to use for seeding/reseeding.
	     * @param personalizationString personalization string to distinguish this DRBG (may be null).
	     * @param nonce nonce to further distinguish this DRBG (may be null).
	     */
	    public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
	    {
	        if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(digest))
	            throw new ArgumentException("Requested security strength is not supported by the derivation function");
	        if (entropySource.EntropySize < securityStrength)
	            throw new ArgumentException("Not enough entropy for security strength required");

            mDigest = digest;
	        mEntropySource = entropySource;
	        mSecurityStrength = securityStrength;
            mSeedLength = (int)seedlens[digest.AlgorithmName];

            // 1. seed_material = entropy_input || nonce || personalization_string.
	        // 2. seed = Hash_df (seed_material, seedlen).
	        // 3. V = seed.
	        // 4. C = Hash_df ((0x00 || V), seedlen). Comment: Preceed V with a byte
	        // of zeros.
	        // 5. reseed_counter = 1.
	        // 6. Return V, C, and reseed_counter as the initial_working_state

	        byte[] entropy = GetEntropy();
	        byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString);
	        byte[] seed = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength);

            mV = seed;
	        byte[] subV = new byte[mV.Length + 1];
	        Array.Copy(mV, 0, subV, 1, mV.Length);
	        mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength);

            mReseedCounter = 1;
	    }
Exemplo n.º 20
0
 /// <summary>
 /// Creates a PBKDF2 Bytes Generator based on the given HMAC function using the default SHA512 engine
 /// </summary>
 public KDF2Drbg()
 {
     _disposeEngine = true;
     _digest = new SHA512();
     _hashLength = _digest.DigestSize;
     _keySize = _digest.BlockSize;
 }
		private void doExpectedTest(IDigest digest, int seed, byte[] expected, byte[] noCycle)
		{
			DigestRandomGenerator rGen = new DigestRandomGenerator(digest);
			byte[] output = new byte[digest.GetDigestSize()];

			rGen.AddSeedMaterial(seed);

			for (int i = 0; i != 1024; i++)
			{
				rGen.NextBytes(output);
			}

			if (noCycle != null)
			{
				if (Arrays.AreEqual(noCycle, output))
				{
					Fail("seed not being cycled!");
				}
			}

			if (!Arrays.AreEqual(expected, output))
			{
				Fail("expected output doesn't match");
			}
		}
Exemplo n.º 22
0
 public static byte[] Compute(IDigest hash, byte[] data)
 {
     var result = new byte[hash.GetDigestSize()];
     hash.BlockUpdate(data, 0, data.Length);
     hash.DoFinal(result, 0);
     return result;
 }
Exemplo n.º 23
0
 public static BigInteger GeneratePrivateValue(IDigest digest, BigInteger N, BigInteger g, SecureRandom random)
 {
     int num = Math.Min(0x100, N.BitLength / 2);
     BigInteger min = BigInteger.One.ShiftLeft(num - 1);
     BigInteger max = N.Subtract(BigInteger.One);
     return BigIntegers.CreateRandomInRange(min, max, random);
 }
		/// <summary>
		/// Generate a signer for the with either implicit or explicit trailers
		/// for ISO9796-2, scheme 2 or 3.
		/// </summary>
		/// <param name="cipher">base cipher to use for signature creation/verification</param>
		/// <param name="digest">digest to use.</param>
		/// <param name="saltLength">length of salt in bytes.</param>
		/// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param>
		public Iso9796d2PssSigner(
			IAsymmetricBlockCipher	cipher,
			IDigest					digest,
			int						saltLength,
			bool					isImplicit)
		{
			this.cipher = cipher;
			this.digest = digest;
			this.hLen = digest.GetDigestSize();
			this.saltLength = saltLength;

			if (isImplicit)
			{
				trailer = TrailerImplicit;
			}
			else
			{
				if (digest is Sha1Digest)
				{
					trailer = TrailerSha1;
				}
				else if (digest is RipeMD160Digest)
				{
					trailer = TrailerRipeMD160;
				}
				else if (digest is RipeMD128Digest)
				{
					trailer = TrailerRipeMD128;
				}
				else
				{
					throw new ArgumentException("no valid trailer for digest");
				}
			}
		}
Exemplo n.º 25
0
        public DigestRandomGenerator(
			IDigest digest)
        {
            this.digest = digest;
            this.state = new byte[digest.GetDigestSize()];
            this.counter = 1;
        }
Exemplo n.º 26
0
		private static TlsMac CreateTlsMac(IDigest digest, byte[] buf, ref int off)
		{
			int len = digest.GetDigestSize();
			TlsMac mac = new TlsMac(digest, buf, off, len);
			off += len;
			return mac;
		}
Exemplo n.º 27
0
		public PssSigner(
			IAsymmetricBlockCipher	cipher,
			IDigest					contentDigest,
			IDigest					mgfDigest,
			int						saltLen)
			: this(cipher, contentDigest, mgfDigest, saltLen, TrailerImplicit)
		{
		}
Exemplo n.º 28
0
		public HMac(IDigest digest)
		{
			this.digest = digest;
			this.digestSize = digest.GetDigestSize();
			this.blockLength = digest.GetByteLength();
			this.inputPad = new byte[blockLength];
			this.outputBuf = new byte[blockLength + digestSize];
		}
		/**
		 * Construct a Pkcs 12 Parameters generator.
		 *
		 * @param digest the digest to be used as the source of derived keys.
		 * @exception ArgumentException if an unknown digest is passed in.
		 */
		public Pkcs12ParametersGenerator(
			IDigest digest)
		{
			this.digest = digest;

			u = digest.GetDigestSize();
			v = digest.GetByteLength();
		}
        /// <summary>Create a generator for the passed in keyAlgorithm and hashAlgorithm codes.</summary>
        public PgpSignatureGenerator(PublicKeyAlgorithmTag keyAlgorithm, HashAlgorithmTag hashAlgorithm)
        {
            _keyAlgorithm = keyAlgorithm;
            _hashAlgorithm = hashAlgorithm;

            _dig = DigestUtilities.GetDigest(PgpUtilities.GetDigestName(hashAlgorithm));
            _sig = SignerUtilities.GetSigner(PgpUtilities.GetSignatureName(keyAlgorithm, hashAlgorithm));
        }
Exemplo n.º 31
0
 /// <summary>
 /// Initialize this class
 /// </summary>
 ///
 /// <param name="Paramaters">The cipher parameters</param>
 public FujisakiCipher(MPKCParameters Paramaters)
 {
     _cipherParams = Paramaters;
     _dgtEngine    = GetDigest(Paramaters.Digest);
 }
Exemplo n.º 32
0
 public Pkcs5S2ParametersGenerator(IDigest digest)
 {
     this.hMac  = new HMac(digest);
     this.state = new byte[hMac.GetMacSize()];
 }
Exemplo n.º 33
0
        public static void SignPrehash(byte[] sk, int skOff, byte[] pk, int pkOff, byte[] ctx, IDigest ph, byte[] sig, int sigOff)
        {
            byte[] m = new byte[PrehashSize];
            if (PrehashSize != ph.DoFinal(m, 0))
            {
                throw new ArgumentException("ph");
            }

            byte phflag = 0x01;

            ImplSign(sk, skOff, pk, pkOff, ctx, phflag, m, 0, m.Length, sig, sigOff);
        }
Exemplo n.º 34
0
 /**
  * Constructor for a signer with an explicit digest trailer.
  *
  * @param cipher cipher to use.
  * @param digest digest to sign with.
  */
 public X931Signer(IAsymmetricBlockCipher cipher, IDigest digest)
     :   this(cipher, digest, false)
 {
 }
Exemplo n.º 35
0
        public DeterministicECDSA()
            : base(new HMacDsaKCalculator(new Sha256Digest()))

        {
            _digest = new Sha256Digest();
        }
Exemplo n.º 36
0
 /**
  * Construct a KDF2 bytes generator. Generates key material
  * according to IEEE P1363 or ISO 18033 depending on the initialisation.
  *
  * @param digest the digest to be used as the source of derived keys.
  */
 public Kdf2BytesGenerator(
     IDigest digest)
     : base(1, digest)
 {
 }
Exemplo n.º 37
0
 public static void Update(this IDigest dgst, byte[] input)
 {
     dgst.Update(input, 0, input.Length);
 }
Exemplo n.º 38
0
 /// <summary>
 /// Creates a HKDFBytesGenerator based on the given hash function.
 /// </summary>
 /// <param name="hash">the digest to be used as the source of generatedBytes bytes</param>
 public HkdfBytesGenerator(IDigest hash)
 {
     this._hMacHash = new HMac(hash);
     this._hashLen  = hash.GetDigestSize();
 }
Exemplo n.º 39
0
 public OaepEncoding(
     IAsymmetricBlockCipher cipher,
     IDigest hash)
     : this(cipher, hash, null)
 {
 }
Exemplo n.º 40
0
 /// <summary> Constructor for a signer with an explicit digest trailer.
 ///
 /// </summary>
 /// <param name="cipher">cipher to use.
 /// </param>
 /// <param name="digest">digest to sign with.
 /// </param>
 public Iso9796d2Signer(IAsymmetricBlockCipher cipher, IDigest digest)
     : this(cipher, digest, false)
 {
 }
Exemplo n.º 41
0
 /**
  * Construct a Pkcs 5 Scheme 1 Parameters generator.
  *
  * @param digest the digest to be used as the source of derived keys.
  */
 public Pkcs5S1ParametersGenerator(
     IDigest digest)
 {
     this.digest = digest;
 }
Exemplo n.º 42
0
 private void AddFieldElement(IDigest digest, ECFieldElement v)
 {
     byte[] p = v.GetEncoded();
     digest.BlockUpdate(p, 0, p.Length);
 }
Exemplo n.º 43
0
 public SM2Signer(IDigest digest)
     : this(StandardDsaEncoding.Instance, digest)
 {
 }
Exemplo n.º 44
0
 public static byte[] Digest(this IDigest dgst)
 {
     byte[] output = new byte[dgst.GetDigestSize()];
     dgst.DoFinal(output, 0);
     return(output);
 }
Exemplo n.º 45
0
 public static void Update(this IDigest dgst, byte[] input, int offset, int len)
 {
     dgst.BlockUpdate(input, offset, len);
 }
Exemplo n.º 46
0
 private static void Hash(IDigest d, byte[] input, byte[] output, int outPos)
 {
     d.BlockUpdate(input, 0, input.Length);
     d.DoFinal(output, outPos);
 }
Exemplo n.º 47
0
        private bool DoVerify(
            AsymmetricKeyParameter key)
        {
            string  digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
            IDigest digest     = Helper.GetDigestInstance(digestName);

            DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID;
            Asn1Encodable       sigParams = this.encryptionAlgorithm.Parameters;
            ISigner             sig;

            if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss))
            {
                // RFC 4056 2.2
                // When the id-RSASSA-PSS algorithm identifier is used for a signature,
                // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
                if (sigParams == null)
                {
                    throw new CmsException("RSASSA-PSS signature must specify algorithm parameters");
                }

                try
                {
                    // TODO Provide abstract configuration mechanism
                    // (via alternate SignerUtilities.GetSigner method taking ASN.1 params)

                    Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance(
                        sigParams.ToAsn1Object());

                    if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm");
                    }
                    if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF");
                    }

                    IDigest pssDigest    = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID);
                    int     saltLength   = pss.SaltLength.Value.IntValue;
                    byte    trailerField = (byte)pss.TrailerField.Value.IntValue;

                    // RFC 4055 3.1
                    // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC
                    if (trailerField != 1)
                    {
                        throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1");
                    }

                    sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength);
                }
                catch (Exception e)
                {
                    throw new CmsException("failed to set RSASSA-PSS signature parameters", e);
                }
            }
            else
            {
                // TODO Probably too strong a check at the moment
//				if (sigParams != null)
//					throw new CmsException("unrecognised signature parameters provided");

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

                sig = Helper.GetSignatureInstance(signatureName);
            }

            try
            {
                if (digestCalculator != null)
                {
                    resultDigest = digestCalculator.GetDigest();
                }
                else
                {
                    if (content != null)
                    {
                        content.Write(new CmsSignedGenerator.DigOutputStream(digest));
                    }
                    else if (signedAttributeSet == null)
                    {
                        // TODO Get rid of this exception and just treat content==null as empty not missing?
                        throw new CmsException("data not encapsulated in signature - use detached constructor.");
                    }

                    resultDigest = DigestUtilities.DoFinal(digest);
                }
            }
            catch (IOException e)
            {
                throw new CmsException("can't process mime object to create signature.", e);
            }

            // TODO Shouldn't be using attribute OID as contentType (should be null)
            bool isCounterSignature = contentType.Equals(CmsAttributes.CounterSignature);

            // RFC 3852 11.1 Check the content-type attribute is correct
            {
                Asn1Object validContentType = GetSingleValuedSignedAttribute(
                    CmsAttributes.ContentType, "content-type");
                if (validContentType == null)
                {
                    if (!isCounterSignature && signedAttributeSet != null)
                    {
                        throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
                    }
                }
                else
                {
                    if (isCounterSignature)
                    {
                        throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
                    }

                    if (!(validContentType is DerObjectIdentifier))
                    {
                        throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
                    }

                    DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType;

                    if (!signedContentType.Equals(contentType))
                    {
                        throw new CmsException("content-type attribute value does not match eContentType");
                    }
                }
            }

            // RFC 3852 11.2 Check the message-digest attribute is correct
            {
                Asn1Object validMessageDigest = GetSingleValuedSignedAttribute(
                    CmsAttributes.MessageDigest, "message-digest");
                if (validMessageDigest == null)
                {
                    if (signedAttributeSet != null)
                    {
                        throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
                    }
                }
                else
                {
                    if (!(validMessageDigest is Asn1OctetString))
                    {
                        throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
                    }

                    Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest;

                    if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets()))
                    {
                        throw new CmsException("message-digest attribute value does not match calculated value");
                    }
                }
            }

            // RFC 3852 11.4 Validate countersignature attribute(s)
            {
                Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
                if (signedAttrTable != null &&
                    signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0)
                {
                    throw new CmsException("A countersignature attribute MUST NOT be a signed attribute");
                }

                Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
                if (unsignedAttrTable != null)
                {
                    foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature))
                    {
                        if (csAttr.AttrValues.Count < 1)
                        {
                            throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue");
                        }

                        // Note: We don't recursively validate the countersignature value
                    }
                }
            }

            try
            {
                sig.Init(false, key);

                if (signedAttributeSet == null)
                {
                    if (digestCalculator != null)
                    {
                        // need to decrypt signature and check message bytes
                        return(VerifyDigest(resultDigest, key, this.GetSignature()));
                    }
                    else if (content != null)
                    {
                        // TODO Use raw signature of the hash value instead
                        content.Write(new CmsSignedGenerator.SigOutputStream(sig));
                    }
                }
                else
                {
                    byte[] tmp = this.GetEncodedSignedAttributes();
                    sig.BlockUpdate(tmp, 0, tmp.Length);
                }

                return(sig.VerifySignature(this.GetSignature()));
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key not appropriate to signature in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("can't process mime object to create signature.", e);
            }
            catch (SignatureException e)
            {
                throw new CmsException("invalid signature format in message: " + e.Message, e);
            }
        }
Exemplo n.º 48
0
        private static STOutput ImplSTRandomPrime(IDigest d, int length, byte[] primeSeed)
        {
            int dLen = d.GetDigestSize();

            if (length < 33)
            {
                int primeGenCounter = 0;

                byte[] c0 = new byte[dLen];
                byte[] c1 = new byte[dLen];

                for (;;)
                {
                    Hash(d, primeSeed, c0, 0);
                    Inc(primeSeed, 1);

                    Hash(d, primeSeed, c1, 0);
                    Inc(primeSeed, 1);

                    uint c = Extract32(c0) ^ Extract32(c1);
                    c &= (uint.MaxValue >> (32 - length));
                    c |= (1U << (length - 1)) | 1U;

                    ++primeGenCounter;

                    if (IsPrime32(c))
                    {
                        return(new STOutput(BigInteger.ValueOf((long)c), primeSeed, primeGenCounter));
                    }

                    if (primeGenCounter > (4 * length))
                    {
                        throw new InvalidOperationException("Too many iterations in Shawe-Taylor Random_Prime Routine");
                    }
                }
            }

            STOutput rec = ImplSTRandomPrime(d, (length + 3) / 2, primeSeed);

            {
                BigInteger c0 = rec.Prime;
                primeSeed = rec.PrimeSeed;
                int primeGenCounter = rec.PrimeGenCounter;

                int outlen     = 8 * dLen;
                int iterations = (length - 1) / outlen;

                int oldCounter = primeGenCounter;

                BigInteger x = HashGen(d, primeSeed, iterations + 1);
                x = x.Mod(One.ShiftLeft(length - 1)).SetBit(length - 1);

                BigInteger c0x2 = c0.ShiftLeft(1);
                BigInteger tx2  = x.Subtract(One).Divide(c0x2).Add(One).ShiftLeft(1);
                int        dt   = 0;

                BigInteger c = tx2.Multiply(c0).Add(One);

                /*
                 * TODO Since the candidate primes are generated by constant steps ('c0x2'),
                 * sieving could be used here in place of the 'HasAnySmallFactors' approach.
                 */
                for (;;)
                {
                    if (c.BitLength > length)
                    {
                        tx2 = One.ShiftLeft(length - 1).Subtract(One).Divide(c0x2).Add(One).ShiftLeft(1);
                        c   = tx2.Multiply(c0).Add(One);
                    }

                    ++primeGenCounter;

                    /*
                     * This is an optimization of the original algorithm, using trial division to screen out
                     * many non-primes quickly.
                     *
                     * NOTE: 'primeSeed' is still incremented as if we performed the full check!
                     */
                    if (!ImplHasAnySmallFactors(c))
                    {
                        BigInteger a = HashGen(d, primeSeed, iterations + 1);
                        a = a.Mod(c.Subtract(Three)).Add(Two);

                        tx2 = tx2.Add(BigInteger.ValueOf(dt));
                        dt  = 0;

                        BigInteger z = a.ModPow(tx2, c);

                        if (c.Gcd(z.Subtract(One)).Equals(One) && z.ModPow(c0, c).Equals(One))
                        {
                            return(new STOutput(c, primeSeed, primeGenCounter));
                        }
                    }
                    else
                    {
                        Inc(primeSeed, iterations + 1);
                    }

                    if (primeGenCounter >= ((4 * length) + oldCounter))
                    {
                        throw new InvalidOperationException("Too many iterations in Shawe-Taylor Random_Prime Routine");
                    }

                    dt += 2;
                    c   = c.Add(c0x2);
                }
            }
        }
Exemplo n.º 49
0
 public DeterministicECDSA(Func <IDigest> digest)
     : base(new HMacDsaKCalculator(digest()))
 {
     _digest = digest();
 }
Exemplo n.º 50
0
        public void MineBlock(Block block)
        {
            INonceGenerator nonceGenerator = HashFactory.GetNonceGenerator();
            IByteConverter  converter      = HashFactory.GetByteConverter();

            if (Difficulty >= HashFactory.GetDigest().HashLength)
            {
                throw new ArgumentException("Difficulty can not be greater or equal to hash length.");
            }

            if (Difficulty <= 0)
            {
                throw new ArgumentException("Difficulty can not be greater or equal to zero.");
            }

            byte[] target = new byte[Difficulty];

            block.HashAlgorithmId = HashAlgorithmId;
            block.Difficulty      = Difficulty;

            nonceGenerator.Reset();

            #region Parallel mining.

            CancellationTokenSource tokenSource = new CancellationTokenSource();
            object locker        = new object();
            byte[] solutionNonce = null;
            byte[] solutionHash  = null;

            string immutableData = converter.ConvertToString(block.PreviousHash) +
                                   block.CreationTime.ToString() +
                                   converter.ConvertToString(block.MerkleRoot) +
                                   converter.ConvertToString(block.MinerAddress) +
                                   block.HashAlgorithmId +
                                   block.Difficulty;
            try
            {
                Parallel.ForEach(nonceGenerator, new ParallelOptions()
                {
                    CancellationToken = tokenSource.Token
                }, (byte[] nonce) =>
                {
                    IDigest digest = HashFactory.GetDigest();

                    converter = HashFactory.GetByteConverter();

                    string dataWithNonce = converter.ConvertToString(nonce) + immutableData;
                    byte[] rawData       = Encoding.ASCII.GetBytes(dataWithNonce);
                    byte[] hash          = digest.GetHash(rawData);

                    if (hash.Take(Difficulty).SequenceEqual(target))
                    {
                        lock (locker)
                        {
                            solutionNonce = nonce;
                            solutionHash  = hash;
                        }

                        tokenSource.Cancel();
                    }
                });
            }
            catch (OperationCanceledException)
            {
            }

            block.Nonce = solutionNonce ?? throw new MiningFailureException("Couldn't resolve block", block);
            block.Hash  = solutionHash;

            #endregion
        }
Exemplo n.º 51
0
        public TlsBlockCipher(TlsContext context, IBlockCipher clientWriteCipher, IBlockCipher serverWriteCipher, IDigest clientWriteDigest, IDigest serverWriteDigest, int cipherKeySize)
        {
            this.context = context;
            randomData   = new byte[256];
            context.NonceRandomGenerator.NextBytes(randomData);
            useExplicitIV  = TlsUtilities.IsTlsV11(context);
            encryptThenMac = context.SecurityParameters.encryptThenMac;
            int num = 2 * cipherKeySize + clientWriteDigest.GetDigestSize() + serverWriteDigest.GetDigestSize();

            if (!useExplicitIV)
            {
                num += clientWriteCipher.GetBlockSize() + serverWriteCipher.GetBlockSize();
            }
            byte[] array  = TlsUtilities.CalculateKeyBlock(context, num);
            int    num2   = 0;
            TlsMac tlsMac = new TlsMac(context, clientWriteDigest, array, num2, clientWriteDigest.GetDigestSize());

            num2 += clientWriteDigest.GetDigestSize();
            TlsMac tlsMac2 = new TlsMac(context, serverWriteDigest, array, num2, serverWriteDigest.GetDigestSize());

            num2 += serverWriteDigest.GetDigestSize();
            KeyParameter parameters = new KeyParameter(array, num2, cipherKeySize);

            num2 += cipherKeySize;
            KeyParameter parameters2 = new KeyParameter(array, num2, cipherKeySize);

            num2 += cipherKeySize;
            byte[] iv;
            byte[] iv2;
            if (useExplicitIV)
            {
                iv  = new byte[clientWriteCipher.GetBlockSize()];
                iv2 = new byte[serverWriteCipher.GetBlockSize()];
            }
            else
            {
                iv    = Arrays.CopyOfRange(array, num2, num2 + clientWriteCipher.GetBlockSize());
                num2 += clientWriteCipher.GetBlockSize();
                iv2   = Arrays.CopyOfRange(array, num2, num2 + serverWriteCipher.GetBlockSize());
                num2 += serverWriteCipher.GetBlockSize();
            }
            if (num2 != num)
            {
                throw new TlsFatalAlert(80);
            }
            ICipherParameters parameters3;
            ICipherParameters parameters4;

            if (context.IsServer)
            {
                mWriteMac     = tlsMac2;
                mReadMac      = tlsMac;
                encryptCipher = serverWriteCipher;
                decryptCipher = clientWriteCipher;
                parameters3   = new ParametersWithIV(parameters2, iv2);
                parameters4   = new ParametersWithIV(parameters, iv);
            }
            else
            {
                mWriteMac     = tlsMac;
                mReadMac      = tlsMac2;
                encryptCipher = clientWriteCipher;
                decryptCipher = serverWriteCipher;
                parameters3   = new ParametersWithIV(parameters, iv);
                parameters4   = new ParametersWithIV(parameters2, iv2);
            }
            encryptCipher.Init(forEncryption: true, parameters3);
            decryptCipher.Init(forEncryption: false, parameters4);
        }
Exemplo n.º 52
0
 /// <summary>
 /// IMPORTANT: USE THIS METHOD CAREFULLY.
 /// This method serves as replacement for the java method MessageDigest#digest(byte[] buf, int offset, int len).
 /// However for now, we simply omit len parameter, because it doesn't affect anything for all current usages
 /// (there are two of them at the moment of the method addition which are in StandardHandlerUsingAes256 class).
 /// This may be not true for future possible usages, so be aware.
 /// </summary>
 public static void Digest(this IDigest dgst, byte[] buff, int offest, int len)
 {
     dgst.DoFinal(buff, offest);
 }
Exemplo n.º 53
0
        public static bool VerifyPrehash(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] ctx, IDigest ph)
        {
            byte[] m = new byte[PrehashSize];
            if (PrehashSize != ph.DoFinal(m, 0))
            {
                throw new ArgumentException("ph");
            }

            byte phflag = 0x01;

            return(ImplVerify(sig, sigOff, pk, pkOff, ctx, phflag, m, 0, m.Length));
        }
        public byte[] GetDigest()
        {
            IDigest digest = CmsSignedHelper.Instance.GetDigestInstance(alg);

            return(DigestUtilities.DoFinal(digest, data));
        }
Exemplo n.º 55
0
 protected override IDigest CloneDigest(IDigest digest)
 {
     return(new Sha1Digest((Sha1Digest)digest));
 }
Exemplo n.º 56
0
 internal void UpdateDigest(IDigest d)
 {
     WriteTo(new DigStream(d));
 }
Exemplo n.º 57
0
 public static byte[] Digest(this IDigest dgst, byte[] input)
 {
     dgst.Update(input);
     return(dgst.Digest());
 }
Exemplo n.º 58
0
 internal DigStream(IDigest d)
 {
     this.d = d;
 }
Exemplo n.º 59
0
        /**
         * generate suitable parameters for DSA, in line with
         * <i>FIPS 186-3 A.1 Generation of the FFC Primes p and q</i>.
         */
        protected virtual DsaParameters GenerateParameters_FIPS186_3()
        {
// A.1.1.2 Generation of the Probable Primes p and q Using an Approved Hash Function
            IDigest d      = digest;
            int     outlen = d.GetDigestSize() * 8;

// 1. Check that the (L, N) pair is in the list of acceptable (L, N pairs) (see Section 4.2). If
//    the pair is not in the list, then return INVALID.
            // Note: checked at initialisation

// 2. If (seedlen < N), then return INVALID.
            // FIXME This should be configurable (must be >= N)
            int seedlen = N;

            byte[] seed = new byte[seedlen / 8];

// 3. n = ceiling(L ⁄ outlen) – 1.
            int n = (L - 1) / outlen;

// 4. b = L – 1 – (n ∗ outlen).
            int b = (L - 1) % outlen;

            byte[] output = new byte[d.GetDigestSize()];
            for (;;)
            {
// 5. Get an arbitrary sequence of seedlen bits as the domain_parameter_seed.
                random.NextBytes(seed);

// 6. U = Hash (domain_parameter_seed) mod 2^(N–1).
                Hash(d, seed, output);
                BigInteger U = new BigInteger(1, output).Mod(BigInteger.One.ShiftLeft(N - 1));

// 7. q = 2^(N–1) + U + 1 – ( U mod 2).
                BigInteger q = U.SetBit(0).SetBit(N - 1);

// 8. Test whether or not q is prime as specified in Appendix C.3.
                // TODO Review C.3 for primality checking
                if (!q.IsProbablePrime(certainty))
                {
// 9. If q is not a prime, then go to step 5.
                    continue;
                }

// 10. offset = 1.
                // Note: 'offset' value managed incrementally
                byte[] offset = Arrays.Clone(seed);

// 11. For counter = 0 to (4L – 1) do
                int counterLimit = 4 * L;
                for (int counter = 0; counter < counterLimit; ++counter)
                {
// 11.1 For j = 0 to n do
//      Vj = Hash ((domain_parameter_seed + offset + j) mod 2^seedlen).
// 11.2 W = V0 + (V1 ∗ 2^outlen) + ... + (V^(n–1) ∗ 2^((n–1) ∗ outlen)) + ((Vn mod 2^b) ∗ 2^(n ∗ outlen)).
                    // TODO Assemble w as a byte array
                    BigInteger W = BigInteger.Zero;
                    for (int j = 0, exp = 0; j <= n; ++j, exp += outlen)
                    {
                        Inc(offset);
                        Hash(d, offset, output);

                        BigInteger Vj = new BigInteger(1, output);
                        if (j == n)
                        {
                            Vj = Vj.Mod(BigInteger.One.ShiftLeft(b));
                        }

                        W = W.Add(Vj.ShiftLeft(exp));
                    }

// 11.3 X = W + 2^(L–1). Comment: 0 ≤ W < 2L–1; hence, 2L–1 ≤ X < 2L.
                    BigInteger X = W.Add(BigInteger.One.ShiftLeft(L - 1));

// 11.4 c = X mod 2q.
                    BigInteger c = X.Mod(q.ShiftLeft(1));

// 11.5 p = X - (c - 1). Comment: p ≡ 1 (mod 2q).
                    BigInteger p = X.Subtract(c.Subtract(BigInteger.One));

                    // 11.6 If (p < 2^(L - 1)), then go to step 11.9
                    if (p.BitLength != L)
                    {
                        continue;
                    }

// 11.7 Test whether or not p is prime as specified in Appendix C.3.
                    // TODO Review C.3 for primality checking
                    if (p.IsProbablePrime(certainty))
                    {
// 11.8 If p is determined to be prime, then return VALID and the values of p, q and
//      (optionally) the values of domain_parameter_seed and counter.
                        // TODO Make configurable (8-bit unsigned)?

                        if (usageIndex >= 0)
                        {
                            BigInteger g = CalculateGenerator_FIPS186_3_Verifiable(d, p, q, seed, usageIndex);
                            if (g != null)
                            {
                                return(new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter, usageIndex)));
                            }
                        }

                        {
                            BigInteger g = CalculateGenerator_FIPS186_3_Unverifiable(p, q, random);

                            return(new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter)));
                        }
                    }

// 11.9 offset = offset + n + 1.      Comment: Increment offset; then, as part of
//                                    the loop in step 11, increment counter; if
//                                    counter < 4L, repeat steps 11.1 through 11.8.
                    // Note: 'offset' value already incremented in inner loop
                }
// 12. Go to step 5.
            }
        }
Exemplo n.º 60
0
 public SM2Signer(IDsaEncoding encoding, IDigest digest)
 {
     this.encoding = encoding;
     this.digest   = digest;
 }