示例#1
0
        /// <summary>
        /// Use this to sign a <see cref="ProtocolMessage"/> before sending it.
        /// If a signature was found on the message, this will error.
        /// </summary>
        /// <param name="protocolMessage">The message that needs to be signed.</param>
        /// <param name="keySigner">An instance of <see cref="IKeySigner"/> used to build the signature.</param>
        /// <param name="signingContext">The context used to sign the message.</param>
        public static ProtocolMessage Sign(this ProtocolMessage protocolMessage,
                                           IKeySigner keySigner,
                                           SigningContext signingContext)
        {
            if ((protocolMessage.Signature?.RawBytes.Length ?? 0) == keySigner.CryptoContext.SignatureLength)
            {
                Logger.Debug("The protocol message was already signed, returning a clone.");
                return(protocolMessage.Clone());
            }

            protocolMessage.Signature = null;
            var signatureBytes = keySigner.Sign(protocolMessage.ToByteArray(),
                                                signingContext).SignatureBytes;
            var signature = new Signature
            {
                SigningContext = signingContext,
                RawBytes       = signatureBytes.ToByteString()
            };

            protocolMessage.Signature = signature;
            return(protocolMessage);
        }