Exemple #1
0
        public void ComputeSignature(IMac macAlg)
        {
            if (macAlg == null)
            {
                throw new ArgumentNullException(nameof(macAlg));
            }

            if (!(macAlg is HMac))
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch);
            }

            int signatureLength;

            if (MSignature.SignedInfo.SignatureLength == null)
            {
                signatureLength = macAlg.GetMacSize() * 8;
            }
            else
            {
                signatureLength = Convert.ToInt32(MSignature.SignedInfo.SignatureLength, null);
            }
            if (signatureLength < 0 || signatureLength > macAlg.GetMacSize() * 8)
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength);
            }
            if (signatureLength % 8 != 0)
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2);
            }

            ReferenceManager.BuildDigestedReferences(this);

            var algorithmName       = macAlg.AlgorithmName.Substring(0, macAlg.AlgorithmName.IndexOf('/')).ToUpperInvariant();
            var signedXmlDictionary = new Dictionary <string, NS>()
            {
                { "SHA-1", NS.XmlDsigHMACSHA1Url },
                { "SHA-256", NS.XmlDsigMoreHMACSHA256Url },
                { "SHA-384", NS.XmlDsigMoreHMACSHA384Url },
                { "SHA-512", NS.XmlDsigMoreHMACSHA512Url },
                { "MD5", NS.XmlDsigMoreHMACMD5Url },
                { "RIPEMD160", NS.XmlDsigMoreHMACRIPEMD160Url }
            };

            try
            {
                SignedInfo.SignatureMethod = XmlNameSpace.Url[signedXmlDictionary[algorithmName]];
            }
            catch (Exception)
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch);
            }

            CheckSignatureManager.GetC14NDigest(new MacHashWrapper(macAlg), this);
            byte[] hashValue = new byte[macAlg.GetMacSize()];
            macAlg.DoFinal(hashValue, 0);

            SignedXmlDebugLog.LogSigning(this, macAlg);
            MSignature.SetSignatureValue(new byte[signatureLength / 8]);
            Buffer.BlockCopy(hashValue, 0, MSignature.GetSignatureValue(), 0, signatureLength / 8);
        }