Inheritance: GeneralDigest
		public override void PerformTest()
		{
			IDigest  d = new Sha1Digest();
			ShortenedDigest sd = new ShortenedDigest(new Sha1Digest(), 10);

			if (sd.GetDigestSize() != 10)
			{
				Fail("size check wrong for SHA-1");
			}

			if (sd.GetByteLength() != d.GetByteLength())
			{
				Fail("byte length check wrong for SHA-1");
			}

			//
			// check output fits
			//
			sd.DoFinal(new byte[10], 0);

			d = new Sha512Digest();
			sd = new ShortenedDigest(new Sha512Digest(), 20);

			if (sd.GetDigestSize() != 20)
			{
				Fail("size check wrong for SHA-512");
			}

			if (sd.GetByteLength() != d.GetByteLength())
			{
				Fail("byte length check wrong for SHA-512");
			}

			//
			// check output fits
			//
			sd.DoFinal(new byte[20], 0);

			try
			{
				new ShortenedDigest(null, 20);

				Fail("null parameter not caught");
			}
			catch (ArgumentException)
			{
				// expected
			}

			try
			{
				new ShortenedDigest(new Sha1Digest(), 50);

				Fail("short digest not caught");
			}
			catch (ArgumentException)
			{
				// expected
			}
		}
        internal SecureMimeDigitalCertificate(X509Certificate certificate)
        {
            Certificate = certificate;

            var pubkey = certificate.GetPublicKey ();
            if (pubkey is DsaKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.Dsa;
            else if (pubkey is RsaKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.RsaGeneral;
            else if (pubkey is ElGamalKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.ElGamalGeneral;
            else if (pubkey is ECKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.EllipticCurve;
            else if (pubkey is DHKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.DiffieHellman;

            var encoded = certificate.GetEncoded ();
            var fingerprint = new StringBuilder ();
            var sha1 = new Sha1Digest ();
            var data = new byte[20];

            sha1.BlockUpdate (encoded, 0, encoded.Length);
            sha1.DoFinal (data, 0);

            for (int i = 0; i < data.Length; i++)
                fingerprint.Append (data[i].ToString ("X2"));

            Fingerprint = fingerprint.ToString ();
        }
 private byte[] ComputeHash(byte[] input)
 {
     var sha = new Sha1Digest();
     sha.BlockUpdate(input, 0, input.Length);
     byte[] result = new byte[sha.GetDigestSize()];
     sha.DoFinal(result, 0);
     return result;
 }
Example #4
0
 /// <summary>
 /// Compute the hash of the input byte array and return the hashed value as a byte array.
 /// </summary>
 /// <param name="inputData">Input data</param>
 /// <returns>SHA1 Hashed data.</returns>
 byte[] IHashProvider.ComputeHash( byte[] inputData )
 {
     Sha1Digest digest = new Sha1Digest();
     digest.BlockUpdate( inputData, 0, inputData.Length );
     byte[] result = new byte[digest.GetDigestSize()];
     digest.DoFinal( result, 0 );
     return result;
 }
        static Asn1OctetString CreateDigestFromBytes(byte[] bytes)
        {
            var digest = new Sha1Digest();

            digest.BlockUpdate(bytes, 0, bytes.Length);
            var digestBytes = new byte[digest.GetDigestSize()];
            digest.DoFinal(digestBytes, 0);
            return new DerOctetString(digestBytes);
        }
Example #6
0
 public static string Sha1(string input)
 {
     var data = System.Text.Encoding.UTF8.GetBytes(input);
     Sha1Digest hash = new Sha1Digest();
     hash.BlockUpdate(data, 0, data.Length);
     byte[] result = new byte[hash.GetDigestSize()];
     hash.DoFinal(result, 0);
     return Hex.ToHexString(result);
 }
Example #7
0
 private void CopyIn(Sha1Digest t)
 {
     CopyIn((GeneralDigest)t);
     H1 = t.H1;
     H2 = t.H2;
     H3 = t.H3;
     H4 = t.H4;
     H5 = t.H5;
     Array.Copy(t.X, 0, X, 0, t.X.Length);
     xOff = t.xOff;
 }
Example #8
0
 private void CopyIn(Sha1Digest t)
 {
     base.CopyIn(t);
     this.H1 = t.H1;
     this.H2 = t.H2;
     this.H3 = t.H3;
     this.H4 = t.H4;
     this.H5 = t.H5;
     Array.Copy(t.X, 0, this.X, 0, t.X.Length);
     this.xOff = t.xOff;
 }
        /**
         *
         * Calulates the keyidentifier using a SHA1 hash over the BIT STRING
         * from SubjectPublicKeyInfo as defined in RFC2459.
         *
         * Example of making a AuthorityKeyIdentifier:
         * <pre>
         *   SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream(
         *       publicKey.getEncoded()).readObject());
         *   AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
         * </pre>
         *
         **/
        public AuthorityKeyIdentifier(
            SubjectPublicKeyInfo spki)
        {
            IDigest digest = new Sha1Digest();
            byte[] resBuf = new byte[digest.GetDigestSize()];

            byte[] bytes = spki.PublicKeyData.GetBytes();
            digest.BlockUpdate(bytes, 0, bytes.Length);
            digest.DoFinal(resBuf, 0);
            this.keyidentifier = new DerOctetString(resBuf);
        }
Example #10
0
 private void CopyIn(Sha1Digest t)
 {
     CopyIn((GeneralDigest)t);
     H1 = t.H1;
     H2 = t.H2;
     H3 = t.H3;
     H4 = t.H4;
     H5 = t.H5;
     global::System.Array.Copy((global::System.Array)t.X, 0, (global::System.Array)X, 0, t.X.Length);
     xOff = t.xOff;
 }
Example #11
0
		/**
         *
         * Calulates the keyIdentifier using a SHA1 hash over the BIT STRING
         * from SubjectPublicKeyInfo as defined in RFC2459.
         *
         **/
        public SubjectKeyIdentifier(
            SubjectPublicKeyInfo spki)
        {
            IDigest digest = new Sha1Digest();
            byte[] resBuf = new byte[digest.GetDigestSize()];

			byte[] bytes = spki.PublicKeyData.GetBytes();
            digest.BlockUpdate(bytes, 0, bytes.Length);
            digest.DoFinal(resBuf, 0);
            this.keyIdentifier = resBuf;
        }
Example #12
0
        /**
         * Copy constructor.  This will copy the state of the provided
         * message digest.
         */
        public Sha1Digest(Sha1Digest t)
            : base(t)
        {
            H1 = t.H1;
            H2 = t.H2;
            H3 = t.H3;
            H4 = t.H4;
            H5 = t.H5;

            Array.Copy(t.X, 0, X, 0, t.X.Length);
            xOff = t.xOff;
        }
Example #13
0
        /**
         * Copy constructor.  This will copy the state of the provided
         * message digest.
         */
        public Sha1Digest(Sha1Digest t)
            : base(t)
        {
            H1 = t.H1;
            H2 = t.H2;
            H3 = t.H3;
            H4 = t.H4;
            H5 = t.H5;

            Array.Copy(t.X, 0, X, 0, t.X.Length);
            xOff = t.xOff;
        }
Example #14
0
		private void CopyIn(Sha1Digest t)
		{
			base.CopyIn(t);

            H1 = t.H1;
            H2 = t.H2;
            H3 = t.H3;
            H4 = t.H4;
            H5 = t.H5;

            Array.Copy(t.X, 0, X, 0, t.X.Length);
            xOff = t.xOff;
        }
        /// <summary>
        /// Gets the fingerprint of the certificate.
        /// </summary>
        /// <remarks>
        /// A fingerprint is a SHA-1 hash of the raw certificate data and is often used
        /// as a unique identifier for a particular certificate in a certificate store.
        /// </remarks>
        /// <returns>The fingerprint.</returns>
        /// <param name="certificate">The certificate.</param>
        public static string GetFingerprint(this X509Certificate certificate)
        {
            var encoded = certificate.GetEncoded ();
            var fingerprint = new StringBuilder ();
            var sha1 = new Sha1Digest ();
            var data = new byte[20];

            sha1.BlockUpdate (encoded, 0, encoded.Length);
            sha1.DoFinal (data, 0);

            for (int i = 0; i < data.Length; i++)
                fingerprint.Append (data[i].ToString ("x2"));

            return fingerprint.ToString ();
        }
        /**
         * create an AuthorityKeyIdentifier with the GeneralNames tag and
         * the serial number provided as well.
         */
        public AuthorityKeyIdentifier(
            SubjectPublicKeyInfo	spki,
            GeneralNames			name,
            BigInteger				serialNumber)
        {
            IDigest digest = new Sha1Digest();
            byte[] resBuf = new byte[digest.GetDigestSize()];

            byte[] bytes = spki.PublicKeyData.GetBytes();
            digest.BlockUpdate(bytes, 0, bytes.Length);
            digest.DoFinal(resBuf, 0);

            this.keyidentifier = new DerOctetString(resBuf);
            this.certissuer = name;
            this.certserno = new DerInteger(serialNumber);
        }
Example #17
0
        public static string CreateResponseKey(string requestKey)
        {
            var combined = requestKey + WebSocketResponseGuid;
            #if !PORTABLE
            var bytes = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(combined));
            #else

            var bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(combined);
            IDigest hash = new Sha1Digest();

            byte[] result = new byte[hash.GetDigestSize()];

            hash.BlockUpdate(bytes, 0, bytes.Length);

            hash.DoFinal(result, 0);

            bytes = result;

            //// Convert the message string to binary data.
            //IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(combined, BinaryStringEncoding.Utf8);

            //// Create a HashAlgorithmProvider object.
            //HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);

            //// Demonstrate how to retrieve the name of the hashing algorithm.
            //String strAlgNameUsed = objAlgProv.AlgorithmName;

            //// Hash the message.
            //IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

            //// Verify that the hash length equals the length specified for the algorithm.
            //if (buffHash.Length != objAlgProv.HashLength)
            //{
            //    throw new Exception("There was an error creating the hash");
            //}

            //// Convert the hash to a string (for display).
            //String strHashBase64 = CryptographicBuffer.EncodeToBase64String(buffHash);

            //byte[] bytes = new byte[buffHash.Length];
            //CryptographicBuffer.CopyToByteArray(buffHash, out bytes);
            #endif

            return Convert.ToBase64String(bytes);
        }
Example #18
0
        /// <summary>
        /// Check an Active Authentication reply from the passport.
        /// </summary>
        /// <param name="publicKey">The AA public key read from the passport.</param>
        /// <param name="message">The original message.</param>
        /// <param name="signature">The response from the passport</param>
        /// <returns>True if the signature is correct for this message.</returns>
        public static bool CheckAA(RsaPublicKeyStructure publicKey, byte[] message, byte[] signature)
        {
            SHA1 sha1 = SHA1.Create();
            RsaEngine rsa = new RsaEngine();
            RsaKeyParameters p = new RsaKeyParameters(false, publicKey.Modulus, publicKey.PublicExponent);
            rsa.Init(false, p);

            byte[] digestedMessage = sha1.ComputeHash(message); // should always be 20 bytes
            byte[] m2 = new byte[8];
            Array.Copy(digestedMessage, 0, m2, 0, m2.Length);
            byte[] plainText = rsa.ProcessBlock(signature, 0, signature.Length);
            byte[] m1 = recoverMessage(digestedMessage.Length, plainText);

            Sha1Digest digest = new Sha1Digest();
            Iso9796d2Signer signer = new Iso9796d2Signer(rsa, digest);
            signer.Init(false, p);
            signer.BlockUpdate(m1, 0, m1.Length);
            signer.BlockUpdate(m2, 0, m2.Length);
            return signer.VerifySignature(signature);
        }
Example #19
0
		public static SecureRandom GetInstance(
			string algorithm)
		{
			// TODO Compared to JDK, we don't auto-seed if the client forgets - problem?

			// TODO Support all digests more generally, by stripping PRNG and calling DigestUtilities?
			IDigest digest = null;
			switch (algorithm.ToUpper(CultureInfo.InvariantCulture))
			{
				case "SHA1PRNG":
					digest = new Sha1Digest();
					break;
				case "SHA256PRNG":
					digest = new Sha256Digest();
					break;
			}

			if (digest != null)
			{
				return new SecureRandom(new DigestRandomGenerator(digest));
			}

			throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm");
		}
Example #20
0
		internal CombinedHash()
		{
			this.md5 = new MD5Digest();
			this.sha1 = new Sha1Digest();
		}
Example #21
0
        public void DoTest13()
        {
            BigInteger modulus = new BigInteger(1, Hex.Decode("CDCBDABBF93BE8E8294E32B055256BBD0397735189BF75816341BB0D488D05D627991221DF7D59835C76A4BB4808ADEEB779E7794504E956ADC2A661B46904CDC71337DD29DDDD454124EF79CFDD7BC2C21952573CEFBA485CC38C6BD2428809B5A31A898A6B5648CAA4ED678D9743B589134B7187478996300EDBA16271A861"));
            BigInteger pubExp = new BigInteger(1, Hex.Decode("010001"));
            BigInteger privExp = new BigInteger(1, Hex.Decode("4BA6432AD42C74AA5AFCB6DF60FD57846CBC909489994ABD9C59FE439CC6D23D6DE2F3EA65B8335E796FD7904CA37C248367997257AFBD82B26F1A30525C447A236C65E6ADE43ECAAF7283584B2570FA07B340D9C9380D88EAACFFAEEFE7F472DBC9735C3FF3A3211E8A6BBFD94456B6A33C17A2C4EC18CE6335150548ED126D"));

            RsaKeyParameters pubParams = new RsaKeyParameters(false, modulus, pubExp);
            RsaKeyParameters privParams = new RsaKeyParameters(true, modulus, privExp);

            IAsymmetricBlockCipher rsaEngine = new RsaBlindedEngine();
            IDigest digest = new Sha256Digest();

            // set challenge to all zero's for verification
            byte[] challenge = new byte[8];

            // DOES NOT USE FINAL BOOLEAN TO INDICATE RECOVERY
            Iso9796d2Signer signer = new Iso9796d2Signer(rsaEngine, digest, false);

            // sign
            signer.Init(true, privParams);
            signer.BlockUpdate(challenge, 0, challenge.Length);

            byte[]  sig = signer.GenerateSignature();

            // verify
            signer.Init(false, pubParams);
            signer.BlockUpdate(challenge, 0, challenge.Length);

            if (!signer.VerifySignature(sig))
            {
                Fail("basic verification failed");
            }

            // === LETS ACTUALLY DO SOME RECOVERY, USING INPUT FROM INTERNAL AUTHENTICATE ===

            signer.Reset();

            string args0 = "482E20D1EDDED34359C38F5E7C01203F9D6B2641CDCA5C404D49ADAEDE034C7481D781D043722587761C90468DE69C6585A1E8B9C322F90E1B580EEDAB3F6007D0C366CF92B4DB8B41C8314929DCE2BE889C0129123484D2FD3D12763D2EBFD12AC8E51D7061AFCA1A53DEDEC7B9A617472A78C952CCC72467AE008E5F132994";

            digest = new Sha1Digest();

            signer = new Iso9796d2Signer(rsaEngine, digest, true);


            signer.Init(false, pubParams);
            byte[] signature = Hex.Decode(args0);
            signer.UpdateWithRecoveredMessage(signature);
            signer.BlockUpdate(challenge, 0, challenge.Length);

            if (!signer.VerifySignature(signature))
            {
                Fail("recovered + challenge signature failed");
            }

            // === FINALLY, USING SHA-256 ===

            signer.Reset();

            digest = new Sha256Digest();

            // NOTE setting implicit to false does not actually do anything for verification !!!
            signer = new Iso9796d2Signer(rsaEngine, digest, false);


            signer.Init(true, privParams);
            // generate NONCE of correct length using some inner knowledge
            int nonceLength = modulus.BitLength / 8 - 1 - digest.GetDigestSize() - 2;
            byte[] nonce = new byte[nonceLength];
            SecureRandom rnd = new SecureRandom();

            rnd.NextBytes(nonce);

            signer.BlockUpdate(nonce, 0, nonce.Length);
            signer.BlockUpdate(challenge, 0, challenge.Length);
            byte[] sig3 = signer.GenerateSignature();

            signer.Init(false, pubParams);
            signer.UpdateWithRecoveredMessage(sig3);
            signer.BlockUpdate(challenge, 0, challenge.Length);
            if (signer.VerifySignature(sig3))
            {
                if (signer.HasFullMessage())
                {
                    Fail("signer indicates full message");
                }
                byte[] recoverableMessage = signer.GetRecoveredMessage();

                // sanity check, normally the nonce is ignored in eMRTD specs (PKI Technical Report)
                if (!Arrays.AreEqual(nonce, recoverableMessage))
                {
                    Fail("Nonce compare with recoverable part of message failed");
                }
            }
            else
            {
                Fail("recoverable + nonce failed.");
            }
        }
Example #22
0
        public virtual void DoTest12()
        {
            BigInteger          mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16);
            BigInteger          pubExp = new BigInteger("65537", 10);
            BigInteger          priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16);
            RsaKeyParameters    pubParameters = new RsaKeyParameters(false, mod, pubExp);
            RsaKeyParameters    privParameters = new RsaKeyParameters(true, mod, priExp);
            RsaEngine           rsa = new RsaEngine();
            byte[]              data;
            byte[]              m1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            byte[]              m2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            byte[]              m3 = { 1, 2, 3, 4, 5, 6, 7, 8 };

            //
            // ISO 9796-2 - Regular Signing
            //
            IDigest           dig = new Sha1Digest();
            Iso9796d2Signer  eng = new Iso9796d2Signer(rsa, dig);

            //
            // check message bounds
            //
            eng.Init(true, privParameters);

            eng.BlockUpdate(m1, 0, m1.Length);

            data = eng.GenerateSignature();

            eng.Init(false, pubParameters);

            eng.BlockUpdate(m2, 0, m2.Length);

            if (eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 m2 verify Test 12");
            }

            eng.Init(false, pubParameters);

            eng.BlockUpdate(m3, 0, m3.Length);

            if (eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 m3 verify Test 12");
            }

            eng.Init(false, pubParameters);

            eng.BlockUpdate(m1, 0, m1.Length);

            if (!eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 verify Test 12");
            }
        }
Example #23
0
        public virtual void DoTest10()
        {
            BigInteger          mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16);
            BigInteger          pubExp = new BigInteger("65537", 10);
            BigInteger          priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16);
            RsaKeyParameters    pubParameters = new RsaKeyParameters(false, mod, pubExp);
            RsaKeyParameters    privParameters = new RsaKeyParameters(true, mod, priExp);
            RsaEngine           rsa = new RsaEngine();
            byte[]              data;

            //
            // ISO 9796-2 - PSS Signing
            //
            IDigest              dig = new Sha1Digest();
            Iso9796d2PssSigner  eng = new Iso9796d2PssSigner(rsa, dig, dig.GetDigestSize());

            //
            // as the padding is random this test needs to repeat a few times to
            // make sure
            //
            for (int i = 0; i != 500; i++)
            {
                eng.Init(true, privParameters);

                eng.Update(msg9[0]);
                eng.BlockUpdate(msg9, 1, msg9.Length - 1);

                data = eng.GenerateSignature();

                eng.Init(false, pubParameters);

                eng.Update(msg9[0]);
                eng.BlockUpdate(msg9, 1, msg9.Length - 1);

                if (!eng.VerifySignature(data))
                {
                    Fail("failed ISO9796-2 verify Test 10");
                }
            }
        }
Example #24
0
 public static byte[] SHA1(byte[] data, int count)
 {
     var sha1 = new Sha1Digest();
     sha1.BlockUpdate(data, 0, count);
     byte[] rv = new byte[20];
     sha1.DoFinal(rv, 0);
     return rv;
 }
Example #25
0
        /**
         * Copy constructor.  This will copy the state of the provided
         * message digest.
         */
        public Sha1Digest(Sha1Digest t)
            : base(t)
        {
			CopyIn(t);
		}
Example #26
0
        public override void Reset(IMemoable other)
        {
            Sha1Digest d = (Sha1Digest)other;

            CopyIn(d);
        }
Example #27
0
        /**
         * which Generates the p and g values from the given parameters,
         * returning the DsaParameters object.
         * <p>
         * Note: can take a while...</p>
         */
        public DsaParameters GenerateParameters()
        {
            byte[]          seed = new byte[20];
            byte[]          part1 = new byte[20];
            byte[]          part2 = new byte[20];
            byte[]          u = new byte[20];
            Sha1Digest      sha1 = new Sha1Digest();
            int             n = (size - 1) / 160;
            byte[]          w = new byte[size / 8];

            BigInteger      q = null, p = null, g = null;
            int             counter = 0;
            bool         primesFound = false;

            while (!primesFound)
            {
                do
                {
                    random.NextBytes(seed);

                    sha1.BlockUpdate(seed, 0, seed.Length);

                    sha1.DoFinal(part1, 0);

                    Array.Copy(seed, 0, part2, 0, seed.Length);

                    Add(part2, seed, 1);

                    sha1.BlockUpdate(part2, 0, part2.Length);

                    sha1.DoFinal(part2, 0);

                    for (int i = 0; i != u.Length; i++)
                    {
                        u[i] = (byte)(part1[i] ^ part2[i]);
                    }

                    u[0] |= (byte)0x80;
                    u[19] |= (byte)0x01;

                    q = new BigInteger(1, u);
                }
                while (!q.IsProbablePrime(certainty));

                counter = 0;

                int offset = 2;

                while (counter < 4096)
                {
                    for (int k = 0; k < n; k++)
                    {
                        Add(part1, seed, offset + k);
                        sha1.BlockUpdate(part1, 0, part1.Length);
                        sha1.DoFinal(part1, 0);
                        Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
                    }

                    Add(part1, seed, offset + n);
                    sha1.BlockUpdate(part1, 0, part1.Length);
                    sha1.DoFinal(part1, 0);
                    Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);

                    w[0] |= (byte)0x80;

                    BigInteger  x = new BigInteger(1, w);

                    BigInteger  c = x.Mod(q.ShiftLeft(1));

                    p = x.Subtract(c.Subtract(BigInteger.One));

                    if (p.TestBit(size - 1))
                    {
                        if (p.IsProbablePrime(certainty))
                        {
                            primesFound = true;
                            break;
                        }
                    }

                    counter += 1;
                    offset += n + 1;
                }
            }

            //
            // calculate the generator g
            //
            BigInteger  pMinusOneOverQ = p.Subtract(BigInteger.One).Divide(q);

            for (;;)
            {
                BigInteger h = new BigInteger(size, random);
                if (h.CompareTo(BigInteger.One) <= 0 || h.CompareTo(p.Subtract(BigInteger.One)) >= 0)
                {
                    continue;
                }

                g = h.ModPow(pMinusOneOverQ, p);
                if (g.CompareTo(BigInteger.One) <= 0)
                {
                    continue;
                }

                break;
            }

            return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
        }
Example #28
0
		/// <summary>
		/// Return the sha1 hash of the byte array.
		/// </summary>
		/// <param name="data">Data to be hashed.</param>
		public static string Sha1(byte[] data)
		{
			Sha1Digest digest = new Sha1Digest();
			return Encode(data, digest);
		}
		private static byte[] GetDigest(
			SubjectPublicKeyInfo spki)
		{
            IDigest digest = new Sha1Digest();
            byte[] resBuf = new byte[digest.GetDigestSize()];

			byte[] bytes = spki.PublicKeyData.GetBytes();
            digest.BlockUpdate(bytes, 0, bytes.Length);
            digest.DoFinal(resBuf, 0);
            return resBuf;
		}
Example #30
0
        public override void PerformTest()
        {
            IDigest digest = new Sha1Digest();
            byte[] resBuf = new byte[digest.GetDigestSize()];
            string resStr;

            //
            // test 1
            //
            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec1.Equals(resStr))
            {
                Fail("failing standard vector test 1" + SimpleTest.NewLine
                    + "    expected: " + resVec1 + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            //
            // test 2
            //
            byte[] bytes = Hex.Decode(testVec2);

            digest.BlockUpdate(bytes, 0, bytes.Length);

            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec2.Equals(resStr))
            {
                Fail("failing standard vector test 2" + SimpleTest.NewLine
                    + "    expected: " + resVec2 + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            //
            // test 3
            //
            bytes = Hex.Decode(testVec3);

            digest.BlockUpdate(bytes, 0, bytes.Length);

            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec3.Equals(resStr))
            {
                Fail("failing standard vector test 3" + SimpleTest.NewLine
                    + "    expected: " + resVec3 + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            //
            // test 4
            //
            bytes = Hex.Decode(testVec4);

            digest.BlockUpdate(bytes, 0, bytes.Length);

            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec4.Equals(resStr))
            {
                Fail("failing standard vector test 4" + SimpleTest.NewLine
                    + "    expected: " + resVec4 + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            //
            // test 5
            //
            bytes = Hex.Decode(testVec4);

            digest.BlockUpdate(bytes, 0, bytes.Length / 2);

            // clone the IDigest
            IDigest d = new Sha1Digest((Sha1Digest)digest);

            digest.BlockUpdate(bytes, bytes.Length / 2, bytes.Length - bytes.Length / 2);
            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec4.Equals(resStr))
            {
                Fail("failing standard vector test 5" + SimpleTest.NewLine
                    + "    expected: " + resVec4 + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            d.BlockUpdate(bytes, bytes.Length / 2, bytes.Length - bytes.Length / 2);
            d.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec4.Equals(resStr))
            {
                Fail("failing standard vector test 5" + SimpleTest.NewLine
                    + "    expected: " + resVec4 + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }
        }
Example #31
0
		/// <summary>
		/// Calculate the restore code for an authenticator. This is taken from the last 10 bytes of a digest of the serial and secret key,
		/// which is then specially encoded to alphanumerics.
		/// </summary>
		/// <returns>restore code for authenticator (always 10 chars)</returns>
		private string BuildRestoreCode()
		{
			// return if not set
			if (string.IsNullOrEmpty(Serial) == true || SecretKey == null)
			{
				return string.Empty;
			}

			// get byte array of serial
			byte[] serialdata = Encoding.UTF8.GetBytes(Serial.ToUpper().Replace("-", string.Empty));
			byte[] secretdata = SecretKey;

			// combine serial data and secret data
			byte[] combined = new byte[serialdata.Length + secretdata.Length];
			Array.Copy(serialdata, 0, combined, 0, serialdata.Length);
			Array.Copy(secretdata, 0, combined, serialdata.Length, secretdata.Length);

			// create digest of combined data
			IDigest digest = new Sha1Digest();
			digest.BlockUpdate(combined, 0, combined.Length);
			byte[] digestdata = new byte[digest.GetDigestSize()];
			digest.DoFinal(digestdata, 0);

			// take last 10 chars of hash and convert each byte to our encoded string that doesn't use I,L,O,S
			StringBuilder code = new StringBuilder();
			int startpos = digestdata.Length - 10;
			for (int i = 0; i < 10; i++)
			{
				code.Append(ConvertRestoreCodeByteToChar(digestdata[startpos + i]));
			}

			return code.ToString();
		}
Example #32
0
        internal override void ProcessBlock()
        {
            for (int i = 16; i < 80; i++)
            {
                uint num = this.X[i - 3] ^ this.X[i - 8] ^ this.X[i - 14] ^ this.X[i - 16];
                this.X[i] = (num << 1 | num >> 31);
            }
            uint num2 = this.H1;
            uint num3 = this.H2;
            uint num4 = this.H3;
            uint num5 = this.H4;
            uint num6 = this.H5;
            int  num7 = 0;

            for (int j = 0; j < 4; j++)
            {
                num6 += (num2 << 5 | num2 >> 27) + Sha1Digest.F(num3, num4, num5) + this.X[num7++] + 1518500249u;
                num3  = (num3 << 30 | num3 >> 2);
                num5 += (num6 << 5 | num6 >> 27) + Sha1Digest.F(num2, num3, num4) + this.X[num7++] + 1518500249u;
                num2  = (num2 << 30 | num2 >> 2);
                num4 += (num5 << 5 | num5 >> 27) + Sha1Digest.F(num6, num2, num3) + this.X[num7++] + 1518500249u;
                num6  = (num6 << 30 | num6 >> 2);
                num3 += (num4 << 5 | num4 >> 27) + Sha1Digest.F(num5, num6, num2) + this.X[num7++] + 1518500249u;
                num5  = (num5 << 30 | num5 >> 2);
                num2 += (num3 << 5 | num3 >> 27) + Sha1Digest.F(num4, num5, num6) + this.X[num7++] + 1518500249u;
                num4  = (num4 << 30 | num4 >> 2);
            }
            for (int k = 0; k < 4; k++)
            {
                num6 += (num2 << 5 | num2 >> 27) + Sha1Digest.H(num3, num4, num5) + this.X[num7++] + 1859775393u;
                num3  = (num3 << 30 | num3 >> 2);
                num5 += (num6 << 5 | num6 >> 27) + Sha1Digest.H(num2, num3, num4) + this.X[num7++] + 1859775393u;
                num2  = (num2 << 30 | num2 >> 2);
                num4 += (num5 << 5 | num5 >> 27) + Sha1Digest.H(num6, num2, num3) + this.X[num7++] + 1859775393u;
                num6  = (num6 << 30 | num6 >> 2);
                num3 += (num4 << 5 | num4 >> 27) + Sha1Digest.H(num5, num6, num2) + this.X[num7++] + 1859775393u;
                num5  = (num5 << 30 | num5 >> 2);
                num2 += (num3 << 5 | num3 >> 27) + Sha1Digest.H(num4, num5, num6) + this.X[num7++] + 1859775393u;
                num4  = (num4 << 30 | num4 >> 2);
            }
            for (int l = 0; l < 4; l++)
            {
                num6 += (num2 << 5 | num2 >> 27) + Sha1Digest.G(num3, num4, num5) + this.X[num7++] + 2400959708u;
                num3  = (num3 << 30 | num3 >> 2);
                num5 += (num6 << 5 | num6 >> 27) + Sha1Digest.G(num2, num3, num4) + this.X[num7++] + 2400959708u;
                num2  = (num2 << 30 | num2 >> 2);
                num4 += (num5 << 5 | num5 >> 27) + Sha1Digest.G(num6, num2, num3) + this.X[num7++] + 2400959708u;
                num6  = (num6 << 30 | num6 >> 2);
                num3 += (num4 << 5 | num4 >> 27) + Sha1Digest.G(num5, num6, num2) + this.X[num7++] + 2400959708u;
                num5  = (num5 << 30 | num5 >> 2);
                num2 += (num3 << 5 | num3 >> 27) + Sha1Digest.G(num4, num5, num6) + this.X[num7++] + 2400959708u;
                num4  = (num4 << 30 | num4 >> 2);
            }
            for (int m = 0; m < 4; m++)
            {
                num6 += (num2 << 5 | num2 >> 27) + Sha1Digest.H(num3, num4, num5) + this.X[num7++] + 3395469782u;
                num3  = (num3 << 30 | num3 >> 2);
                num5 += (num6 << 5 | num6 >> 27) + Sha1Digest.H(num2, num3, num4) + this.X[num7++] + 3395469782u;
                num2  = (num2 << 30 | num2 >> 2);
                num4 += (num5 << 5 | num5 >> 27) + Sha1Digest.H(num6, num2, num3) + this.X[num7++] + 3395469782u;
                num6  = (num6 << 30 | num6 >> 2);
                num3 += (num4 << 5 | num4 >> 27) + Sha1Digest.H(num5, num6, num2) + this.X[num7++] + 3395469782u;
                num5  = (num5 << 30 | num5 >> 2);
                num2 += (num3 << 5 | num3 >> 27) + Sha1Digest.H(num4, num5, num6) + this.X[num7++] + 3395469782u;
                num4  = (num4 << 30 | num4 >> 2);
            }
            this.H1  += num2;
            this.H2  += num3;
            this.H3  += num4;
            this.H4  += num5;
            this.H5  += num6;
            this.xOff = 0;
            Array.Clear(this.X, 0, 16);
        }
Example #33
0
		internal CombinedHash(CombinedHash t)
		{
			this.md5 = new MD5Digest(t.md5);
			this.sha1 = new Sha1Digest(t.sha1);
		}
		private DsaParameters GenerateParameters_FIPS186_2()
		{
            byte[] seed = new byte[20];
            byte[] part1 = new byte[20];
            byte[] part2 = new byte[20];
            byte[] u = new byte[20];
            Sha1Digest sha1 = new Sha1Digest();
			int n = (L - 1) / 160;
			byte[] w = new byte[L / 8];

			for (;;)
			{
				random.NextBytes(seed);

				Hash(sha1, seed, part1);
				Array.Copy(seed, 0, part2, 0, seed.Length);
				Inc(part2);
				Hash(sha1, part2, part2);

				for (int i = 0; i != u.Length; i++)
				{
					u[i] = (byte)(part1[i] ^ part2[i]);
				}

				u[0] |= (byte)0x80;
				u[19] |= (byte)0x01;

				BigInteger q = new BigInteger(1, u);

				if (!q.IsProbablePrime(certainty))
					continue;

				byte[] offset = Arrays.Clone(seed);
				Inc(offset);

				for (int counter = 0; counter < 4096; ++counter)
				{
					for (int k = 0; k < n; k++)
					{
						Inc(offset);
						Hash(sha1, offset, part1);
						Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
					}

					Inc(offset);
					Hash(sha1, offset, part1);
					Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);

					w[0] |= (byte)0x80;

					BigInteger x = new BigInteger(1, w);

					BigInteger c = x.Mod(q.ShiftLeft(1));

					BigInteger p = x.Subtract(c.Subtract(BigInteger.One));

					if (p.BitLength != L)
						continue;

					if (p.IsProbablePrime(certainty))
					{
						BigInteger g = CalculateGenerator_FIPS186_2(p, q, random);

						return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
					}
				}
			}
		}
Example #35
0
 /**
  * Copy constructor.  This will copy the state of the provided
  * message digest.
  */
 public Sha1Digest(Sha1Digest t)
     : base(t)
 {
     CopyIn(t);
 }
Example #36
0
        public override void Reset(IMemoable other)
        {
            Sha1Digest t = (Sha1Digest)other;

            this.CopyIn(t);
        }
Example #37
0
        // signature
        public static string CreateSignature(string email, string password, RsaKeyParameters key)
        {
            
            byte[] prefix = { 0x00 };
            var keyStruct = KeyToStruct(key);
            var toEncrypt = Encoding.UTF8.GetBytes(email + "\x00" + password);
            var cipher = new OaepEncoding(new RsaEngine(), new Sha1Digest(), null);
            cipher.Init(true, key);
            var encrypted = cipher.ProcessBlock(toEncrypt, 0, toEncrypt.Length);

            var digest = new Sha1Digest();
            var hash = new byte[digest.GetByteLength()];
            digest.BlockUpdate(keyStruct, 0, keyStruct.Length);
            digest.DoFinal(hash, 0);
            var hashExcerpt = hash.Take(4).ToArray();

            return DataTypeUtils.UrlSafeBase64(DataTypeUtils.CombineBytes(prefix, hashExcerpt, encrypted));
        }
Example #38
0
        public static byte[] Digest(byte[] data, String algo)
        {
            if (algo == null)
            {
                throw new ArgumentNullException("El algoritmo de huella digital no puede ser nulo");
            }
            if (data == null)
            {
                throw new ArgumentNullException("Los datos no pueden ser nulos");
            }

            switch (algo)
            {
                /**
                 * ALGORITMOS DE HASING
                 */
                case AOSignConstants.SIGN_ALGORITHM_SHA1:
                    {
                        Sha1Digest dig = new Sha1Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_SHA256:
                    {
                        Sha256Digest dig = new Sha256Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_SHA384:
                    {
                        Sha384Digest dig = new Sha384Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_SHA512:
                    {
                        Sha512Digest dig = new Sha512Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_RIPEMD160:
                    {
                        RipeMD160Digest dig = new RipeMD160Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }
                case AOSignConstants.SIGN_ALGORITHM_MD5:
                    {
                        MD5Digest dig = new MD5Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_MD2:
                    {
                        MD2Digest dig = new MD2Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                default:
                    // You can use the default case.
                    throw new ArgumentNullException("El algoritmo no es reconocido");
            }

            throw new ArgumentNullException("Algoritmo de hash no soportado: " + algo);
        }
Example #39
0
 public Sha1Digest(Sha1Digest t) : base(t)
 {
     this.X = new uint[80];
     this.CopyIn(t);
 }