DotNet encryption-Digital Signature and dotnet Digital Signature
I am about to return to the village soon. There is no wifi in the village, No 4G traffic, and no traffic. More importantly, I have to sell my computer and change my ticket in a few days. I have to write a few blogs.
Public byte [] SignData (Stream inputStream, object halg) {int calgHash = Utils. objToAlgId (halg, OidGroup. hashAlgorithm); return this. signHash (Utils. objToHashAlgorithm (halg ). computeHash (inputStream), calgHash );}
This method has three overload methods. The first parameter of the three overload methods is different, namely Stream and byte. The Code shows that this method accepts two parameters. inputStream is the input data for calculating its hash value, and halg is used to create a hash algorithm. SignHash () uses the private key to encrypt it to calculate the signature of the specified hash value.
(2). VerifyData (): use the provided public key to determine the hash value in the signature and compare it with the hash value of the provided data to verify whether the digital signature is valid.
public bool VerifyData(byte[] buffer, object halg, byte[] signature) { int calgHash = Utils.ObjToAlgId(halg, OidGroup.HashAlgorithm); return this.VerifyHash(Utils.ObjToHashAlgorithm(halg).ComputeHash(buffer), calgHash, signature); }
This method does not have an overloaded version. The source code shows that this method receives three parameters: buffer signed data, and halg is used to create the hash algorithm name of the Data hash value, the signature data to be verified by signature. This method returns a boolean type. If the signature is valid, the value is true; otherwise, the value is false. VerifyHash () uses the provided public key to determine the hash value in the signature and compare it with the provided hash value to verify whether the digital signature is valid.
2. Analysis of DSA class:
(1). CreateSignature (): Create the Cryptography. DSA Signature for the specified data.
public abstract byte[] CreateSignature(byte[] rgbHash);
This method is an abstract method that is rewritten in a derived class. It accepts a byte array to indicate the data to be signed and returns the digital signature of the specified data. When using the CreateSignature method, you must create your own SHA-1 hash code to return a DSA Signature represented by a byte array.
(2). VerifySignature (): verifies the Cryptography. DSA Signature of the specified data.
public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature);
This method is verified by the SHA-1 hash code and signature represented by the character array.
3. DSACryptoServiceProvider class parsing:
(1). ImportParameters (): import the specified DSAParameters. This method accepts the parameter Cryptography. DSA.
(2). VerifyData (): verifies the specified signature data by comparing the specified signature data with the signature calculated for the specified data.
public bool VerifyData(byte[] rgbData, byte[] rgbSignature) { return this.VerifyHash(this._sha1.ComputeHash(rgbData), (string) null, rgbSignature); }
This method accepts two parameters: rgbData signed data; rgbSignature: true if the signature is valid; otherwise, false. VerifyHash () compares the specified signature data with the signature calculated for the specified hash value to verify the specified signature data. Let's take a look at the VerifyHash () implementation code:
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { if (rgbHash == null) throw new ArgumentNullException("rgbHash"); if (rgbSignature == null) throw new ArgumentNullException("rgbSignature"); int calgHash = X509Utils.NameOrOidToAlgId(str, OidGroup.HashAlgorithm); if (rgbHash.Length != this._sha1.HashSize / 8) { string key = "Cryptography_InvalidHashSize"; object[] objArray = new object[2]; int index1 = 0; string str1 = "SHA1"; objArray[index1] = (object) str1; int index2 = 1; // ISSUE: variable of a boxed type __Boxed<int> local = (ValueType) (this._sha1.HashSize / 8); objArray[index2] = (object) local; throw new CryptographicException(Environment.GetResourceString(key, objArray)); } this.GetKeyPair(); return Utils.VerifySign(this._safeKeyHandle, 8704, calgHash, rgbHash, rgbSignature); }
This method receives three parameters: the hash value of the data to be signed by rgbHash, the hash algorithm name used by str to create the hash value of the data, and the signature data to be verified by rgbSignature.
4. parsing the X509Certificate class:
This class is available in the space of System. Security. Cryptography. X509Certificates to help you use X.509 v.3 certificates.
(1). LoadCertificateFromBlob (): Load certificate:
private void LoadCertificateFromBlob(byte[] rawData, object password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyOrNullArray"), "rawData"); if (X509Utils.MapContentType(X509Utils._QueryCertBlobType(rawData)) == X509ContentType.Pfx && (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) new KeyContainerPermission(KeyContainerPermissionFlags.Create).Demand(); uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags); IntPtr num = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { num = X509Utils.PasswordToHGlobalUni(password); X509Utils._LoadCertFromBlob(rawData, num, dwFlags, (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) != X509KeyStorageFlags.DefaultKeySet, ref this.m_safeCertContext); } finally { if (num != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(num); } }
This method is used to load the certificate using the X509Certificate class constructor and other methods.
(2). Export (): Use the specified format and password to Export the current X509Certificate object to the byte array.
public virtual byte[] Export(X509ContentType contentType, SecureString password) { return this.ExportHelper(contentType, (object) password); }
This method accepts two parameters. contentType describes how to set one of the X509ContentType values of the output data format. Password: the password required to access X.509 certificate data. Returns the byte array of the current X509Certificate object.
4. DotNet digital signature instance:
The following is an example of an X509Certificate operation method:
public void EncryptXmlDocument(string arqXmlAssinar, string tagAssinatura, string tagAtributoId, X509Certificate2 x509Cert) { StreamReader sr = null; try { sr = System.IO.File.OpenText(arqXmlAssinar); var xmlString = sr.ReadToEnd(); sr.Close(); sr = null; XmlDocument doc = new XmlDocument { PreserveWhitespace = false }; doc.LoadXml(xmlString); if (doc.GetElementsByTagName(tagAssinatura).Count == 0) { throw new Exception(tagAssinatura.Trim()); } if (doc.GetElementsByTagName(tagAtributoId).Count == 0) { throw new Exception(tagAtributoId.Trim()); } XmlNodeList lists = doc.GetElementsByTagName(tagAssinatura); foreach (XmlNode nodes in lists) { foreach (XmlNode childNodes in nodes.ChildNodes) { if (!childNodes.Name.Equals(tagAtributoId)) continue; if (childNodes.NextSibling != null && childNodes.NextSibling.Name.Equals("Signature")) continue; Reference reference = new Reference { Uri = "" }; XmlElement childElemen = (XmlElement)childNodes; if (childElemen.GetAttributeNode("Id") != null) { var attributeNode = childElemen.GetAttributeNode("Id"); if (attributeNode != null) reference.Uri = "#" + attributeNode.Value; } else if (childElemen.GetAttributeNode("id") != null) { var attributeNode = childElemen.GetAttributeNode("id"); if (attributeNode != null) reference.Uri = "#" + attributeNode.Value; } XmlDocument documentoNovo = new XmlDocument(); documentoNovo.LoadXml(nodes.OuterXml); SignedXml signedXml = new SignedXml(documentoNovo) { SigningKey = x509Cert.PrivateKey }; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); XmlDsigC14NTransform c14 = new XmlDsigC14NTransform(); reference.AddTransform(c14); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(x509Cert)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml();nodes.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); } } var xmlDoc = doc; var stringXmlAssinado = xmlDoc.OuterXml; StreamWriter sw2 = System.IO.File.CreateText(arqXmlAssinar); sw2.Write(stringXmlAssinado); sw2.Close(); } catch (CryptographicException ex) { throw new CryptographicException(ex.Message); } catch (Exception e) { throw new Exception(e.Message); } finally { if (sr != null) sr.Close(); } }
V. Summary:
The above is related. A Brief Introduction to the. NET digital certificate. If something is wrong, I still hope to forgive me. In this blog, there are not many classes and methods listed, if you are interested, you can go deep into it. When we learn a knowledge, we have learned from the knowledge structure, which helps us to think about problems globally.