Example #1
0
        private async Task <string> SignIfRequiredAsync <T>(T response)
        {
            string payload = HelperTools.JSONSerialize(response, false);

            if (minerId == null)
            {
                // Do not sign if we do not have miner id
                return(payload);
            }

            lastMinerId ??= await minerId.GetCurrentMinerIdAsync();

            async Task <JsonEnvelope> TryToSign()
            {
                async Task <(string signature, string publicKey)> signWithMinerId(string sigHashHex)
                {
                    var signature = await minerId.SignWithMinerIdAsync(lastMinerId, sigHashHex);

                    return(signature, lastMinerId);
                }

                var envelope = await JsonEnvelopeSignature.CreateJSonSignatureAsync(payload, signWithMinerId);

                // Verify a signature - some implementation might have incorrect race conditions when rotating the keys
                if (!JsonEnvelopeSignature.VerifySignature(envelope))
                {
                    return(null);
                }

                return(envelope);
            }

            var jsonEnvelope = await TryToSign();

            if (jsonEnvelope == null)
            {
                throw new Exception("Error while validating signature. Possible reason: incorrect configuration or key rotation");
            }
            return(HelperTools.JSONSerialize(new SignedPayloadViewModel(jsonEnvelope), true));
        }
        /// <summary>
        /// Signs response if required. If response already contains minerId (for example as part of policy quote), pass it in as currentMinerId
        /// To make sure that correct key is used even key rotation just occured
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response"></param>
        /// <param name="responseMinerId"></param>
        /// <returns></returns>
        async Task <ActionResult> SignIfRequiredAsync <T>(T response, string responseMinerId)
        {
            string payload = HelperTools.JSONSerialize(response, false);

            if (string.IsNullOrEmpty(responseMinerId))
            {
                // Do not sing if we do not have miner id
                return(Ok(new JSONEnvelopeViewModel(payload)));
            }


            async Task <(string signature, string publicKey)> SignWithMinerId(string sigHashHex)
            {
                var signature = await minerId.SignWithMinerIdAsync(responseMinerId, sigHashHex);

                return(signature, responseMinerId);
            }

            var jsonEnvelope = await JsonEnvelopeSignature.CreateJSonSignatureAsync(payload, SignWithMinerId);

            var ret = new SignedPayloadViewModel(jsonEnvelope);

            return(Ok(ret));
        }