GetDigestSize() public method

public GetDigestSize ( ) : int
return int
Example #1
0
    private static string GetHashDigest(Org.BouncyCastle.Crypto.Digests.Sha256Digest hash)
    {
        var digest = new byte[hash.GetDigestSize()];

        hash.DoFinal(digest, 0);
        return(BitConverter.ToString(digest).Replace("-", string.Empty).ToLower());
    }
 /**
  * Hashes the given data.
  *
  * @param data The data to hash
  * @return byte-array containing the hashed data
  */
 public static byte[] Hash(byte[] data)
 {
     Sha256Digest sha256 = new Sha256Digest();
     sha256.BlockUpdate(data, 0, data.Length);
     byte[] hash = new byte[sha256.GetDigestSize()];
     sha256.DoFinal(hash, 0);
     return hash;
 }
Example #3
0
		public static byte[] SHA256Hash(byte[] data)
		{
			var shaHash = new Sha256Digest ();
			shaHash.BlockUpdate (data, 0, data.Length);
			byte[] hashedValue = new byte[shaHash.GetDigestSize ()];
			shaHash.DoFinal(hashedValue, 0);
			return hashedValue;
		}
Example #4
0
 public static string Sha256(string input)
 {
     var data = System.Text.Encoding.UTF8.GetBytes(input);
     Sha256Digest hash = new Sha256Digest();
     hash.BlockUpdate(data, 0, data.Length);
     byte[] result = new byte[hash.GetDigestSize()];
     hash.DoFinal(result, 0);
     return Hex.ToHexString(result);
 }
Example #5
0
        public static byte[] Array(byte[] value)
        {
            var digest = new Sha256Digest();
            digest.BlockUpdate(value, 0, value.Length);

            var ret = new byte[digest.GetDigestSize()];
            digest.DoFinal(ret, 0);
            return ret;
        }
Example #6
0
        public static String SHA256(string tosha256)
        {
            Sha256Digest digest = new Sha256Digest();
            byte[] scratch = new byte[digest.GetDigestSize()];
            digest.BlockUpdate(UTF8Encoding.UTF8.GetBytes(tosha256), 0, UTF8Encoding.UTF8.GetByteCount(tosha256));
            digest.DoFinal(scratch, 0);

            string hex = BitConverter.ToString(scratch).ToLower();
            return hex.Replace("-", "");
        }
Example #7
0
        public static byte[] Sha256(string text)
        {
            var bytes = new byte[text.Length * sizeof(char)];
            Buffer.BlockCopy(text.ToCharArray(), 0, bytes, 0, bytes.Length);

            var sha256 = new Sha256Digest();
            var hash = new byte[sha256.GetDigestSize()];
            sha256.BlockUpdate(bytes, 0, bytes.Length);
            sha256.DoFinal(hash, 0);
            return hash;
        }
Example #8
0
 private static string GetFileName(string imageUri)
 {
     var sha = new Sha256Digest();
     var stream = new DigestStream(new MemoryStream(), null, sha);
     using (var writer = new StreamWriter(stream))
     {
         writer.Write(imageUri);
     }
     byte[] buffer = new byte[sha.GetDigestSize()];
     sha.DoFinal(buffer, 0);
     string hex = BitConverter.ToString(buffer);
     string fileName = hex.Replace("-", "");
     return fileName;
 }
    public string GetSign(byte[] msg)
    {
        //Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(Convert.FromBase64String(privKey));
        byte[] prvB = StringToByteArray(prv);
        byte[] pubB = StringToByteArray(pub);
        //byte[] prvB = StringToByteArray(prvTmp);
        //byte[] pubB = StringToByteArray(pubTmp);
        Org.BouncyCastle.Math.BigInteger sk = new Org.BouncyCastle.Math.BigInteger(+1, prvB);
        Org.BouncyCastle.Math.EC.ECPoint q  = domain.G.Multiply(sk);

        byte[]     pubKeyX = q.Normalize().AffineXCoord.GetEncoded();
        byte[]     pubKeyY = q.Normalize().AffineYCoord.GetEncoded();
        BigInteger k       = GenerateRandom();

        //BigInteger k = new BigInteger(+1,StringToByteArray("015B931D9C7BF3A7A70E57868BF29712377E74355FC59032CD7547C80E179010"));
        //Debug.Log("kv:" + BitConverter.ToString(kv.ToByteArray()).Replace("-", ""));
        Debug.Log("K:" + BitConverter.ToString(k.ToByteArray()).Replace("-", ""));
        ECPoint Q = domain.G.Multiply(k);

        Org.BouncyCastle.Crypto.Digests.Sha256Digest digester = new Org.BouncyCastle.Crypto.Digests.Sha256Digest();
        byte[] h = new byte[digester.GetDigestSize()];

        digester.BlockUpdate(Q.GetEncoded(true), 0, Q.GetEncoded(true).Length);
        digester.BlockUpdate(pubB, 0, pubB.Length);
        digester.BlockUpdate(msg, 0, msg.Length);

        digester.DoFinal(h, 0);

        Org.BouncyCastle.Math.BigInteger r = new Org.BouncyCastle.Math.BigInteger(+1, h);

        BigInteger s = r.Multiply(sk);

        s = k.Subtract(s);
        s = s.Mod(domain.n);
        string rt = BitConverter.ToString(r.ToByteArray()).Replace("-", "");

        if (rt.Length > 32)
        {
            rt = rt.Remove(0, 2);
        }
        string st = BitConverter.ToString(s.ToByteArray()).Replace("-", "");

        return(rt + st);
    }
Example #10
0
		/// <summary>
		/// From a single given key create a hashname with the intermediate hashes of other keys
		/// </summary>
		/// <returns>The key.</returns>
		/// <param name="csid">The identifier for the cipher set as a string.</param>
		/// <param name="keyData">The key data for the given csid.</param>
		/// <param name="intermediates">Intermediates.</param>
		public static string FromKey(string csid, byte[] keyData, IDictionary<string, string> intermediates)
		{
			Sha256Digest digest = new Sha256Digest ();
			List<string> keys = new List<string>(intermediates.Keys);
			keys.Add (csid);
			keys.Sort ();

			int digestSize = digest.GetDigestSize ();
			byte[] outhash = null;
			foreach (var key in keys) {
				if (outhash != null) {
					digest.BlockUpdate (outhash, 0, digestSize);
				} else {
					outhash = new byte[digestSize];
				}
				byte inByte;
				try {
					inByte = Convert.ToByte (key, 16);
				} catch(FormatException) {
					return null;
				} catch(OverflowException) {
					return null;
				} catch (ArgumentException) {
					return null;
				}
				digest.Update (inByte);
				digest.DoFinal (outhash, 0);
				digest.Reset ();

				digest.BlockUpdate (outhash, 0, digestSize);
				if (key == csid) {
					Sha256Digest keyDigest = new Sha256Digest ();
					keyDigest.BlockUpdate (keyData, 0, keyData.Length);
					keyDigest.DoFinal (outhash, 0);
					digest.BlockUpdate (outhash, 0, outhash.Length);
				} else {
					byte[] keyIntermediate = Base32Encoder.Decode (intermediates [key]);
					digest.BlockUpdate (keyIntermediate, 0, keyIntermediate.Length);
				}
				digest.DoFinal (outhash, 0);
			}
			return Base32Encoder.Encode (outhash).TrimEnd(trimChars).ToLower();
		}
Example #11
0
        public static string HashSomething(string password, string something)
        {
            var dig = new Sha256Digest();
            byte[] bpassword = Encoding.UTF8.GetBytes(password);
            dig.BlockUpdate(bpassword, 0, bpassword.Length);
            var key = new byte[dig.GetDigestSize()];
            dig.DoFinal(key, 0);

            var hmac = new HMac(new Sha256Digest());
            hmac.Init(new KeyParameter(key));
            byte[] input = Encoding.UTF8.GetBytes(something);
            hmac.BlockUpdate(input, 0, input.Length);
            var output = new byte[hmac.GetMacSize()];
            hmac.DoFinal(output, 0);

            var sb = new StringBuilder(output.Length*2);
            foreach (byte b in output)
            {
                sb.AppendFormat("{0:x2}", b);
            }
            return sb.ToString();
        }
Example #12
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 #13
0
        private static Boolean SignatureMatches(string encodedSignature, string encodedAgreement, string signTextTransformation, OpensignSignature opensignSignature)
        {
            if (!encodedAgreement.Equals(encodedSignature))
            {
                return false;
            }

            var stylesheetDigest = opensignSignature.StylesheetDigest;
            if (stylesheetDigest != null)
            {
                if (signTextTransformation == null)
                {
                    throw new ArgumentException("signTextTransformation is required for XML signing");
                }

                var digest = new Sha256Digest();
                var encode = new ASCIIEncoding();
                byte[] stylesheetBytes = encode.GetBytes(signTextTransformation);
                digest.BlockUpdate(stylesheetBytes, 0, stylesheetBytes.Length);
                var digestBytes = new byte[digest.GetDigestSize()];
                digest.DoFinal(digestBytes, 0);
                var calculatedDigest = Encoding.UTF8.GetString(digestBytes, 0, digestBytes.Length);

                return stylesheetDigest.Equals(calculatedDigest);
            }
            return true;
        }
Example #14
0
		public static string FromKeys(IDictionary<string, string> publicKeys) {
			// You've gotta have some keys to hash!
			if (publicKeys.Count <= 0)
				return null;
			Sha256Digest digest = new Sha256Digest ();
			List<string> keys = new List<string>(publicKeys.Keys);
			keys.Sort ();

			int digestSize = digest.GetDigestSize ();
			byte[] outhash = null;
			foreach (var key in keys) {
				if (outhash != null) {
					digest.BlockUpdate (outhash, 0, digestSize);
				} else {
					outhash = new byte[digestSize];
				}
				byte inByte;
				try {
					inByte = Convert.ToByte (key, 16);
				} catch(FormatException) {
					return null;
				} catch(OverflowException) {
					return null;
				} catch (ArgumentException) {
					return null;
				}
				digest.Update (inByte);
				digest.DoFinal (outhash, 0);
				digest.Reset ();

				digest.BlockUpdate (outhash, 0, digestSize);
				byte[] keyData = Base32Encoder.Decode(publicKeys [key]);
				Sha256Digest keyDigest = new Sha256Digest ();
				keyDigest.BlockUpdate (keyData, 0, keyData.Length);
				keyDigest.DoFinal (outhash, 0);
				digest.BlockUpdate (outhash, 0, outhash.Length);
				digest.DoFinal (outhash, 0);
			}
			return Base32Encoder.Encode (outhash).TrimEnd(trimChars).ToLower();
		}
Example #15
0
		public ITestResult Perform()
        {
            IDigest digest = new Sha256Digest();
            byte[] resBuf = new byte[digest.GetDigestSize()];
            string resStr;

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

            resStr = Hex.ToHexString(resBuf);
            if (!resVec1.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 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))
            {
                return new SimpleTestResult(false,
                    "SHA-256 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))
            {
                return new SimpleTestResult(false,
                    "SHA-256 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))
            {
                return new SimpleTestResult(false,
                    "SHA-256 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 Sha256Digest((Sha256Digest)digest);

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

            resStr = Hex.ToHexString(resBuf);
            if (!resVec4.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 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))
            {
                return new SimpleTestResult(false,
                    "SHA-256 failing standard vector test 5"
                    + SimpleTest.NewLine
                    + "    expected: " + resVec4
                    + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            // test 6
            bytes = Hex.Decode(testVec5);
            for ( int i = 0; i < 100000; i++ )
            {
                digest.BlockUpdate(bytes, 0, bytes.Length);
            }
            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec5.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 failing standard vector test 6"
                    + SimpleTest.NewLine
                    + "    expected: " + resVec5
                    + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            return new SimpleTestResult(true, Name + ": Okay");
        }
 private static string GetHashDigest(Sha256Digest hash)
 {
     var digest = new byte[hash.GetDigestSize()];
     hash.DoFinal(digest, 0);
     return BitConverter.ToString(digest).Replace("-", string.Empty).ToLower();
 }
Example #17
0
 private static byte[] ComputeHash(object document)
 {
     var sha = new Sha256Digest();
     var stream = new DigestStream(new MemoryStream(), null, sha);
     using (var writer = new StreamWriter(stream))
     {
         string mementoToString = JsonConvert.SerializeObject(document);
         writer.Write(mementoToString);
     }
     byte[] buffer = new byte[sha.GetDigestSize()];
     sha.DoFinal(buffer, 0);
     return buffer;
 }
		/**
		 * generate suitable parameters for DSA, in line with
		 * <i>FIPS 186-3 A.1 Generation of the FFC Primes p and q</i>.
		 */
		private DsaParameters GenerateParameters_FIPS186_3()
		{
// A.1.1.2 Generation of the Probable Primes p and q Using an Approved Hash Function
			// FIXME This should be configurable (digest size in bits must be >= N)
			IDigest d = new Sha256Digest();
			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 = BigInteger.One.ShiftLeft(N - 1).Add(U).Add(BigInteger.One).Subtract(
					U.Mod(BigInteger.Two));

// 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)?
//	                    int index = 1;
//	                    BigInteger g = CalculateGenerator_FIPS186_3_Verifiable(d, p, q, seed, index);
//	                    if (g != null)
//	                    {
//	                        // TODO Should 'index' be a part of the validation parameters?
//	                        return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
//	                    }

						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.
			}
		}
		internal static byte[] GetCertificateAssocicationData(TlsaSelector selector, TlsaMatchingType matchingType, X509Certificate certificate)
		{
			byte[] selectedBytes;
			switch (selector)
			{
				case TlsaSelector.FullCertificate:
					selectedBytes = certificate.GetRawCertData();
					break;

				case TlsaSelector.SubjectPublicKeyInfo:
					selectedBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.FromX509Certificate(certificate).GetPublicKey()).GetDerEncoded();
					break;

				default:
					throw new NotSupportedException();
			}

			byte[] matchingBytes;
			switch (matchingType)
			{
				case TlsaMatchingType.Full:
					matchingBytes = selectedBytes;
					break;

				case TlsaMatchingType.Sha256Hash:
					Sha256Digest sha256Digest = new Sha256Digest();
					sha256Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length);
					matchingBytes = new byte[sha256Digest.GetDigestSize()];
					sha256Digest.DoFinal(matchingBytes, 0);
					break;

				case TlsaMatchingType.Sha512Hash:
					Sha512Digest sha512Digest = new Sha512Digest();
					sha512Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length);
					matchingBytes = new byte[sha512Digest.GetDigestSize()];
					sha512Digest.DoFinal(matchingBytes, 0);
					break;

				default:
					throw new NotSupportedException();
			}

			return matchingBytes;
		}
Example #20
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 #21
0
        private BigInteger SMPHash(byte hash_number, BigInteger big_int_a, BigInteger big_int_b)
        {
            byte[] _encoded_mpi = null;

            Sha256Digest _sha256 = new Sha256Digest();

            _sha256.Update(hash_number);

            Utility.EncodeMpiBytes(big_int_a, ref _encoded_mpi);
            _sha256.BlockUpdate(_encoded_mpi, 0, _encoded_mpi.Length);

            if (big_int_b != null)
            {

                Utility.EncodeMpiBytes(big_int_b, ref _encoded_mpi);
                _sha256.BlockUpdate(_encoded_mpi, 0, _encoded_mpi.Length);
            }

            byte[] _hashed_bytes = new byte[_sha256.GetDigestSize()];

            _sha256.DoFinal(_hashed_bytes, 0);

            return new BigInteger(1,_hashed_bytes);
        }