internal static bool IsSupportedAlgorithm([NotNull] this SecurityKey key, [NotNull] string algorithm) { // Note: SecurityKey currently doesn't support IsSupportedAlgorithm. // To work around this limitation, this static extension tries to // determine whether the given security key supports the specified // algorithm via CryptoConfig when available or using a pre-defined table. var symmetricSecurityKey = key as SymmetricSecurityKey; if (symmetricSecurityKey != null) { #if DNX451 try { var instance = CryptoConfig.CreateFromName(algorithm); if (instance is SymmetricAlgorithm || instance is KeyedHashAlgorithm) { return(true); } } // Ignore the InvalidOperationException thrown by CryptoConfig. catch (InvalidOperationException) { } #endif switch (algorithm) { case SecurityAlgorithms.HmacSha256Signature: case SecurityAlgorithms.HMAC_SHA256: case SecurityAlgorithms.HMAC_SHA384: case SecurityAlgorithms.HMAC_SHA512: return(true); case SecurityAlgorithms.Aes128Encryption: case SecurityAlgorithms.Aes128KeyWrap: return(symmetricSecurityKey.KeySize >= 128 && symmetricSecurityKey.KeySize <= 256); case SecurityAlgorithms.Aes192Encryption: case SecurityAlgorithms.Aes192KeyWrap: return(symmetricSecurityKey.KeySize >= 192 && symmetricSecurityKey.KeySize <= 256); case SecurityAlgorithms.Aes256Encryption: case SecurityAlgorithms.Aes256KeyWrap: return(symmetricSecurityKey.KeySize == 256); default: return(false); } } else if (key is AsymmetricSecurityKey) { #if DNX451 try { var instance = CryptoConfig.CreateFromName(algorithm); if (instance is AsymmetricAlgorithm || instance is SignatureDescription) { return(true); } } // Ignore the InvalidOperationException thrown by CryptoConfig. catch (InvalidOperationException) { } #endif switch (algorithm) { case SecurityAlgorithms.RsaSha256Signature: case SecurityAlgorithms.RsaSha384Signature: case SecurityAlgorithms.RsaSha512Signature: case SecurityAlgorithms.RSA_SHA256: case SecurityAlgorithms.RSA_SHA384: case SecurityAlgorithms.RSA_SHA512: case SecurityAlgorithms.RsaOaepKeyWrap: case SecurityAlgorithms.RsaV15KeyWrap: { if (key is RsaSecurityKey) { return(true); } var x509SecurityKey = key as X509SecurityKey; if (x509SecurityKey != null) { #if DNX451 return(x509SecurityKey.Certificate.PublicKey.Key is RSA); #else return(x509SecurityKey.Certificate.GetRSAPublicKey() != null); #endif } return(false); } #if DNXCORE50 // Note: the ECDsa type exists on .NET 4.5.1 but not on Mono 4.3. // To prevent this code path from throwing an exception // on Mono, the following algorithms are ignored on DNX451. case SecurityAlgorithms.ECDSA_SHA256: case SecurityAlgorithms.ECDSA_SHA384: case SecurityAlgorithms.ECDSA_SHA512: { if (key is ECDsaSecurityKey) { return(true); } var x509SecurityKey = key as X509SecurityKey; if (x509SecurityKey != null) { return(x509SecurityKey.Certificate.GetECDsaPublicKey() != null); } return(false); } #endif default: return(false); } } // If the security key doesn't inherit from SymmetricSecurityKey // or AsymmetricSecurityKey, it must be treated as an invalid key // and false must be returned to indicate that it cannot be used // with the specified algorithm. return(false); }
public void CreateViaCryptoConfig() { // extensions can be created with CryptoConfig AsnEncodedData aed = new AsnEncodedData(new byte[] { 0x04, 0x00 }); X509SubjectKeyIdentifierExtension ski = (X509SubjectKeyIdentifierExtension)CryptoConfig.CreateFromName(oid, new object[2] { aed, true }); Assert.AreEqual(String.Empty, ski.SubjectKeyIdentifier, "SubjectKeyIdentifier"); Assert.AreEqual("04-00", BitConverter.ToString(ski.RawData), "RawData"); }
public void Render() { // TO DO: REWRITE THIS CLASS! and maybe the whole process of // getting data from the lower classes, why convert buffers // to XML just to convert them again in this Render method? // ALSO: this conversion process does not take into account that // the XML data that this class is converted from might // contain more than _CX characters in a line, since the // previous conversion to XML converts '<' to "<" and // the like, which will also cause shifts in character positions. // // Reset cache // _stringValueCache = null; // if (CX == 0 || CY == 0) { // TODO: Need to fix this CX = 132; CY = 43; } // CFCJr 2008/07/11 if (CX < 80) { CX = 80; } if (CY < 25) { CY = 25; } // CFCJr 2008/07/11 if (CX < 80) { CX = 80; } if (CY < 25) { CY = 25; } UserIdentified = null; MatchListIdentified = null; // // Render text image of screen // // mScreenBuffer = new char[CX * CY]; mScreenRows = new string[CY]; // CFCJr 2008/07/11 // The following might be much faster: // // string str = "".PadRight(_CX*_CY, ' '); // mScreenBuffer = str.ToCharArray(); // ........do operations on mScreenBuffer to fill it...... // str = string.FromCharArray(mScreenBuffer); // for (int r = 0; r < _CY; r++) // mScreenRows[i] = str.SubString(r*_CY,_CX); // // ie, fill mScreenBuffer with the data from Unformatted and Field, then // create str (for the hash) and mScreenRows[] // with the result. int i; for (i = 0; i < mScreenBuffer.Length; i++) // CFCJr. 2008.07/11 replase _CX*CY with mScreenBuffer.Length { mScreenBuffer[i] = ' '; } // int chindex; if (Field == null || Field.Length == 0 && (Unformatted == null || Unformatted.Text == null)) { if (Unformatted == null || Unformatted.Text == null) { Console.WriteLine("XMLScreen:Render: **BUGBUG** XMLScreen.Unformatted screen is blank"); } else { Console.WriteLine("XMLScreen:Render: **BUGBUG** XMLScreen.Field is blank"); } Console.Out.Flush(); // CFCJr. Move logic for what is in mScreenRows to seperate if logic // this will give unformatted results even if Field==null or 0 length // and vise-a-versa. /* * for (i=0; i<mScreenRows.Length; i++) * { * mScreenRows[i] = new String(' ',_CX); * } */ } var blankRow = string.Empty; blankRow = blankRow.PadRight(CX, ' '); if (Unformatted == null || Unformatted.Text == null) { // CFCJr. 2008/07/11 initilize a blank row of _CX (80?) spaces for (i = 0; i < mScreenRows.Length; i++) { //mScreenRows[i] = " ".Substring(0, _CX); // CFCJr. 2008/07/11 replace above method of 80 spaces with following mScreenRows[i] = blankRow; } } else { for (i = 0; i < Unformatted.Text.Length; i++) { var text = Unformatted.Text[i]; // CFCJr, make sure text is not null if (string.IsNullOrEmpty(text)) { text = string.Empty; } // CFCJr, replace "<" with '<' text = text.Replace("<", "<"); // CFCJr, Remove this loop to pad text // and use text.PadRight later. // This will help in not processing more // characters than necessary into mScreenBuffer // below //while (text.Length < _CX) // text+=" "; // int p; //for (p=0; p<_CX; p++) for (p = 0; p < text.Length; p++) // CFC,Jr. { if (text[p] < 32 || text[p] > 126) { text = text.Replace(text[p], ' '); } } // //for (chindex=0; chindex<Unformatted.Text[i].Length; chindex++) // CFCJr, 2008/07/11 use text.length instead of Unformatted.Text[i].Length // since we only pad text with 80 chars but if Unformatted.Text[i] // contains XML codes (ie, "<") then it could be longer than // 80 chars (hence, longer than text). // Also, I replace "<" above with "<". for (chindex = 0; chindex < text.Length; chindex++) { // CFCJr, calculate mScreenBuffer index only once var bufNdx = chindex + i * CX; if (bufNdx < mScreenBuffer.Length) { mScreenBuffer[bufNdx] = text[chindex]; } } // CFCJr, make sure we don't overflow the index of mScreenRows // since i is based on the dimensions of Unformatted.Text // instead of mScreenRows.Length if (i < mScreenRows.Length) { text = text.PadRight(CX, ' '); // CFCJr. 2008/07/11 use PadRight instead of loop above mScreenRows[i] = text; } } } // CFCJr, lets make sure we have _CY rows in mScreenRows here // since we use Unformated.Text.Length for loop above which // could possibly be less than _CY. for (i = 0; i < mScreenRows.Length; i++) { if (string.IsNullOrEmpty(mScreenRows[i])) { mScreenRows[i] = blankRow; } } //============== // Now process the Field (s) if (Field != null && Field.Length > 0) { // // Now superimpose the formatted fields on the unformatted base // for (i = 0; i < Field.Length; i++) { var field = Field[i]; if (field.Text != null) { for (chindex = 0; chindex < field.Text.Length; chindex++) { var ch = field.Text[chindex]; if (ch < 32 || ch > 126) { ch = ' '; } // CFCJr, 2008/07/11 make sure we don't get out of bounds // of the array m_ScreenBuffer. var bufNdx = chindex + field.Location.left + field.Location.top * CX; if (bufNdx >= 0 && bufNdx < mScreenBuffer.Length) { mScreenBuffer[bufNdx] = ch; } } } } // CFCJr, 2008/07/11 // SOMETHING needs to be done in this method to speed things up. // Above, in the processing of the Unformatted.Text, Render() // goes to the trouble of loading up mScreenBuffer and mScreenRows. // now here, we replace mScreenRows with the contents of mScreenBuffer. // Maybe, we should only load mScreenBuffer and then at the end // of Render(), load mScreenRows from it (or vise-a-vera). // WE COULD ALSO use // mScreenRows[i] = string.FromCharArraySubset(mScreenBuffer, i*_CX, _CX); // inside this loop. for (i = 0; i < CY; i++) { var temp = string.Empty; // CFCJr, 2008/07/11 replace "" for (var j = 0; j < CX; j++) { temp += mScreenBuffer[i * CX + j]; } mScreenRows[i] = temp; } } // now calculate our screen's hash // // CFCJr, dang, now we're going to copy the data again, // this time into a long string.....(see comments at top of Render()) // I bet there's a easy way to redo this class so that we use just // one buffer (string or char[]) instead of all these buffers. // WE COULD also use // string hashStr = string.FromCharArray(mScreenBuffer); // instead of converting mScreenRows to StringBuilder // and then converting it to a string. var hash = (HashAlgorithm)CryptoConfig.CreateFromName("MD5"); var builder = new StringBuilder(); for (i = 0; i < mScreenRows.Length; i++) { builder.Append(mScreenRows[i]); } var myHash = hash.ComputeHash(new UnicodeEncoding().GetBytes(builder.ToString())); Hash = BitConverter.ToString(myHash); _ScreenGuid = Guid.NewGuid(); }
//md5加密源码 public static String Encrypt(string password) { Byte[] clearBytes = new UnicodeEncoding().GetBytes(password); Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes); return(BitConverter.ToString(hashedBytes)); }
public static void AddAlgorithm_CreateFromName_ReturnsMapped() { CryptoConfig.AddAlgorithm(typeof(AesCryptoServiceProvider), "AESFancy"); Assert.Equal(typeof(AesCryptoServiceProvider).FullName, CryptoConfig.CreateFromName("AESFancy").GetType().FullName); }
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 m_hashAlgorithm = CryptoConfig.CreateFromName(m_digestMethod) as HashAlgorithm; if (m_hashAlgorithm == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } // Let's go get the target. string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI); Stream hashInputStream = null; WebRequest request = null; WebResponse response = null; Stream inputStream = null; XmlResolver resolver = null; byte[] hashval = null; try { switch (m_refTargetType) { case ReferenceTargetType.Stream: // This is the easiest case. We already have a stream, so just pump it through the TransformChain resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream((Stream)m_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 (m_uri == null) { // We need to create a DocumentNavigator out of the XmlElement resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_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 = this.TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri); } else if (m_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 CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), m_uri)); } // Normalize the containing document resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else if (m_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(m_uri, out discardComments); if (idref == "xpointer(/)") { // This is a self referencial case if (document == null) { throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), m_uri)); } // We should not discard comments here!!! resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri); break; } XmlElement elem = this.SignedXml.GetIdElement(document, idref); if (elem != null) { m_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 (this.m_signedXml.m_context != null) { m_namespaces = Utils.GetPropagatedAttributes(this.m_signedXml.m_context); } break; } } } } if (elem == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference")); } XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri); // Add the propagated attributes Utils.AddNamespaces(normDocument.DocumentElement, m_namespaces); resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); if (discardComments) { // We should discard comments before going into the transform chain XmlDocument docWithNoComments = Utils.DiscardComments(normDocument); hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else { // This is an XPointer reference, do not discard comments!!! hashInputStream = this.TransformChain.TransformToOctetStream(normDocument, resolver, baseUri); } } else if (Utils.AllowDetachedSignature()) { // WebRequest always expects an Absolute Uri, so try to resolve if we were passed a relative Uri. System.Uri uri = new System.Uri(m_uri, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) { uri = new Uri(new Uri(baseUri), uri); } request = WebRequest.Create(uri); if (request == null) { goto default; } response = request.GetResponse(); if (response == null) { goto default; } inputStream = response.GetResponseStream(); if (inputStream == null) { goto default; } resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(inputStream, resolver, m_uri); } else { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), m_uri); } break; case ReferenceTargetType.XmlElement: // We need to create a DocumentNavigator out of the XmlElement resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement)m_refTarget, resolver, baseUri), resolver, baseUri); break; default: throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), m_uri); } // Compute the new hash value hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream); hashval = m_hashAlgorithm.ComputeHash(hashInputStream); } finally { if (hashInputStream != null) { hashInputStream.Close(); } if (response != null) { response.Close(); } if (inputStream != null) { inputStream.Close(); } } return(hashval); }
static void Main(string[] args) { int option = 3; if (option == 1) { Console.WriteLine("Hello World!"); X509Certificate2 cert = new X509Certificate2(); //string certificateThumbprint = "c6a24a08eb419a70980ba0ab3b174e92c8cf743e"; //clientauth root-ca.observicing.net string certificateThumbprint = "8782c6c304353bcfd29692d2593e7d44d934ff11"; X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); //X509Certificate2 rootCertificate = (store.Certificates.Find(X509FindType.FindByThumbprint, "6272237b5079bf4bb57194f841dc01508fadbc50", false))[0]; //client.obs X509Certificate2Collection storeCerts = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false); if (storeCerts.Count > 0) { cert = storeCerts[0]; } else { throw new ArgumentException($"{nameof(certificateThumbprint)} was not found in the computer trusted root store", nameof(certificateThumbprint)); //return newCert; } //X509Certificate2 cert = /* your code here */; foreach (X509Extension extension in cert.Extensions) { if (extension.Oid.Value == "2.5.29.31") { Console.WriteLine("yeet"); var rawExtensionData = extension.RawData; AsnEncodedData asnExtensionData = new AsnEncodedData(extension.Oid, extension.RawData); //var hmm = extension. //CopyFrom(asnExtensionData); System.IO.File.WriteAllBytes(@"F:\DevGit\certs\csharptest\crloid.txt", rawExtensionData); //asnExtensionData. } //var rawExtensionData = extension.RawData; //AsnEncodedData asnExtensionData = new AsnEncodedData(extension.Oid, extension.RawData); //System.IO.File.WriteAllBytes(@"F:\DevGit\certs\csharptest\compare\" + extension.Oid.Value + ".txt", rawExtensionData); // Create an AsnEncodedData object using the extensions information. AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData); Console.WriteLine("Extension type: {0}", extension.Oid.FriendlyName); Console.WriteLine("Oid value: {0}", asndata.Oid.Value); Console.WriteLine("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine); Console.WriteLine(asndata.Format(true)); } } if (option == 2) { // Create a CryptoConfig object to store configuration information. CryptoConfig cryptoConfig = new CryptoConfig(); // Retrieve the class path for CryptoConfig. string classDescription = cryptoConfig.ToString(); // Create a new SHA1 provider. //SHA256CryptoServiceProvider SHA1alg = // (SHA256CryptoServiceProvider)CryptoConfig.CreateFromName("SHA256"); // Create an RSAParameters with the TestContainer key container. CspParameters parameters = new CspParameters(); parameters.KeyContainerName = "http://dev-11.observicing.net/crl/root-ca.crl"; Object[] argsArray = new Object[] { parameters }; //string[] tst = new string[0]; List <string> strlst = new List <string>(); string tst = "http://dev-11.observicing.net/crl/root-ca.crl"; var strarr = strlst.ToArray(); // Instantiate the RSA provider instance accessing the TestContainer // key container. RSACryptoServiceProvider rsaProvider = (RSACryptoServiceProvider) CryptoConfig.CreateFromName("RSA", argsArray); //parameters. // Use the MapNameToOID method to get an object identifier // (OID) from the string name of the SHA1 algorithm. string sha1Oid = CryptoConfig.MapNameToOID("SHA256RSA"); // Encode the specified object identifier. byte[] encodedMessage = CryptoConfig.EncodeOID(sha1Oid); CryptoConfig.AddOID("2.5.29.31", strarr); byte[] encodetest = CryptoConfig.EncodeOID(sha1Oid); //.EncodeOID("2.5.29.31"); System.IO.File.WriteAllBytes(@"F:\DevGit\certs\csharptest\encodedsha256.txt", encodetest); // Display the results to the console. Console.WriteLine("** " + classDescription + " **"); Console.WriteLine("Created an RSA provider " + "with a KeyContainerName called " + parameters.KeyContainerName + "."); Console.WriteLine("Object identifier from the SHA1 name:" + sha1Oid); Console.WriteLine("The object identifier encoded: " + System.Text.Encoding.ASCII.GetString(encodedMessage)); Console.WriteLine("This sample completed successfully; " + "press Enter to exit."); Console.ReadLine(); //byte[] oidBytes = File.ReadAllBytes(@"F:\DevGit\certs\csharptest\crloid.txt"); //X509SignatureGenerator hmm = new X509SignatureGenerator(); //string s = "30353033a031a02f862d687474703a2f2f6465762d31312e6f62736572766963696e672e6e65742f63726c2f726f6f742d63612e63726c"; // int len = s.Length; // byte[] data = new byte[len / 2]; // for (int i = 0; i < len; i += 2) // { // data[i / 2] = (byte)((Character.digit(s.charAt(i), 16) << 4) // + Character.digit(s.charAt(i + 1), 16)); // } // return data; } if (option == 3) { // WORKING EXAMPLE TO DECODE X509 EXTENSION BYTE ARRAY //Oid oidObj = new Oid("2.5.29.31"); // CRL distribution points List <string> files = new List <string>(); files.Add("2.5.29.37.txt"); files.Add("2.5.29.14.txt"); files.Add("2.5.29.15.txt"); files.Add("2.5.29.17.txt"); files.Add("2.5.29.19.txt"); files.Add("2.5.29.31.txt"); files.Add("2.5.29.35.txt"); //WOW //files.Add("crltext-base64decode-bytes1.txt"); //var hmm = extension. //CopyFrom(asnExtensionData);2.5.29.14.txt //WORKS! //byte[] rawExtensionData = System.IO.File.ReadAllBytes(@"F:\DevGit\certs\csharptest\crloid.txt"); //WriteAllBytes(@"F:\DevGit\certs\csharptest\crloid.txt", rawExtensionData); foreach (var f in files) { // testing loop Oid oidObj = new Oid(f.Replace(".txt", "")); //Oid oidObj = new Oid("2.5.29.31"); byte[] rawExtensionData = System.IO.File.ReadAllBytes(@"F:\DevGit\certs\csharptest\" + f); //byte[] rawExtensionData = System.IO.File.ReadAllBytes(@"F:\DevGit\certs\csharptest\encodingusinglib\" + f); //decode base64 //string base64Decoded; //byte[] data = System.Convert.FromBase64String(base64Encoded); // base64Decoded = System.Text.ASCIIEncoding.ASCII.GetString(data); //srcref_test testencode = new srcref_test(); srcref_test testencode = new srcref_test(); //AsnEncodedData asnExtensionData = new AsnEncodedData(oidObj, rawExtensionData); var hmm = testencode.FormatNative(oidObj, rawExtensionData, true); Console.WriteLine("------------------------"); Console.WriteLine(oidObj.FriendlyName); Console.WriteLine(hmm); Console.WriteLine("------------------------"); //var encfunction = testencode.Srcref_test();// Srcref_test Srcref_test.for } Console.ReadKey(); } if (option == 4) { //WORKING EXAMPLE OF ENCODING CRL string testnumber = "3"; var urisStr = new string[] { "http://dev-11.observicing.net/crl/root-ca.crl" }; var uris = urisStr.Select(u => Encoding.UTF8.GetBytes(u)); var zero = new byte[] { 48 }; //"0", delimiter ? var nbsp = new byte[] { 160 }; //" ", separator ? var dagger = new byte[] { 134 }; //"dagger", separator ? var zeroSize = zero.Length + 1; var nbspSize = nbsp.Length + 1; var daggerSize = dagger.Length + 1; var col = new List <byte>(); col.AddRange(zero); //delimiter int totalBytes = uris.Sum(u => u.Length); totalBytes += (zeroSize + (nbspSize * 2) + daggerSize) * uris.Count(); col.Add((byte)totalBytes); //size of everything it contains foreach (var uri in uris) { var uriSize = uri.Length; col.AddRange(zero); //delimiter col.Add((byte)(nbspSize + nbspSize + uriSize + daggerSize)); //size of everything it contains col.AddRange(nbsp); col.Add((byte)(nbspSize + uriSize + daggerSize)); //size of everything it contains col.AddRange(nbsp); col.Add((byte)(uriSize + daggerSize)); //size of everything it contains col.AddRange(dagger); //separator ? col.Add((byte)uriSize); col.AddRange(uri); } var bytes = col.ToArray(); var base64 = Convert.ToBase64String(bytes); var oidCDP = new CObjectId(); oidCDP.InitializeFromName(CERTENROLL_OBJECTID.XCN_OID_CRL_DIST_POINTS); // There is no specific class to CDPs, so we use the CX509Extension var crlList = new CX509Extension(); crlList.Initialize(oidCDP, EncodingType.XCN_CRYPT_STRING_BASE64, base64); //certRequest.X509Extensions.Add(crlList); //crlList.RawData ASCIIEncoding asc = new ASCIIEncoding(); System.IO.File.WriteAllText(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-hexascii" + testnumber + ".txt", crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_HEXASCII]); System.IO.File.WriteAllText(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-hexraw" + testnumber + ".txt", crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_HEXRAW]); System.IO.File.WriteAllText(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-base64string" + testnumber + ".txt", crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BASE64]); System.IO.File.WriteAllText(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-base64string" + testnumber + ".txt", crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BASE64]); byte[] data = System.Convert.FromBase64String(crlList.RawData[CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BASE64]); System.IO.File.WriteAllBytes(@"F:\DevGit\certs\csharptest\encodingusinglib\crltext-base64decode-bytes" + testnumber + ".txt", data); //crlList.RawData System.Text.Encoding.ASCII //x509extensions } }
/// <summary> /// Parse the test case specifications from the <Tests> element in the /// test spec file /// </summary> /// <remarks> /// Throws an InvalidOperationException if an invalid XML node is presented /// </remarks> /// <param name="specRoot">Tests element in the test spec file</param> /// <param name="algorithms">mapping of algorithm names to implementations</returns> private static TestGroup[] ParseTestCases(XmlElement specRoot, Hashtable algorithms) { ArrayList groups = new ArrayList(); // read all the test groups foreach (XmlElement test in specRoot.GetElementsByTagName("Test")) { string groupName = test.GetAttribute("name"); if (groupName == "") { throw new InvalidOperationException("Missing 'name' attribute on Test"); } ArrayList testCases = new ArrayList(); // read all the tests in the group foreach (XmlElement testCase in test.GetElementsByTagName("TestItem")) { string dataType = testCase.GetAttribute("dataType").ToLower(); string data = testCase.GetAttribute("data"); // validate if (dataType == "") { throw new InvalidOperationException("Missing 'dataType' attribute on TestItem"); } if (!(dataType == "string" || dataType == "base64" || dataType == "hex")) { throw new InvalidOperationException("Invalid data type: " + dataType); } // parse the data byte[] dataBytes = null; switch (dataType) { case "string": dataBytes = new System.Text.UTF8Encoding().GetBytes(data); break; case "base64": dataBytes = Convert.FromBase64String(data); break; case "hex": dataBytes = Util.ParseHexBytes(data); break; } // grab all the results for this foreach (XmlElement testResult in testCase.GetElementsByTagName("HashValue")) { string algName = testResult.GetAttribute("algorithm"); string result = testResult.GetAttribute("value"); string key = testResult.GetAttribute("key"); string truncation = testResult.GetAttribute("truncation"); if (algName == "" || result == "") { throw new InvalidOperationException("Missing 'algorithm' or 'value' attribute on HashValue"); } // create the hashing function string algClass = (string)algorithms[algName]; HashAlgorithm hasher = null; if (algClass == null) { hasher = (HashAlgorithm)CryptoConfig.CreateFromName(algName); } else { // create the hash algorithm using reflection Type algType = Type.GetType(algClass); if (algType == null) { throw new InvalidOperationException("Invalid hashing algorithm: " + algClass); } hasher = (HashAlgorithm)Activator.CreateInstance(algType); } if (hasher == null) { throw new InvalidOperationException("Could not create hash algorithm: " + algName); } // parse the key byte[] keyBytes = Util.ParseHexBytes(key); // see if the hashing algorithm needs a key if (hasher is KeyedHashAlgorithm) { ((KeyedHashAlgorithm)hasher).Key = keyBytes; } // convert the value to bytes byte[] val = Util.ParseHexBytes(result); // create a test case string caseName = algName + " - " + data; caseName = caseName.Length > 50 ? caseName.Substring(0, 50) : caseName; if (truncation == "") { testCases.Add(new HashTestCase(caseName, hasher, dataBytes, val)); } else { testCases.Add(new HashTestCaseTruncate(caseName + "-" + truncation, hasher, dataBytes, val, Int32.Parse(truncation))); } } } groups.Add(new TestGroup(groupName, (TestCase[])testCases.ToArray(new TestCase("", null).GetType()))); } return((TestGroup[])groups.ToArray(new TestGroup("", new TestCase[] { }).GetType())); }
// Create a CustomCrypto object by calling CrytoConfig's // CreateFromName method and casting the type to CustomCrypto. // The create function attempts to create a CustomCrypto object using // the assembly name. This functionality requires modification of the // machine.config file. Add the following section to the configuration // element and modify the values of the cryptoClass to reflect what is // installed in your machines GAC. //<mscorlib> // <cryptographySettings> // <cryptoNameMapping> // <cryptoClasses> // <cryptoClass CustomCrypto="Contoso.CustomCrypto, // CustomCrypto, // Culture=neutral, // PublicKeyToken=fdb9f9c4851028bf, // Version=1.0.1448.27640" /> // </cryptoClasses> // <nameEntry name="Contoso.CustomCrypto" class="CustomCrypto" /> // <nameEntry name="CustomCrypto" class="CustomCrypto" /> // </cryptoNameMapping> // </cryptographySettings> //</mscorlib> new static public CustomCrypto Create(String algorithmName) { return((CustomCrypto)CryptoConfig.CreateFromName(algorithmName)); }
public void CreateFromName() { CreateFromName("SHA", "System.Security.Cryptography.SHA1CryptoServiceProvider"); // FIXME: We need to support the machine.config file to get exact same results // with the MS .NET Framework CreateFromName("SHA1", "System.Security.Cryptography.SHA1CryptoServiceProvider"); CreateFromName("System.Security.Cryptography.SHA1", "System.Security.Cryptography.SHA1CryptoServiceProvider"); // after installing the WSDK - changes to the machine.config file (not documented) // CreateFromName ("SHA1", "System.Security.Cryptography.SHA1Managed"); // CreateFromName ("System.Security.Cryptography.SHA1", "System.Security.Cryptography.SHA1Managed"); CreateFromName("System.Security.Cryptography.HashAlgorithm", "System.Security.Cryptography.SHA1CryptoServiceProvider"); CreateFromName("System.Security.Cryptography.SHA1CryptoServiceProvider", "System.Security.Cryptography.SHA1CryptoServiceProvider"); CreateFromName("MD5", "System.Security.Cryptography.MD5CryptoServiceProvider"); CreateFromName("System.Security.Cryptography.MD5", "System.Security.Cryptography.MD5CryptoServiceProvider"); CreateFromName("System.Security.Cryptography.MD5CryptoServiceProvider", "System.Security.Cryptography.MD5CryptoServiceProvider"); CreateFromName("SHA256", "System.Security.Cryptography.SHA256Managed"); CreateFromName("SHA-256", "System.Security.Cryptography.SHA256Managed"); CreateFromName("System.Security.Cryptography.SHA256", "System.Security.Cryptography.SHA256Managed"); CreateFromName("SHA384", "System.Security.Cryptography.SHA384Managed"); CreateFromName("SHA-384", "System.Security.Cryptography.SHA384Managed"); CreateFromName("System.Security.Cryptography.SHA384", "System.Security.Cryptography.SHA384Managed"); CreateFromName("SHA512", "System.Security.Cryptography.SHA512Managed"); CreateFromName("SHA-512", "System.Security.Cryptography.SHA512Managed"); CreateFromName("System.Security.Cryptography.SHA512", "System.Security.Cryptography.SHA512Managed"); CreateFromName("RSA", "System.Security.Cryptography.RSACryptoServiceProvider"); CreateFromName("System.Security.Cryptography.RSA", "System.Security.Cryptography.RSACryptoServiceProvider"); CreateFromName("System.Security.Cryptography.AsymmetricAlgorithm", "System.Security.Cryptography.RSACryptoServiceProvider"); CreateFromName("DSA", "System.Security.Cryptography.DSACryptoServiceProvider"); CreateFromName("System.Security.Cryptography.DSA", "System.Security.Cryptography.DSACryptoServiceProvider"); CreateFromName("DES", "System.Security.Cryptography.DESCryptoServiceProvider"); CreateFromName("System.Security.Cryptography.DES", "System.Security.Cryptography.DESCryptoServiceProvider"); CreateFromName("3DES", "System.Security.Cryptography.TripleDESCryptoServiceProvider"); CreateFromName("TripleDES", "System.Security.Cryptography.TripleDESCryptoServiceProvider"); CreateFromName("Triple DES", "System.Security.Cryptography.TripleDESCryptoServiceProvider"); CreateFromName("System.Security.Cryptography.TripleDES", "System.Security.Cryptography.TripleDESCryptoServiceProvider"); // LAMESPEC SymmetricAlgorithm documented as TripleDESCryptoServiceProvider CreateFromName("System.Security.Cryptography.SymmetricAlgorithm", "System.Security.Cryptography.RijndaelManaged"); CreateFromName("RC2", "System.Security.Cryptography.RC2CryptoServiceProvider"); CreateFromName("System.Security.Cryptography.RC2", "System.Security.Cryptography.RC2CryptoServiceProvider"); CreateFromName("Rijndael", "System.Security.Cryptography.RijndaelManaged"); CreateFromName("System.Security.Cryptography.Rijndael", "System.Security.Cryptography.RijndaelManaged"); // LAMESPEC Undocumented Names in CryptoConfig CreateFromName("RandomNumberGenerator", "System.Security.Cryptography.RNGCryptoServiceProvider"); CreateFromName("System.Security.Cryptography.RandomNumberGenerator", "System.Security.Cryptography.RNGCryptoServiceProvider"); CreateFromName("System.Security.Cryptography.KeyedHashAlgorithm", "System.Security.Cryptography.HMACSHA1"); CreateFromName("HMACSHA1", "System.Security.Cryptography.HMACSHA1"); CreateFromName("System.Security.Cryptography.HMACSHA1", "System.Security.Cryptography.HMACSHA1"); CreateFromName("MACTripleDES", "System.Security.Cryptography.MACTripleDES"); CreateFromName("System.Security.Cryptography.MACTripleDES", "System.Security.Cryptography.MACTripleDES"); // new HMAC - new base class doesn't return anything with it's short name Assert.IsNull(CryptoConfig.CreateFromName("HMAC"), "HMAC"); CreateFromName("System.Security.Cryptography.HMAC", "System.Security.Cryptography.HMACSHA1"); CreateFromName("HMACMD5", "System.Security.Cryptography.HMACMD5"); CreateFromName("System.Security.Cryptography.HMACMD5", "System.Security.Cryptography.HMACMD5"); CreateFromName("HMACRIPEMD160", "System.Security.Cryptography.HMACRIPEMD160"); CreateFromName("System.Security.Cryptography.HMACRIPEMD160", "System.Security.Cryptography.HMACRIPEMD160"); CreateFromName("HMACSHA256", "System.Security.Cryptography.HMACSHA256"); CreateFromName("System.Security.Cryptography.HMACSHA256", "System.Security.Cryptography.HMACSHA256"); CreateFromName("HMACSHA384", "System.Security.Cryptography.HMACSHA384"); CreateFromName("System.Security.Cryptography.HMACSHA384", "System.Security.Cryptography.HMACSHA384"); CreateFromName("HMACSHA512", "System.Security.Cryptography.HMACSHA512"); CreateFromName("System.Security.Cryptography.HMACSHA512", "System.Security.Cryptography.HMACSHA512"); // new hash algorithm CreateFromName("RIPEMD160", "System.Security.Cryptography.RIPEMD160Managed"); CreateFromName("RIPEMD-160", "System.Security.Cryptography.RIPEMD160Managed"); CreateFromName("System.Security.Cryptography.RIPEMD160", "System.Security.Cryptography.RIPEMD160Managed"); // x.509 stuff #if !MOBILE CreateFromName("X509Chain", "System.Security.Cryptography.X509Certificates.X509Chain"); // note: CryptoConfig can create any object ! CreateFromName("System.Security.Cryptography.CryptoConfig", "System.Security.Cryptography.CryptoConfig"); CreateFromName("System.IO.MemoryStream", "System.IO.MemoryStream"); #endif // non existing algo should return null (without exception) Assert.IsNull(CryptoConfig.CreateFromName("NonExistingAlgorithm"), "NonExistingAlgorithm"); }
public static new SHA384 Create(string hashName) { return((SHA384)CryptoConfig.CreateFromName(hashName)); }
public void CreateFromNameNull() { object o = CryptoConfig.CreateFromName(null); }
public ValidationResult Validate(SignatureDocument sigDocument) { /* Los elementos que se validan son: * * 1. Las huellas de las referencias de la firma. * 2. Se comprueba la huella del elemento SignedInfo y se verifica la firma con la clave pública del certificado. * 3. Si la firma contiene un sello de tiempo se comprueba que la huella de la firma coincide con la del sello de tiempo. * * La validación de perfiles -C, -X, -XL y -A esta fuera del ámbito de este proyecto. */ ValidationResult result = new ValidationResult(); try { // Verifica las huellas de las referencias y la firma sigDocument.XadesSignature.CheckXmldsigSignature(); } catch (Exception ex) { result.IsValid = false; result.Message = "La verificación de la firma no ha sido satisfactoria"; return(result); } if (sigDocument.XadesSignature.UnsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Count > 0) { // Se comprueba el sello de tiempo TimeStamp timeStamp = sigDocument.XadesSignature.UnsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection[0]; TimeStampToken token = new TimeStampToken(new CmsSignedData(timeStamp.EncapsulatedTimeStamp.PkiData)); byte[] tsHashValue = token.TimeStampInfo.GetMessageImprintDigest(); Crypto.DigestMethod tsDigestMethod = Crypto.DigestMethod.GetByOid(token.TimeStampInfo.HashAlgorithm.ObjectID.Id); System.Security.Cryptography.Xml.Transform transform = null; if (timeStamp.CanonicalizationMethod != null) { transform = CryptoConfig.CreateFromName(timeStamp.CanonicalizationMethod.Algorithm) as System.Security.Cryptography.Xml.Transform; } else { transform = new XmlDsigC14NTransform(); } ArrayList signatureValueElementXpaths = new ArrayList(); signatureValueElementXpaths.Add("ds:SignatureValue"); byte[] signatureValueHash = DigestUtil.ComputeHashValue(XMLUtil.ComputeValueOfElementList(sigDocument.XadesSignature, signatureValueElementXpaths, transform), tsDigestMethod); if (!Arrays.AreEqual(tsHashValue, signatureValueHash)) { result.IsValid = false; result.Message = "La huella del sello de tiempo no se corresponde con la calculada"; return(result); } } result.IsValid = true; result.Message = "Verificación de la firma satisfactoria"; return(result); }
public void Render() { // // Reset cache // _stringValueCache = null; // if (_CX == 0 || _CY == 0) { // TODO: Need to fix this _CX = 132; _CY = 43; } UserIdentified = null; MatchListIdentified = null; // // Render text image of screen // // mScreenBuffer = new char[_CX * _CY]; mScreenRows = new string[_CY]; int i; for (i = 0; i < _CX * _CY; i++) { mScreenBuffer[i] = ' '; } // int chindex; if (Field == null || Field.Length == 0 && (Unformatted == null || Unformatted.Text == null)) { //Console.WriteLine("**BUGBUG** Unformatted screen is blank"); for (i = 0; i < mScreenRows.Length; i++) { mScreenRows[i] = new String(' ', _CX); } } else { for (i = 0; i < Unformatted.Text.Length; i++) { string text = Unformatted.Text[i]; while (text.Length < _CX) { text += " "; } // int p; for (p = 0; p < _CX; p++) { if (text[p] < 32 || text[p] > 126) { text = text.Replace(text[p], ' '); } } // for (chindex = 0; chindex < Unformatted.Text[i].Length; chindex++) { if ((chindex + i * _CX) < mScreenBuffer.Length) { mScreenBuffer[chindex + i * _CX] = text[chindex]; } } if (i >= 0 && i < mScreenRows.Length) { mScreenRows[i] = text; } } // // Now superimpose the formatted fields on the unformatted base // for (i = 0; i < Field.Length; i++) { XMLScreenField field = Field[i]; if (field.Text != null) { for (chindex = 0; chindex < field.Text.Length; chindex++) { char ch = field.Text[chindex]; if (ch < 32 || ch > 126) { ch = ' '; } int off = chindex + field.Location.left + field.Location.top * _CX; if (off >= 0 && off < mScreenBuffer.Length) { mScreenBuffer[chindex + field.Location.left + field.Location.top * _CX] = ch; } } } } for (i = 0; i < _CY; i++) { string temp = ""; for (int j = 0; j < _CX; j++) { temp += mScreenBuffer[i * _CX + j]; } mScreenRows[i] = temp; } } // now calculate our screen's hash // HashAlgorithm hash = (HashAlgorithm)CryptoConfig.CreateFromName("MD5"); StringBuilder builder = new StringBuilder(); for (i = 0; i < mScreenRows.Length; i++) { builder.Append(mScreenRows[i]); } byte[] myHash = hash.ComputeHash(new UnicodeEncoding().GetBytes(builder.ToString())); this.Hash = BitConverter.ToString(myHash); this._ScreenGuid = Guid.NewGuid(); }
/// <summary> /// 使用SHA1哈希算法对byte数组进行单向哈希。 /// </summary> /// <param name="buf">准备进行哈希的byte数组</param> /// <returns>使用SHA1算法进行单向哈希后得到的byte数组</returns> public static byte[] ComputeHash(byte[] buf) { return(((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(buf)); }
public static X509Chain Create() { return((X509Chain)CryptoConfig.CreateFromName("X509Chain")); }
public void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } m_id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl); m_uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl); m_type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); // Transforms this.TransformChain = new TransformChain(); XmlElement transformsElement = value.SelectSingleNode("ds:Transforms", nsm) as XmlElement; if (transformsElement != null) { XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm); if (transformNodes != null) { foreach (XmlNode transformNode in transformNodes) { XmlElement transformElement = transformNode as XmlElement; string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); Transform transform = CryptoConfig.CreateFromName(algorithm) as Transform; if (transform == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UnknownTransform")); } AddTransform(transform); // let the transform read the children of the transformElement for data transform.LoadInnerXml(transformElement.ChildNodes); // Hack! this is done to get around the lack of here() function support in XPath if (transform is XmlDsigEnvelopedSignatureTransform) { // Walk back to the Signature tag. Find the nearest signature ancestor // Signature-->SignedInfo-->Reference-->Transforms-->Transform XmlNode signatureTag = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm); XmlNodeList signatureList = transformElement.SelectNodes("//ds:Signature", nsm); if (signatureList != null) { int position = 0; foreach (XmlNode node in signatureList) { position++; if (node == signatureTag) { ((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = position; break; } } } } } } } // DigestMethod XmlElement digestMethodElement = value.SelectSingleNode("ds:DigestMethod", nsm) as XmlElement; if (digestMethodElement == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestMethod"); } m_digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); // DigestValue XmlElement digestValueElement = value.SelectSingleNode("ds:DigestValue", nsm) as XmlElement; if (digestValueElement == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestValue"); } m_digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText)); // cache the Xml m_cachedXml = value; }
public new static Aes Create(string algorithmName) { return((Aes)CryptoConfig.CreateFromName(algorithmName)); }
static void Main(string[] args) { // Create a CryptoConfig object to store configuration information. //<Snippet2> CryptoConfig cryptoConfig = new CryptoConfig(); //</Snippet2> // Retrieve the class path for CryptoConfig. //<Snippet7> string classDescription = cryptoConfig.ToString(); //</Snippet7> // Create a new SHA1 provider. //<Snippet4> // This example uses the SHA1 algorithm. // Due to collision problems with SHA1, Microsoft recommends SHA256 or better. SHA1CryptoServiceProvider SHA1alg = (SHA1CryptoServiceProvider)CryptoConfig.CreateFromName("SHA1"); //</Snippet4> // Create an RSAParameters with the TestContainer key container. //<Snippet5> CspParameters parameters = new CspParameters(); parameters.KeyContainerName = "TestContainer"; Object[] argsArray = new Object[] { parameters }; // Instantiate the RSA provider instance accessing the TestContainer // key container. RSA rsa = (RSA) CryptoConfig.CreateFromName("RSA", argsArray); //</Snippet5> // Use the MapNameToOID method to get an object identifier // (OID) from the string name of the SHA1 algorithm. //<Snippet3> // This example uses the SHA1 algorithm. // Due to collision problems with SHA1, Microsoft recommends SHA256 or better. string sha1Oid = CryptoConfig.MapNameToOID("SHA1"); //</Snippet3> // Encode the specified object identifier. //<Snippet6> // This example uses the SHA1 algorithm. // Due to collision problems with SHA1, Microsoft recommends SHA256 or better. byte[] encodedMessage = CryptoConfig.EncodeOID(sha1Oid); //</Snippet6> // Display the results to the console. Console.WriteLine("** " + classDescription + " **"); Console.WriteLine("Created an RSA provider " + "with a KeyContainerName called " + parameters.KeyContainerName + "."); Console.WriteLine("Object identifier from the SHA1 name:" + sha1Oid); Console.WriteLine("The object identifier encoded: " + System.Text.Encoding.ASCII.GetString(encodedMessage)); Console.WriteLine("This sample completed successfully; " + "press Enter to exit."); Console.ReadLine(); }
internal GenericHashResult ComputeFileHash(Enums.HashAlgorithm hashAlgorithm, string filePathToComputeHash, long offset = 0, long count = 0) { if (!File.Exists(filePathToComputeHash)) { return(new GenericHashResult() { Success = false, Message = $"{MessageDictionary.Instance["Common.FileNotFound"]} \"{filePathToComputeHash}\"." }); } GenericHashResult result = null; HashAlgorithm hashAlg = null; #if CORERT switch (hashAlgorithm) { case Enums.HashAlgorithm.MD5: hashAlg = MD5.Create(); break; case Enums.HashAlgorithm.SHA1: hashAlg = SHA1.Create(); break; case Enums.HashAlgorithm.SHA256: hashAlg = SHA256.Create(); break; case Enums.HashAlgorithm.SHA384: hashAlg = SHA384.Create(); break; case Enums.HashAlgorithm.SHA512: hashAlg = SHA512.Create(); break; case Enums.HashAlgorithm.BCrypt: default: break; } #else hashAlg = (HashAlgorithm)CryptoConfig.CreateFromName(hashAlgorithm.ToString()); #endif try { byte[] hash = null; using (var fStream = new FileStream(filePathToComputeHash, FileMode.Open, FileAccess.Read, FileShare.None)) { //offset = (offset == 0 ? 0 : offset); count = (count == 0 ? fStream.Length : count); fStream.Position = offset; byte[] buffer = new byte[(1024 * 4)]; long amount = (count - offset); using (hashAlg) { int percentageDone = 0; while (amount > 0) { int bytesRead = fStream.Read(buffer, 0, (int)Math.Min(buffer.Length, amount)); if (bytesRead > 0) { amount -= bytesRead; if (amount > 0) { hashAlg.TransformBlock(buffer, 0, bytesRead, buffer, 0); } else { hashAlg.TransformFinalBlock(buffer, 0, bytesRead); } var tmpPercentageDone = (int)(fStream.Position * 100 / count); if (tmpPercentageDone != percentageDone) { percentageDone = tmpPercentageDone; RaiseOnHashProgress(percentageDone, (percentageDone != 100 ? $"Computing hash ({percentageDone}%)..." : $"Hash computed ({percentageDone}%).")); } } else { throw new InvalidOperationException(); } } hash = hashAlg.Hash; } } result = new GenericHashResult() { Success = true, Message = MessageDictionary.Instance["Hash.ComputeSuccess"], HashString = Encoding.HighPerformanceHexadecimal.ToHexString(hash), HashBytes = hash }; } catch (Exception ex) { result = new GenericHashResult() { Success = false, Message = ex.ToString() }; } return(result); }
new static public KeyedHashAlgorithm Create(String algName) { return((KeyedHashAlgorithm)CryptoConfig.CreateFromName(algName)); }
internal GenericHashResult ComputeHash(Enums.HashAlgorithm hashAlgorithm, byte[] bytesToComputeHash, int offset = 0, int count = 0) { if (bytesToComputeHash == null || bytesToComputeHash.Length <= 0) { return(new GenericHashResult() { Success = false, Message = MessageDictionary.Instance["Hash.InputRequired"] }); } GenericHashResult result = null; try { HashAlgorithm hashAlg = null; #if CORERT switch (hashAlgorithm) { case Enums.HashAlgorithm.MD5: hashAlg = MD5.Create(); break; case Enums.HashAlgorithm.SHA1: hashAlg = SHA1.Create(); break; case Enums.HashAlgorithm.SHA256: hashAlg = SHA256.Create(); break; case Enums.HashAlgorithm.SHA384: hashAlg = SHA384.Create(); break; case Enums.HashAlgorithm.SHA512: hashAlg = SHA512.Create(); break; case Enums.HashAlgorithm.BCrypt: default: break; } #else hashAlg = (HashAlgorithm)CryptoConfig.CreateFromName(hashAlgorithm.ToString()); #endif using (hashAlg) { //offset = (offset == 0 ? 0 : offset); count = (count == 0 ? bytesToComputeHash.Length : count); byte[] hash = hashAlg.ComputeHash(bytesToComputeHash, offset, count); result = new GenericHashResult() { Success = true, Message = MessageDictionary.Instance["Hash.ComputeSuccess"], HashBytes = hash, HashString = Encoding.HighPerformanceHexadecimal.ToHexString(hash) }; } } catch (Exception ex) { return(new GenericHashResult() { Success = false, Message = ex.ToString() }); } return(result); }
public static void HandleHandshakeResponse(ClientObject client, byte[] messageData) { int protocolVersion; string playerName = ""; string playerPublicKey; byte[] playerChallangeSignature; string clientVersion = ""; string reason = ""; Regex regex = new Regex(@"[\""<>|$]"); // Regex to detect quotation marks, and other illegal characters //0 - Success HandshakeReply handshakeReponse = HandshakeReply.HANDSHOOK_SUCCESSFULLY; try { using (MessageReader mr = new MessageReader(messageData)) { protocolVersion = mr.Read <int>(); playerName = mr.Read <string>(); playerPublicKey = mr.Read <string>(); playerChallangeSignature = mr.Read <byte[]>(); clientVersion = mr.Read <string>(); try { client.compressionEnabled = mr.Read <bool>(); } catch { //This is safe to ignore. We want to tell people about version mismatches still. client.compressionEnabled = false; } } } catch (Exception e) { DarkLog.Debug("Error in HANDSHAKE_REQUEST from " + client.playerName + ": " + e); SendHandshakeReply(client, HandshakeReply.MALFORMED_HANDSHAKE, "Malformed handshake"); return; } if (regex.IsMatch(playerName)) { // Invalid username handshakeReponse = HandshakeReply.INVALID_PLAYERNAME; reason = "Invalid username"; } if (playerName.Contains("/") || playerName.Contains(@"\") || playerName.Contains("\n") || playerName.Contains("\r")) { handshakeReponse = HandshakeReply.INVALID_PLAYERNAME; reason = "Invalid username"; } if (protocolVersion != Common.PROTOCOL_VERSION) { //Protocol mismatch handshakeReponse = HandshakeReply.PROTOCOL_MISMATCH; reason = "Protocol mismatch"; } if (handshakeReponse == HandshakeReply.HANDSHOOK_SUCCESSFULLY) { //Check client isn't already connected ClientObject testClient = ClientHandler.GetClientByName(playerName); if (testClient != null) { Messages.Heartbeat.Send(testClient); Thread.Sleep(1000); } if (ClientHandler.ClientConnected(testClient)) { handshakeReponse = HandshakeReply.ALREADY_CONNECTED; reason = "Client already connected"; } } if (handshakeReponse == HandshakeReply.HANDSHOOK_SUCCESSFULLY) { bool reserveKick = false; //Check the client isn't using a reserved name if (playerName == "Initial") { reserveKick = true; } if (playerName == "Shared") { reserveKick = true; } if (playerName == Settings.settingsStore.consoleIdentifier) { reserveKick = true; } if (reserveKick) { handshakeReponse = HandshakeReply.RESERVED_NAME; reason = "Kicked for using a reserved name"; } } if (handshakeReponse == HandshakeReply.HANDSHOOK_SUCCESSFULLY) { //Check the client matches any database entry string storedPlayerFile = Path.Combine(Server.universeDirectory, "Players", playerName + ".txt"); string storedPlayerPublicKey = ""; if (File.Exists(storedPlayerFile)) { storedPlayerPublicKey = File.ReadAllText(storedPlayerFile); if (playerPublicKey != storedPlayerPublicKey) { handshakeReponse = HandshakeReply.INVALID_KEY; reason = "Invalid key for user"; } else { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024)) { rsa.PersistKeyInCsp = false; rsa.FromXmlString(playerPublicKey); bool result = rsa.VerifyData(client.challange, CryptoConfig.CreateFromName("SHA256"), playerChallangeSignature); if (!result) { handshakeReponse = HandshakeReply.INVALID_KEY; reason = "Public/private key mismatch"; } } } } else { try { File.WriteAllText(storedPlayerFile, playerPublicKey); DarkLog.Debug("Client " + playerName + " registered!"); } catch { handshakeReponse = HandshakeReply.INVALID_PLAYERNAME; reason = "Invalid username"; } } } client.playerName = playerName; client.publicKey = playerPublicKey; client.clientVersion = clientVersion; if (handshakeReponse == HandshakeReply.HANDSHOOK_SUCCESSFULLY) { if (BanSystem.fetch.IsPlayerNameBanned(client.playerName) || BanSystem.fetch.IsIPBanned(client.ipAddress) || BanSystem.fetch.IsPublicKeyBanned(client.publicKey)) { handshakeReponse = HandshakeReply.PLAYER_BANNED; reason = "You were banned from the server!"; } } if (handshakeReponse == HandshakeReply.HANDSHOOK_SUCCESSFULLY) { if (ClientHandler.GetActiveClientCount() >= Settings.settingsStore.maxPlayers) { handshakeReponse = HandshakeReply.SERVER_FULL; reason = "Server is full"; } } if (handshakeReponse == HandshakeReply.HANDSHOOK_SUCCESSFULLY) { if (Settings.settingsStore.whitelisted && !WhitelistSystem.fetch.IsWhitelisted(client.playerName)) { handshakeReponse = HandshakeReply.NOT_WHITELISTED; reason = "You are not on the whitelist"; } } if (handshakeReponse == HandshakeReply.HANDSHOOK_SUCCESSFULLY) { client.authenticated = true; string devClientVersion = ""; DMPPluginHandler.FireOnClientAuthenticated(client); if (client.clientVersion.Length == 40) { devClientVersion = client.clientVersion.Substring(0, 7); } else { devClientVersion = client.clientVersion; } DarkLog.Normal("Client " + playerName + " handshook successfully, version: " + devClientVersion); SendHandshakeReply(client, handshakeReponse, "success"); Server.playerCount = ClientHandler.GetActiveClientCount(); Server.players = ClientHandler.GetActivePlayerNames(); DarkLog.Debug("Online players is now: " + Server.playerCount + ", connected: " + ClientHandler.GetClients().Length); } else { DarkLog.Normal("Client " + playerName + " failed to handshake: " + reason); SendHandshakeReply(client, handshakeReponse, reason); } }
new static public SHA1 Create(String hashName) { return((SHA1)CryptoConfig.CreateFromName(hashName)); }
new static public Rijndael Create(String algName) { return((Rijndael)CryptoConfig.CreateFromName(algName)); }
private static byte[] getMD5Digest(String data) { Byte[] clearBytes = Encoding.Default.GetBytes(data); Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes); return(hashedBytes); }
public static string EncodePassword_Old(string cleanString, string salt) { byte[] bytes = Encoding.UTF8.GetBytes(salt.ToLower() + cleanString); byte[] value = ((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(bytes); return(BitConverter.ToString(value)); }
public static string getMD5(string sText) { Byte[] clearBytes = Encoding.Default.GetBytes(sText); Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes); return(BitConverter.ToString(hashedBytes)); }
public void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } if ((value.LocalName != XmlSignature.ElementNames.Reference) || (value.NamespaceURI != XmlSignature.NamespaceURI)) { throw new CryptographicException(); } id = GetAttribute(value, XmlSignature.AttributeNames.Id); uri = GetAttribute(value, XmlSignature.AttributeNames.URI); type = GetAttribute(value, XmlSignature.AttributeNames.Type); // Note: order is important for validations XmlNodeList xnl = value.GetElementsByTagName(XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI); if ((xnl != null) && (xnl.Count > 0)) { Transform t = null; foreach (XmlNode xn in xnl) { string a = GetAttribute((XmlElement)xn, XmlSignature.AttributeNames.Algorithm); /* This code is useful for debugging in VS.NET because using CryptoConfig * (from MS mscorlib) would throw InvalidCastException because it's * Transform would come from MS System.Security.dll not Mono's. * switch (a) { * case "http://www.w3.org/2000/09/xmldsig#base64": * t = new XmlDsigBase64Transform (); * break; * case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315": * t = new XmlDsigC14NTransform (); * break; * case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments": * t = new XmlDsigC14NWithCommentsTransform (); * break; * case "http://www.w3.org/2000/09/xmldsig#enveloped-signature": * t = new XmlDsigEnvelopedSignatureTransform (); * break; * case "http://www.w3.org/TR/1999/REC-xpath-19991116": * t = new XmlDsigXPathTransform (); * break; * case "http://www.w3.org/TR/1999/REC-xslt-19991116": * t = new XmlDsigXsltTransform (); * break; * case "http://www.w3.org/2002/07/decrypt#XML": * t = new XmlDecryptionTransform (); * break; * default: * throw new NotSupportedException (); * } */ t = (Transform)CryptoConfig.CreateFromName(a); if (t == null) { throw new CryptographicException("Unknown transform {0}.", a); } if (xn.ChildNodes.Count > 0) { t.LoadInnerXml(xn.ChildNodes); } AddTransform(t); } } // get DigestMethod DigestMethod = XmlSignature.GetAttributeFromElement(value, XmlSignature.AttributeNames.Algorithm, XmlSignature.ElementNames.DigestMethod); // get DigestValue XmlElement dig = XmlSignature.GetChildElement(value, XmlSignature.ElementNames.DigestValue, XmlSignature.NamespaceURI); if (dig != null) { DigestValue = Convert.FromBase64String(dig.InnerText); } element = value; }
public static new Streebog512 Create(string algorithmName) => (Streebog512)CryptoConfig.CreateFromName(algorithmName);