public void WriteHash(IHash hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (!GetIsInNodeSet() || !IncludeComments) { return; } UTF8Encoding utf8 = new UTF8Encoding(false); byte[] rgbData = utf8.GetBytes("(char) 10"); if (docPos == DocPosition.AfterRootElement) { hash.BlockUpdate(rgbData, 0, rgbData.Length); } rgbData = utf8.GetBytes("<!--"); hash.BlockUpdate(rgbData, 0, rgbData.Length); rgbData = utf8.GetBytes(Value); hash.BlockUpdate(rgbData, 0, rgbData.Length); rgbData = utf8.GetBytes("-->"); hash.BlockUpdate(rgbData, 0, rgbData.Length); if (docPos == DocPosition.BeforeRootElement) { rgbData = utf8.GetBytes("(char) 10"); hash.BlockUpdate(rgbData, 0, rgbData.Length); } }
public void WriteHash(IHash hash, DocPosition docPos, AncestralNamespaceContextManager anc) { UTF8Encoding utf8 = new UTF8Encoding(false); byte[] rgbData = utf8.GetBytes(" " + Name + "=\""); hash.BlockUpdate(rgbData, 0, rgbData.Length); rgbData = utf8.GetBytes(Utils.EscapeAttributeValue(Value)); hash.BlockUpdate(rgbData, 0, rgbData.Length); rgbData = utf8.GetBytes("\""); hash.BlockUpdate(rgbData, 0, rgbData.Length); }
public override void Write(byte[] buffer, int offset, int count) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(count > 0); CheckIfCanDecorate(); _streamBinding.Write(buffer, offset, count); _digest.BlockUpdate(buffer, offset, count); }
public void WriteHash(IHash hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && docPos == DocPosition.InRootElement) { UTF8Encoding utf8 = new UTF8Encoding(false); byte[] rgbData = utf8.GetBytes(Utils.EscapeWhitespaceData(Value)); hash.BlockUpdate(rgbData, 0, rgbData.Length); } }
public void WriteHash(IHash hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (GetIsInNodeSet()) { UTF8Encoding utf8 = new UTF8Encoding(false); byte[] rgbData = utf8.GetBytes(ParserUtils.EscapeTextData(Value)); hash.BlockUpdate(rgbData, 0, rgbData.Length); } }
public virtual void GetDigestedOutput(IHash hash) { byte[] buffer = new byte[4096]; int bytesRead; var inputStream = (Stream)GetOutput(typeof(Stream)); hash.Reset(); while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) { hash.BlockUpdate(buffer, 0, bytesRead); } }
public void WriteHash(IHash hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (!IsInNodeSet) { return; } UTF8Encoding utf8 = new UTF8Encoding(false); byte[] rgbData; if (docPos == DocPosition.AfterRootElement) { rgbData = utf8.GetBytes("(char) 10"); hash.BlockUpdate(rgbData, 0, rgbData.Length); } rgbData = utf8.GetBytes("<?"); hash.BlockUpdate(rgbData, 0, rgbData.Length); rgbData = utf8.GetBytes((Name)); hash.BlockUpdate(rgbData, 0, rgbData.Length); if ((Value != null) && (Value.Length > 0)) { rgbData = utf8.GetBytes(" " + Value); hash.BlockUpdate(rgbData, 0, rgbData.Length); } rgbData = utf8.GetBytes("?>"); hash.BlockUpdate(rgbData, 0, rgbData.Length); if (docPos == DocPosition.BeforeRootElement) { rgbData = utf8.GetBytes("(char) 10"); hash.BlockUpdate(rgbData, 0, rgbData.Length); } }
protected void RunDiscreteVectorTest(int number, DiscreteVectorDigestTestCase testCase) { var hashFunctionEnum = testCase.Primitive; IHash authenticator = AuthenticatorFactory.CreateHashPrimitive(hashFunctionEnum); authenticator.BlockUpdate(testCase.Message, 0, testCase.Message.Length); var output = new byte[authenticator.OutputSize]; authenticator.DoFinal(output, 0); Assert.IsTrue(testCase.Output.SequenceEqualShortCircuiting(output), "Test #{0} (\"{1}\") failed!", number, testCase.Name); }
public static void KeyExchange(ArraySegment <byte> sharedKey, ArraySegment <byte> publicKey, ArraySegment <byte> privateKey, bool naclCompat = false) { if (sharedKey.Array == null) { throw new ArgumentNullException("sharedKey.Array"); } if (publicKey.Array == null) { throw new ArgumentNullException("publicKey.Array"); } if (privateKey.Array == null) { throw new ArgumentNullException("privateKey"); } if (sharedKey.Count != SharedKeySizeInBytes) { throw new ArgumentException("sharedKey.Count != 32"); } if (publicKey.Count != PublicKeySizeInBytes) { throw new ArgumentException("publicKey.Count != 32"); } if (privateKey.Count != ExpandedPrivateKeySizeInBytes) { throw new ArgumentException("privateKey.Count != 64"); } FieldElement montgomeryX, edwardsY, edwardsZ, sharedMontgomeryX; FieldOperations.fe_frombytes(out edwardsY, publicKey.Array, publicKey.Offset); FieldOperations.fe_1(out edwardsZ); Curve25519.EdwardsToMontgomeryX(out montgomeryX, ref edwardsY, ref edwardsZ); IHash hasher = AuthenticatorFactory.CreateHashPrimitive(HashFunction.Sha512); hasher.BlockUpdate(privateKey.Array, privateKey.Offset, 32); byte[] h = new byte[64]; hasher.DoFinal(h, 0); ScalarOperations.sc_clamp(h, 0); MontgomeryOperations.scalarmult(out sharedMontgomeryX, h, 0, ref montgomeryX); h.SecureWipe(); FieldOperations.fe_tobytes(sharedKey.Array, sharedKey.Offset, ref sharedMontgomeryX); if (naclCompat) { Curve25519.KeyExchangeOutputHashNaCl(sharedKey.Array, sharedKey.Offset); } }
private void DoTestHMacDetECDsa(IHash digest, byte[] data, ECKey privKey, BigInteger r, BigInteger s) { var m = new byte[digest.OutputSize]; digest.BlockUpdate(data, 0, data.Length); digest.DoFinal(m, 0); var signer = new ECDsaSigner(true, privKey, null, new HmacDsaKCalculator(digest)); BigInteger rOut, sOut; signer.GenerateSignature(m, out rOut, out sOut); if (!r.Equals(rOut)) { Assert.Fail("r value wrong"); } if (!s.Equals(sOut)) { Assert.Fail("s value wrong"); } }
/** * Reset the mac generator. */ public override void Reset() { // Reset underlying digest _digest.Reset(); _digest.BlockUpdate(_inputPad, 0, _inputPad.Length); }
// What we want to do is pump the input throug the TransformChain and then // hash the output of the chain document is the document context for resolving relative references internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { // refList is a list of elements that might be targets of references // Now's the time to create our hashing algorithm IDigest digest = CryptoHelpers.CreateFromName <IDigest>(_digestMethod); if (digest == null) { IMac mac = CryptoHelpers.CreateFromName <IMac>(_digestMethod); if (mac == null) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); } // For compatibility to corefx' HMAC implementation byte[] randomKey = Utils.GenerateRandomBlock(mac.GetMacSize()); mac.Init(new KeyParameter(randomKey)); _hashAlgorithm = new MacHashWrapper(mac); } else { _hashAlgorithm = new DigestHashWrapper(digest); } // Let's go get the target. string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI); Stream hashInputStream = null; WebResponse response = null; Stream inputStream = null; XmlResolver resolver = null; _hashval = null; try { switch (_refTargetType) { case ReferenceTargetType.Stream: // This is the easiest case. We already have a stream, so just pump it through the TransformChain resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream((Stream)_refTarget, resolver, baseUri); break; case ReferenceTargetType.UriReference: // Second-easiest case -- dereference the URI & pump through the TransformChain // handle the special cases where the URI is null (meaning whole doc) // or the URI is just a fragment (meaning a reference to an embedded Object) if (_uri == null) { // We need to create a DocumentNavigator out of the XmlElement resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); // In the case of a Uri-less reference, we will simply pass null to the transform chain. // The first transform in the chain is expected to know how to retrieve the data to hash. hashInputStream = TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri); } else if (_uri.Length == 0) { // This is the self-referential case. First, check that we have a document context. // The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process if (document == null) { throw new System.Security.Cryptography.CryptographicException(string.Format(CultureInfo.CurrentCulture, SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); } // Normalize the containing document resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri)); hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else if (_uri[0] == '#') { // If we get here, then we are constructing a Reference to an embedded DataObject // referenced by an Id = attribute. Go find the relevant object bool discardComments = true; string idref = Utils.GetIdFromLocalUri(_uri, out discardComments); if (idref == "xpointer(/)") { // This is a self referencial case if (document == null) { throw new System.Security.Cryptography.CryptographicException(string.Format(CultureInfo.CurrentCulture, SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); } // We should not discard comments here!!! resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri); break; } XmlElement elem = SignedXml.GetIdElement(document, idref); if (elem != null) { _namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement); } if (elem == null) { // Go throw the referenced items passed in if (refList != null) { foreach (XmlNode node in refList) { XmlElement tempElem = node as XmlElement; if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)) && (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref))) { elem = tempElem; if (_signedXml._context != null) { _namespaces = Utils.GetPropagatedAttributes(_signedXml._context); } break; } } } } if (elem == null) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidReference); } XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri); // Add the propagated attributes Utils.AddNamespaces(normDocument.DocumentElement, _namespaces); resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); if (discardComments) { // We should discard comments before going into the transform chain XmlDocument docWithNoComments = Utils.DiscardComments(normDocument); hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else { // This is an XPointer reference, do not discard comments!!! hashInputStream = TransformChain.TransformToOctetStream(normDocument, resolver, baseUri); } } else { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri); } break; case ReferenceTargetType.XmlElement: // We need to create a DocumentNavigator out of the XmlElement resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement)_refTarget, resolver, baseUri), resolver, baseUri); break; default: throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri); } // Compute the new hash value hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream); // Default the buffer size to 4K. byte[] buffer = new byte[4096]; int bytesRead; _hashAlgorithm.Reset(); while ((bytesRead = hashInputStream.Read(buffer, 0, buffer.Length)) > 0) { _hashAlgorithm.BlockUpdate(buffer, 0, bytesRead); } _hashval = new byte[_hashAlgorithm.GetHashSize()]; _hashAlgorithm.DoFinal(_hashval, 0); } finally { if (hashInputStream != null) { hashInputStream.Close(); } if (response != null) { response.Close(); } if (inputStream != null) { inputStream.Close(); } } return(_hashval); }
public void WriteHash(IHash hash, DocPosition docPos, AncestralNamespaceContextManager anc) { Hashtable nsLocallyDeclared = new Hashtable(); SortedList nsListToRender = new SortedList(new NamespaceSortOrder()); SortedList attrListToRender = new SortedList(new AttributeSortOrder()); UTF8Encoding utf8 = new UTF8Encoding(false); byte[] rgbData; XmlAttributeCollection attrList = Attributes; if (attrList != null) { foreach (XmlAttribute attr in attrList) { if (((CanonicalXmlAttribute)attr).IsInNodeSet || Utils.IsNamespaceNode(attr) || Utils.IsXmlNamespaceNode(attr)) { if (Utils.IsNamespaceNode(attr)) { anc.TrackNamespaceNode(attr, nsListToRender, nsLocallyDeclared); } else if (Utils.IsXmlNamespaceNode(attr)) { anc.TrackXmlNamespaceNode(attr, nsListToRender, attrListToRender, nsLocallyDeclared); } else if (IsInNodeSet) { attrListToRender.Add(attr, null); } } } } if (!Utils.IsCommittedNamespace(this, Prefix, NamespaceURI)) { string name = ((Prefix.Length > 0) ? "xmlns" + ":" + Prefix : "xmlns"); XmlAttribute nsattrib = (XmlAttribute)OwnerDocument.CreateAttribute(name); nsattrib.Value = NamespaceURI; anc.TrackNamespaceNode(nsattrib, nsListToRender, nsLocallyDeclared); } if (IsInNodeSet) { anc.GetNamespacesToRender(this, attrListToRender, nsListToRender, nsLocallyDeclared); rgbData = utf8.GetBytes("<" + Name); hash.BlockUpdate(rgbData, 0, rgbData.Length); foreach (object attr in nsListToRender.GetKeyList()) { (attr as CanonicalXmlAttribute).WriteHash(hash, docPos, anc); } foreach (object attr in attrListToRender.GetKeyList()) { (attr as CanonicalXmlAttribute).WriteHash(hash, docPos, anc); } rgbData = utf8.GetBytes(">"); hash.BlockUpdate(rgbData, 0, rgbData.Length); } anc.EnterElementContext(); anc.LoadUnrenderedNamespaces(nsLocallyDeclared); anc.LoadRenderedNamespaces(nsListToRender); XmlNodeList childNodes = ChildNodes; foreach (XmlNode childNode in childNodes) { CanonicalizationDispatcher.WriteHash(childNode, hash, docPos, anc); } anc.ExitElementContext(); if (IsInNodeSet) { rgbData = utf8.GetBytes("</" + Name + ">"); hash.BlockUpdate(rgbData, 0, rgbData.Length); } }
/// <summary> /// Hashes a BigInteger into another BigInteger. /// </summary> private BigInteger Hash(BigInteger k) { _digest.Reset(); // Item is prefixed with its length as a little-endian 4-byte unsigned integer byte[] kBytes = k.ToByteArray(); var lengthPrefix = new byte[4]; Pack.UInt32_To_LE((uint)kBytes.Length, lengthPrefix); _digest.BlockUpdate(lengthPrefix, 0, 4); _digest.BlockUpdate(kBytes, 0, kBytes.Length); var hash = new byte[_digest.OutputSize]; _digest.DoFinal(hash, 0); return(new BigInteger(1, hash)); }
internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { IDigest digest = CryptoHelpers.CreateFromName <IDigest>(_digestMethod); if (digest == null) { IMac mac = CryptoHelpers.CreateFromName <IMac>(_digestMethod); if (mac == null) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); } byte[] randomKey = CryptoUtils.GenerateRandomBlock(mac.GetMacSize()); mac.Init(new KeyParameter(randomKey)); _hashAlgorithm = new MacHashWrapper(mac); } else { _hashAlgorithm = new DigestHashWrapper(digest); } string baseUri = document == null ? Environment.CurrentDirectory + "\\" : document.BaseURI; Stream hashInputStream = null; WebResponse response = null; Stream inputStream = null; XmlResolver resolver = null; _hashval = null; try { switch (_refTargetType) { case ReferenceTargetType.Stream: resolver = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream((Stream)_refTarget, resolver, baseUri); break; case ReferenceTargetType.UriReference: if (_uri == null) { resolver = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri); } else if (_uri.Length == 0) { if (document == null) { throw new System.Security.Cryptography.CryptographicException(string.Format(CultureInfo.CurrentCulture, SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); } resolver = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument docWithNoComments = StreamUtils.DiscardComments(StreamUtils.PreProcessDocumentInput(document, resolver, baseUri)); hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else if (_uri[0] == '#') { bool discardComments = true; string idref = ParserUtils.GetIdFromLocalUri(_uri, out discardComments); if (idref == "xpointer(/)") { if (document == null) { throw new System.Security.Cryptography.CryptographicException(string.Format(CultureInfo.CurrentCulture, SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); } resolver = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream(StreamUtils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri); break; } XmlElement elem = GetSignedXml().GetIdElement(document, idref); if (elem != null) { _namespaces = ElementUtils.GetPropagatedAttributes(elem.ParentNode as XmlElement); } if (elem == null && refList != null) { foreach (XmlNode node in refList) { XmlElement tempElem = node as XmlElement; if ((tempElem != null) && (ElementUtils.HasAttribute(tempElem, "Id", XmlNameSpace.Url[NS.XmlDsigNamespaceUrl])) && (ElementUtils.GetAttribute(tempElem, "Id", NS.XmlDsigNamespaceUrl).Equals(idref))) { elem = tempElem; if (_signedXml._context != null) { _namespaces = ElementUtils.GetPropagatedAttributes(_signedXml._context); } break; } } } if (elem == null) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidReference); } XmlDocument normDocument = StreamUtils.PreProcessElementInput(elem, resolver, baseUri); ElementUtils.AddNamespaces(normDocument.DocumentElement, _namespaces); resolver = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); if (discardComments) { XmlDocument docWithNoComments = StreamUtils.DiscardComments(normDocument); hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else { hashInputStream = TransformChain.TransformToOctetStream(normDocument, resolver, baseUri); } } else { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri); } break; case ReferenceTargetType.XmlElement: resolver = (GetSignedXml().ResolverSet ? GetSignedXml()._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = TransformChain.TransformToOctetStream(StreamUtils.PreProcessElementInput((XmlElement)_refTarget, resolver, baseUri), resolver, baseUri); break; default: throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri); } hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream); byte[] buffer = new byte[4096]; int bytesRead; _hashAlgorithm.Reset(); while ((bytesRead = hashInputStream.Read(buffer, 0, buffer.Length)) > 0) { _hashAlgorithm.BlockUpdate(buffer, 0, bytesRead); } _hashval = new byte[_hashAlgorithm.GetHashSize()]; _hashAlgorithm.DoFinal(_hashval, 0); } finally { if (hashInputStream != null) { hashInputStream.Close(); } if (response != null) { response.Close(); } if (inputStream != null) { inputStream.Close(); } } return(_hashval); }
private void DigestUpdate(byte[] inSeed) { _digest.BlockUpdate(inSeed, 0, inSeed.Length); }