GetDigestSize() public method

public GetDigestSize ( ) : int
return int
コード例 #1
0
 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;
 }
コード例 #2
0
ファイル: HashProviders.cs プロジェクト: chaoscode/SteamSharp
 /// <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;
 }
コード例 #3
0
        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);
        }
コード例 #4
0
ファイル: MATEncryption.cs プロジェクト: erosh/sdk-release
 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);
 }
コード例 #5
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;
        }
コード例 #6
0
        /**
         *
         * 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);
        }
コード例 #7
0
        /**
         * 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);
        }
コード例 #8
0
ファイル: Hybi13Handler.cs プロジェクト: JoschaMetze/Fleck
        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);
        }
コード例 #9
0
ファイル: ISO9796Test.cs プロジェクト: KimikoMuffin/bc-csharp
        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");
                }
            }
        }
コード例 #10
0
ファイル: HKDFGeneratorTest.cs プロジェクト: bcgit/bc-csharp
        public override void PerformTest()
        {
            {
                // === A.1. Test Case 1 - Basic test case with SHA-256 ===

                IDigest hash = new Sha256Digest();
                byte[] ikm = Hex.Decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
                byte[] salt = Hex.Decode("000102030405060708090a0b0c");
                byte[] info = Hex.Decode("f0f1f2f3f4f5f6f7f8f9");
                int l = 42;
                byte[] okm = new byte[l];

                HkdfParameters parameters = new HkdfParameters(ikm, salt, info);

                HkdfBytesGenerator hkdf = new HkdfBytesGenerator(hash);
                hkdf.Init(parameters);
                hkdf.GenerateBytes(okm, 0, l);

                CompareOkm(1, okm, Hex.Decode(
                    "3cb25f25faacd57a90434f64d0362f2a" +
                    "2d2d0a90cf1a5a4c5db02d56ecc4c5bf" +
                    "34007208d5b887185865"));
            }

            // === A.2. Test Case 2 - Test with SHA-256 and longer inputs/outputs
            // ===
            {
                IDigest hash = new Sha256Digest();
                byte[] ikm = Hex.Decode("000102030405060708090a0b0c0d0e0f"
                    + "101112131415161718191a1b1c1d1e1f"
                    + "202122232425262728292a2b2c2d2e2f"
                    + "303132333435363738393a3b3c3d3e3f"
                    + "404142434445464748494a4b4c4d4e4f");
                byte[] salt = Hex.Decode("606162636465666768696a6b6c6d6e6f"
                    + "707172737475767778797a7b7c7d7e7f"
                    + "808182838485868788898a8b8c8d8e8f"
                    + "909192939495969798999a9b9c9d9e9f"
                    + "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf");
                byte[] info = Hex.Decode("b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
                    + "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
                    + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
                    + "e0e1e2e3e4e5e6e7e8e9eaebecedeeef"
                    + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff");
                int l = 82;
                byte[] okm = new byte[l];

                HkdfParameters parameters = new HkdfParameters(ikm, salt, info);

                HkdfBytesGenerator hkdf = new HkdfBytesGenerator(hash);
                hkdf.Init(parameters);
                hkdf.GenerateBytes(okm, 0, l);

                CompareOkm(2, okm, Hex.Decode(
                    "b11e398dc80327a1c8e7f78c596a4934" +
                    "4f012eda2d4efad8a050cc4c19afa97c" +
                    "59045a99cac7827271cb41c65e590e09" +
                    "da3275600c2f09b8367793a9aca3db71" +
                    "cc30c58179ec3e87c14c01d5c1f3434f" +
                    "1d87"));
            }

            {
                // === A.3. Test Case 3 - Test with SHA-256 and zero-length
                // salt/info ===

                // setting salt to an empty byte array means that the salt is set to
                // HashLen zero valued bytes
                // setting info to null generates an empty byte array as info
                // structure

                IDigest hash = new Sha256Digest();
                byte[] ikm = Hex.Decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
                byte[] salt = new byte[0];
                byte[] info = null;
                int l = 42;
                byte[] okm = new byte[l];

                HkdfParameters parameters = new HkdfParameters(ikm, salt, info);

                HkdfBytesGenerator hkdf = new HkdfBytesGenerator(hash);
                hkdf.Init(parameters);
                hkdf.GenerateBytes(okm, 0, l);

                CompareOkm(3, okm, Hex.Decode(
                    "8da4e775a563c18f715f802a063c5a31" +
                    "b8a11f5c5ee1879ec3454e5f3c738d2d" +
                    "9d201395faa4b61a96c8"));
            }

            {
                // === A.4. Test Case 4 - Basic test case with SHA-1 ===

                IDigest hash = new Sha1Digest();
                byte[] ikm = Hex.Decode("0b0b0b0b0b0b0b0b0b0b0b");
                byte[] salt = Hex.Decode("000102030405060708090a0b0c");
                byte[] info = Hex.Decode("f0f1f2f3f4f5f6f7f8f9");
                int l = 42;
                byte[] okm = new byte[l];

                HkdfParameters parameters = new HkdfParameters(ikm, salt, info);

                HkdfBytesGenerator hkdf = new HkdfBytesGenerator(hash);
                hkdf.Init(parameters);
                hkdf.GenerateBytes(okm, 0, l);

                CompareOkm(4, okm, Hex.Decode(
                    "085a01ea1b10f36933068b56efa5ad81" +
                        "a4f14b822f5b091568a9cdd4f155fda2" +
                        "c22e422478d305f3f896"));
            }

            // === A.5. Test Case 5 - Test with SHA-1 and longer inputs/outputs ===
            {
                IDigest hash = new Sha1Digest();
                byte[] ikm = Hex.Decode("000102030405060708090a0b0c0d0e0f"
                    + "101112131415161718191a1b1c1d1e1f"
                    + "202122232425262728292a2b2c2d2e2f"
                    + "303132333435363738393a3b3c3d3e3f"
                    + "404142434445464748494a4b4c4d4e4f");
                byte[] salt = Hex.Decode("606162636465666768696a6b6c6d6e6f"
                    + "707172737475767778797a7b7c7d7e7f"
                    + "808182838485868788898a8b8c8d8e8f"
                    + "909192939495969798999a9b9c9d9e9f"
                    + "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf");
                byte[] info = Hex.Decode("b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
                    + "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
                    + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
                    + "e0e1e2e3e4e5e6e7e8e9eaebecedeeef"
                    + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff");
                int l = 82;
                byte[] okm = new byte[l];

                HkdfParameters parameters = new HkdfParameters(ikm, salt, info);

                HkdfBytesGenerator hkdf = new HkdfBytesGenerator(hash);
                hkdf.Init(parameters);
                hkdf.GenerateBytes(okm, 0, l);

                CompareOkm(5, okm, Hex.Decode(
                    "0bd770a74d1160f7c9f12cd5912a06eb" +
                    "ff6adcae899d92191fe4305673ba2ffe" +
                    "8fa3f1a4e5ad79f3f334b3b202b2173c" +
                    "486ea37ce3d397ed034c7f9dfeb15c5e" +
                    "927336d0441f4c4300e2cff0d0900b52" +
                    "d3b4"));
            }

            {
                // === A.6. Test Case 6 - Test with SHA-1 and zero-length salt/info
                // ===

                // setting salt to null should generate a new salt of HashLen zero
                // valued bytes

                IDigest hash = new Sha1Digest();
                byte[] ikm = Hex.Decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
                byte[] salt = null;
                byte[] info = new byte[0];
                int l = 42;
                byte[] okm = new byte[l];

                HkdfParameters parameters = new HkdfParameters(ikm, salt, info);

                HkdfBytesGenerator hkdf = new HkdfBytesGenerator(hash);
                hkdf.Init(parameters);
                hkdf.GenerateBytes(okm, 0, l);

                CompareOkm(6, okm, Hex.Decode(
                    "0ac1af7002b3d761d1e55298da9d0506" +
                    "b9ae52057220a306e07b6b87e8df21d0" +
                    "ea00033de03984d34918"));
            }

            {
                // === A.7. Test Case 7 - Test with SHA-1, salt not provided,
                // zero-length info ===
                // (salt defaults to HashLen zero octets)

                // this test is identical to test 6 in all ways bar the IKM value

                IDigest hash = new Sha1Digest();
                byte[] ikm = Hex.Decode("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c");
                byte[] salt = null;
                byte[] info = new byte[0];
                int l = 42;
                byte[] okm = new byte[l];

                HkdfParameters parameters = new HkdfParameters(ikm, salt, info);

                HkdfBytesGenerator hkdf = new HkdfBytesGenerator(hash);
                hkdf.Init(parameters);
                hkdf.GenerateBytes(okm, 0, l);

                CompareOkm(7, okm, Hex.Decode(
                    "2c91117204d745f3500d636a62f64f0a" +
                    "b3bae548aa53d423b0d1f27ebba6f5e5" +
                    "673a081d70cce7acfc48"));
            }

            {
                // === A.101. Additional Test Case - Test with SHA-1, skipping extract
                // zero-length info ===
                // (salt defaults to HashLen zero octets)

                // this test is identical to test 7 in all ways bar the IKM value
                // which is set to the PRK value

                IDigest hash = new Sha1Digest();
                byte[] ikm = Hex.Decode("2adccada18779e7c2077ad2eb19d3f3e731385dd");
                byte[] info = new byte[0];
                int l = 42;
                byte[] okm = new byte[l];

                HkdfParameters parameters = HkdfParameters.SkipExtractParameters(ikm, info);

                HkdfBytesGenerator hkdf = new HkdfBytesGenerator(hash);
                hkdf.Init(parameters);
                hkdf.GenerateBytes(okm, 0, l);

                CompareOkm(101, okm, Hex.Decode(
                    "2c91117204d745f3500d636a62f64f0a" +
                    "b3bae548aa53d423b0d1f27ebba6f5e5" +
                    "673a081d70cce7acfc48"));
            }

            {
                // === A.102. Additional Test Case - Test with SHA-1, maximum output ===
                // (salt defaults to HashLen zero octets)

                // this test is identical to test 7 in all ways bar the IKM value

                IDigest hash = new Sha1Digest();
                byte[] ikm = Hex.Decode("2adccada18779e7c2077ad2eb19d3f3e731385dd");
                byte[] info = new byte[0];
                int l = 255 * hash.GetDigestSize();
                byte[] okm = new byte[l];

                HkdfParameters parameters = HkdfParameters.SkipExtractParameters(ikm, info);

                HkdfBytesGenerator hkdf = new HkdfBytesGenerator(hash);
                hkdf.Init(parameters);
                hkdf.GenerateBytes(okm, 0, l);

                int zeros = 0;
                for (int i = 0; i < hash.GetDigestSize(); i++)
                {
                    if (okm[i] == 0)
                    {
                        zeros++;
                    }
                }

                if (zeros == hash.GetDigestSize())
                {
                    Fail("HKDF failed generator test " + 102);
                }
            }
        }
コード例 #11
0
		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;
		}
コード例 #12
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);
            }
        }
コード例 #13
0
ファイル: Authenticator.cs プロジェクト: kgdyinpv/WinAuth7
		/// <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();
		}
コード例 #14
0
		private byte[] SignDsa(byte[] buffer, int length)
		{
			var signer = new DsaSigner();
			signer.Init(true, new ParametersWithRandom(PrivateKeyFactory.CreateKey(PrivateKey), _secureRandom));

			var sha1 = new Sha1Digest();

			sha1.BlockUpdate(buffer, 0, length);
			byte[] hash = new byte[sha1.GetDigestSize()];
			sha1.DoFinal(hash, 0);

			var signature = signer.GenerateSignature(hash);

			byte[] res = new byte[41];

			res[0] = PublicKey[0];

			signature[0].ToByteArrayUnsigned().CopyTo(res, 1);
			signature[1].ToByteArrayUnsigned().CopyTo(res, 21);

			return res;
		}
コード例 #15
0
ファイル: PasswordHashMethod.cs プロジェクト: hellyhe/pgina
        public override string hash(string pw)
        {
            Sha1Digest digest = new Sha1Digest();

            // 8 byte random salt
            byte[] salt = randomSalt(8);

            // Generate the hash of the password + salt
            byte[] password = Encoding.UTF8.GetBytes(pw);
            digest.BlockUpdate(password, 0, password.Length);
            digest.BlockUpdate(salt, 0, salt.Length);
            int digestSize = digest.GetDigestSize();
            byte[] hashData = new byte[digestSize];
            digest.DoFinal(hashData, 0);

            // Put the salt on the end of the hashed password + salt
            byte[] result = new byte[hashData.Length + salt.Length];
            hashData.CopyTo(result, 0);
            salt.CopyTo(result, hashData.Length);

            // Return in base 64
            return "{SSHA}" + Convert.ToBase64String(result);
        }
コード例 #16
0
ファイル: PasswordHashMethod.cs プロジェクト: hellyhe/pgina
        public override string hash(string pw)
        {
            Sha1Digest digest = new Sha1Digest();

            byte[] password = Encoding.UTF8.GetBytes(pw);
            digest.BlockUpdate(password, 0, password.Length);
            int digestSize = digest.GetDigestSize();
            byte[] hashData = new byte[digestSize];
            digest.DoFinal(hashData, 0);

            return "{SHA}" + Convert.ToBase64String(hashData);
        }
コード例 #17
0
ファイル: ISO9796Test.cs プロジェクト: KimikoMuffin/bc-csharp
        public virtual void DoTest11()
        {
            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 - PSS Signing
            //
            IDigest              dig = new Sha1Digest();
            Iso9796d2PssSigner  eng = new Iso9796d2PssSigner(rsa, dig, dig.GetDigestSize());

            //
            // 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 11");
            }

            eng.Init(false, pubParameters);

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

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

            eng.Init(false, pubParameters);

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

            if (!eng.VerifySignature(data))
            {
                Fail("failed ISO9796-2 verify Test 11");
            }
        }
コード例 #18
0
		private bool VerifyDsa(byte[] buffer, int length, byte[] signature)
		{
			int numberSize = 64 + PublicKey[0] * 8;

			DsaPublicKeyParameters parameters = new DsaPublicKeyParameters(
				new BigInteger(1, PublicKey, 21 + 2 * numberSize, numberSize),
				new DsaParameters(
					new BigInteger(1, PublicKey, 21, numberSize),
					new BigInteger(1, PublicKey, 1, 20),
					new BigInteger(1, PublicKey, 21 + numberSize, numberSize))
				);

			var dsa = new DsaSigner();
			dsa.Init(false, parameters);

			var sha1 = new Sha1Digest();

			sha1.BlockUpdate(buffer, 0, length);
			byte[] hash = new byte[sha1.GetDigestSize()];
			sha1.DoFinal(hash, 0);

			return dsa.VerifySignature(hash, new BigInteger(1, signature, 1, 20), new BigInteger(1, signature, 21, 20));
		}
コード例 #19
0
ファイル: Program.cs プロジェクト: modulexcite/jxmgr
        static void Main(string[] args)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var title = (AssemblyTitleAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyTitleAttribute));
            Console.WriteLine("{0} version {1}", title.Title, assembly.GetName().Version);
            var copyright = (AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyCopyrightAttribute));
            Console.WriteLine(copyright.Copyright);
            Console.WriteLine("More information can be found at https://Jexus.codeplex.com");
            Console.WriteLine();

            var baseAddress = args.Length > 0 ? args[0] : "https://*****:*****@"Remote services must be run as root on Linux.");
                    return;
                }

                if (!File.Exists("jws"))
                {
                    Console.WriteLine(@"Remote services must be running in Jexus installation folder.");
                    return;
                }

                var loc = baseAddress.LastIndexOf(':');
                var port = "443";
                if (loc != -1)
                {
                    port = baseAddress.Substring(loc + 1);
                }

                string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string path = Path.Combine(dirname, ".mono", "httplistener");
                if (false == Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                string target_cert = Path.Combine(path, string.Format("{0}.cer", port));
                if (File.Exists(target_cert))
                {
                    Console.WriteLine("Use {0}", target_cert);
                }
                else
                {
                    Console.WriteLine("Generating a self-signed certificate for Jexus Manager");

                    // Generate certificate
                    string defaultIssuer = "CN=jexus.lextudio.com";
                    string defaultSubject = "CN=jexus.lextudio.com";
                    byte[] sn = Guid.NewGuid().ToByteArray();
                    string subject = defaultSubject;
                    string issuer = defaultIssuer;
                    DateTime notBefore = DateTime.Now;
                    DateTime notAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z

                    RSA issuerKey = new RSACryptoServiceProvider(2048);
                    RSA subjectKey = null;

                    bool selfSigned = true;
                    string hashName = "SHA1";

                    CspParameters subjectParams = new CspParameters();
                    CspParameters issuerParams = new CspParameters();
                    BasicConstraintsExtension bce = new BasicConstraintsExtension
                    {
                        PathLenConstraint = BasicConstraintsExtension.NoPathLengthConstraint,
                        CertificateAuthority = true
                    };
                    ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension();
                    eku.KeyPurpose.Add("1.3.6.1.5.5.7.3.1");                    
                    SubjectAltNameExtension alt = null;
                    string p12file = Path.Combine(path, "temp.pfx");
                    string p12pwd = "test";

                    // serial number MUST be positive
                    if ((sn[0] & 0x80) == 0x80)
                        sn[0] -= 0x80;

                    if (selfSigned)
                    {
                        if (subject != defaultSubject)
                        {
                            issuer = subject;
                            issuerKey = subjectKey;
                        }
                        else
                        {
                            subject = issuer;
                            subjectKey = issuerKey;
                        }
                    }

                    if (subject == null)
                        throw new Exception("Missing Subject Name");

                    X509CertificateBuilder cb = new X509CertificateBuilder(3);
                    cb.SerialNumber = sn;
                    cb.IssuerName = issuer;
                    cb.NotBefore = notBefore;
                    cb.NotAfter = notAfter;
                    cb.SubjectName = subject;
                    cb.SubjectPublicKey = subjectKey;
                    // extensions
                    if (bce != null)
                        cb.Extensions.Add(bce);
                    if (eku != null)
                        cb.Extensions.Add(eku);
                    if (alt != null)
                        cb.Extensions.Add(alt);

                    IDigest digest = new Sha1Digest();
                    byte[] resBuf = new byte[digest.GetDigestSize()];
                    var spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.GetRsaPublicKey(issuerKey));                    
                    byte[] bytes = spki.PublicKeyData.GetBytes();
                    digest.BlockUpdate(bytes, 0, bytes.Length);
                    digest.DoFinal(resBuf, 0);

                    cb.Extensions.Add(new SubjectKeyIdentifierExtension { Identifier = resBuf });
                    cb.Extensions.Add(new AuthorityKeyIdentifierExtension { Identifier = resBuf });
                    // signature
                    cb.Hash = hashName;
                    byte[] rawcert = cb.Sign(issuerKey);

                    PKCS12 p12 = new PKCS12();
                    p12.Password = p12pwd;

                    ArrayList list = new ArrayList();
                    // we use a fixed array to avoid endianess issues 
                    // (in case some tools requires the ID to be 1).
                    list.Add(new byte[4] { 1, 0, 0, 0 });
                    Hashtable attributes = new Hashtable(1);
                    attributes.Add(PKCS9.localKeyId, list);

                    p12.AddCertificate(new Mono.Security.X509.X509Certificate(rawcert), attributes);
                    p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes);
                    p12.SaveToFile(p12file);

                    var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(p12file, p12pwd, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);

                    // Install certificate
                    string target_pvk = Path.Combine(path, string.Format("{0}.pvk", port));

                    using (Stream cer = File.OpenWrite(target_cert))
                    {
                        byte[] raw = x509.RawData;
                        cer.Write(raw, 0, raw.Length);
                    }

                    PrivateKey pvk = new PrivateKey();
                    pvk.RSA = subjectKey;
                    pvk.Save(target_pvk);
                }
            }

            JexusServer.Credentials = args.Length > 2 ? args[1] + "|" + args[2] : "jexus|lextudio.com";
            JexusServer.Timeout = args.Length > 3 ? double.Parse(args[3]) : 30D;

            using (WebApp.Start<Startup>(url: baseAddress))
            {
                Console.WriteLine("Remote services have started at {0}.", baseAddress);
                Console.WriteLine("Credentials is {0}", JexusServer.Credentials);
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
コード例 #20
0
		public static ISigner GetSigner(
			string algorithm)
        {
			if (algorithm == null)
				throw new ArgumentNullException("algorithm");

			algorithm = algorithm.ToUpper(CultureInfo.InvariantCulture);

			string mechanism = (string) algorithms[algorithm];

			if (mechanism == null)
				mechanism = algorithm;

			if (mechanism.Equals("RSA"))
			{
				return (new RsaDigestSigner(new NullDigest()));
			}
			if (mechanism.Equals("MD2withRSA"))
            {
                return (new RsaDigestSigner(new MD2Digest()));
            }
            if (mechanism.Equals("MD4withRSA"))
            {
                return (new RsaDigestSigner(new MD4Digest()));
            }
            if (mechanism.Equals("MD5withRSA"))
            {
                return (new RsaDigestSigner(new MD5Digest()));
            }
            if (mechanism.Equals("SHA-1withRSA"))
            {
                return (new RsaDigestSigner(new Sha1Digest()));
            }
            if (mechanism.Equals("SHA-224withRSA"))
            {
                return (new RsaDigestSigner(new Sha224Digest()));
            }
            if (mechanism.Equals("SHA-256withRSA"))
            {
                return (new RsaDigestSigner(new Sha256Digest()));
            }
            if (mechanism.Equals("SHA-384withRSA"))
            {
                return (new RsaDigestSigner(new Sha384Digest()));
            }
            if (mechanism.Equals("SHA-512withRSA"))
            {
                return (new RsaDigestSigner(new Sha512Digest()));
            }
			if (mechanism.Equals("RIPEMD128withRSA"))
            {
                return (new RsaDigestSigner(new RipeMD128Digest()));
            }
            if (mechanism.Equals("RIPEMD160withRSA"))
            {
                return (new RsaDigestSigner(new RipeMD160Digest()));
            }
            if (mechanism.Equals("RIPEMD256withRSA"))
            {
                return (new RsaDigestSigner(new RipeMD256Digest()));
            }

			if (mechanism.Equals("RAWRSASSA-PSS"))
			{
				// TODO Add support for other parameter settings
				IDigest contentDigest = new NullDigest();
				IDigest mgfDigest = new Sha1Digest();
				int saltLen = mgfDigest.GetDigestSize();
				return (new PssSigner(new RsaBlindedEngine(), contentDigest, mgfDigest, saltLen, PssSigner.TrailerImplicit));
			}
			if (mechanism.Equals("PSSwithRSA"))
			{
				// TODO The Sha1Digest here is a default. In JCE version, the actual digest
				// to be used can be overridden by subsequent parameter settings.
				return (new PssSigner(new RsaBlindedEngine(), new Sha1Digest()));
			}
			if (mechanism.Equals("SHA-1withRSAandMGF1"))
			{
				return (new PssSigner(new RsaBlindedEngine(), new Sha1Digest()));
			}
			if (mechanism.Equals("SHA-224withRSAandMGF1"))
			{
				return (new PssSigner(new RsaBlindedEngine(), new Sha224Digest()));
			}
			if (mechanism.Equals("SHA-256withRSAandMGF1"))
			{
				return (new PssSigner(new RsaBlindedEngine(), new Sha256Digest()));
			}
			if (mechanism.Equals("SHA-384withRSAandMGF1"))
			{
				return (new PssSigner(new RsaBlindedEngine(), new Sha384Digest()));
			}
			if (mechanism.Equals("SHA-512withRSAandMGF1"))
			{
				return (new PssSigner(new RsaBlindedEngine(), new Sha512Digest()));
			}

			if (mechanism.Equals("NONEwithDSA"))
			{
				return (new DsaDigestSigner(new DsaSigner(), new NullDigest()));
			}
			if (mechanism.Equals("SHA-1withDSA"))
            {
                return (new DsaDigestSigner(new DsaSigner(), new Sha1Digest()));
            }
			if (mechanism.Equals("SHA-224withDSA"))
			{
				return (new DsaDigestSigner(new DsaSigner(), new Sha224Digest()));
			}
			if (mechanism.Equals("SHA-256withDSA"))
			{
				return (new DsaDigestSigner(new DsaSigner(), new Sha256Digest()));
			}
			if (mechanism.Equals("SHA-384withDSA"))
			{
				return (new DsaDigestSigner(new DsaSigner(), new Sha384Digest()));
			}
			if (mechanism.Equals("SHA-512withDSA"))
			{
				return (new DsaDigestSigner(new DsaSigner(), new Sha512Digest()));
			}

			if (mechanism.Equals("NONEwithECDSA"))
			{
				return (new DsaDigestSigner(new ECDsaSigner(), new NullDigest()));
			}
			if (mechanism.Equals("SHA-1withECDSA"))
            {
                return (new DsaDigestSigner(new ECDsaSigner(), new Sha1Digest()));
            }
			if (mechanism.Equals("SHA-224withECDSA"))
			{
				return (new DsaDigestSigner(new ECDsaSigner(), new Sha224Digest()));
			}
			if (mechanism.Equals("SHA-256withECDSA"))
			{
				return (new DsaDigestSigner(new ECDsaSigner(), new Sha256Digest()));
			}
			if (mechanism.Equals("SHA-384withECDSA"))
			{
				return (new DsaDigestSigner(new ECDsaSigner(), new Sha384Digest()));
			}
			if (mechanism.Equals("SHA-512withECDSA"))
			{
				return (new DsaDigestSigner(new ECDsaSigner(), new Sha512Digest()));
			}

			if (mechanism.Equals("RIPEMD160withECDSA"))
			{
				return (new DsaDigestSigner(new ECDsaSigner(), new RipeMD160Digest()));
			}

			if (mechanism.Equals("SHA1WITHECNR"))
			{
				return (new DsaDigestSigner(new ECNRSigner(), new Sha1Digest()));
			}
			if (mechanism.Equals("SHA224WITHECNR"))
			{
				return (new DsaDigestSigner(new ECNRSigner(), new Sha224Digest()));
			}
			if (mechanism.Equals("SHA256WITHECNR"))
			{
				return (new DsaDigestSigner(new ECNRSigner(), new Sha256Digest()));
			}
			if (mechanism.Equals("SHA384WITHECNR"))
			{
				return (new DsaDigestSigner(new ECNRSigner(), new Sha384Digest()));
			}
			if (mechanism.Equals("SHA512WITHECNR"))
			{
				return (new DsaDigestSigner(new ECNRSigner(), new Sha512Digest()));
			}

			if (mechanism.Equals("GOST3410"))
			{
				return new Gost3410DigestSigner(new Gost3410Signer(), new Gost3411Digest());
			}
			if (mechanism.Equals("ECGOST3410"))
			{
				return new Gost3410DigestSigner(new ECGost3410Signer(), new Gost3411Digest());
			}

			if (mechanism.Equals("SHA1WITHRSA/ISO9796-2"))
			{
				return new Iso9796d2Signer(new RsaBlindedEngine(), new Sha1Digest(), true);
			}
			if (mechanism.Equals("MD5WITHRSA/ISO9796-2"))
			{
				return new Iso9796d2Signer(new RsaBlindedEngine(), new MD5Digest(), true);
			}
			if (mechanism.Equals("RIPEMD160WITHRSA/ISO9796-2"))
			{
				return new Iso9796d2Signer(new RsaBlindedEngine(), new RipeMD160Digest(), true);
			}

			throw new SecurityUtilityException("Signer " + algorithm + " not recognised.");
        }
コード例 #21
0
ファイル: Digester.cs プロジェクト: bibou1324/clienteafirma
        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);
        }
コード例 #22
0
ファイル: Utility.cs プロジェクト: jbtule/keyczar-dotnet
        /// <summary>
        /// Hashes each component of the key hash with it's length first.
        /// </summary>
        /// <param name="size">The size.</param>
        /// <param name="components">The components.</param>
        /// <returns></returns>
        public static byte[] HashKeyLengthPrefix(int size, params byte[][] components)
        {
            var sha1 = new Sha1Digest();

            foreach (var data in components)
            {
                byte[] length = GetBytes(data.Length);
                sha1.BlockUpdate(length, 0, length.Length);
                sha1.BlockUpdate(data, 0, data.Length);
            }
            var hash = new byte[sha1.GetDigestSize()];
            sha1.DoFinal(hash, 0);
            sha1.Reset();
            var outBytes = new byte[size];
            Array.Copy(hash, 0, outBytes, 0, outBytes.Length);
            return outBytes;
        }