public async void ShouldDoFullValidation()
        {
            var owner               = new Nethereum.Web3.Accounts.Account("0xb1939d6c8c73d6aa5ad97873c2f99a2dfc2b4c356acfd5338caff20392d7960d");
            var signer              = new Nethereum.Web3.Accounts.Account("0xa83369462189d7cc3d2aed78614d0df89f4d9651770fef9fc64b05acf7464a7f");
            var guardian            = new Nethereum.Web3.Accounts.Account("0xa0f2dd3adc8b79603f92736ac50843f1c5344514505b042369efdab105e9442b");
            var immunityCertificate = new ImmunityCertificate();

            immunityCertificate.OwnerAddress  = owner.Address;
            immunityCertificate.SignerAddress = signer.Address;
            immunityCertificate.TestKitId     = "TestKit1";
            immunityCertificate.PhotoId       = "QmbtqAxAnEqumx9k8wx8yxyANpC5vVwvQsdSWUQof9NP2o".DecodeBase58();
            immunityCertificate.TestCentreId  = "100";
            immunityCertificate.Guardians     = new System.Collections.Generic.List <string> {
                guardian.Address
            };
            immunityCertificate.SetExpiryDate(DateTime.Now.AddDays(1000));

            var signature = new EthereumMessageSigner().Sign(immunityCertificate.GetHashCertificate(), new EthECKey(signer.PrivateKey));


            var signedCertificate = new SignedImmunityCertificate(immunityCertificate, signature);

            var web3 = _ethereumClientIntegrationFixture.GetWeb3();

            //admin deployer
            var account = AccountFactory.GetAccount();
            //simple deployment
            //var web3 = new Nethereum.Web3.Web3(new Nethereum.Web3.Accounts.Account("0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7"), "https://ropsten.infura.io/v3/7238211010344719ad14a89db874158c");
            var tokenService = await Covid19CertificationService.DeployContractAndGetServiceAsync(web3, new Covid19CertificationDeployment());

            var address = tokenService.ContractHandler.ContractAddress;
            //Add Test Centre
            var receiptAddTestCentre = await tokenService.UpsertTestCentreRequestAndWaitForReceiptAsync(new TestCentre()
            {
                TestCentreId = "100", Invalid = false
            });

            //Add Test Centre Owner
            var receiptAddTestCentreOwner = await tokenService.UpsertTestCentreOwnerRequestAndWaitForReceiptAsync("100".ToUTF8Bytes(), account.Address, true);

            //Add Test Centre Certificate Signer
            var receiptAddTestCentreSigner = await tokenService.UpsertTestCentreCertSignerRequestAndWaitForReceiptAsync(new TestCentreCertSigner()
            {
                TestCentreId = "100", SignerAddress = signer.Address, Invalid = false, ExpiryDate = 0
            });


            var challenge       = "testtest";
            var challengeSigner = new EthereumMessageSigner();
            var signatureOwner  = challengeSigner.EncodeUTF8AndSign(challenge, new EthECKey(owner.PrivateKey));

            var certificateText = signedCertificate.GenerateFullCertificate();

            Assert.True(await tokenService.FullVerificationCertificateChallengeWithSignatureQueryAsync(signedCertificate, challenge, signatureOwner.HexToByteArray(), DateTimeOffset.Now.ToUnixTimeSeconds()));


            var signatureGuardian = challengeSigner.EncodeUTF8AndSign(challenge, new EthECKey(guardian.PrivateKey));

            Assert.True(await tokenService.FullVerificationCertificateChallengeWithSignatureQueryAsync(signedCertificate, challenge, signatureGuardian.HexToByteArray(), DateTimeOffset.Now.ToUnixTimeSeconds()));
        }
示例#2
0
        internal static string GetAddressSignature(string privateKey, ECurrency currency, Environment environment)
        {
            if (string.IsNullOrWhiteSpace(privateKey))
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            string timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            string signature = null;

            if (currency == ECurrency.BTC)
            {
                BitcoinSecret secret = new BitcoinSecret(privateKey, environment.Network);
                signature = secret.PrivateKey.SignMessage(timestamp);
            }
            else if (currency.IsGluwaCoinCurrency())
            {
                var signer = new EthereumMessageSigner();
                signature = signer.EncodeUTF8AndSign(timestamp, new EthECKey(privateKey));
            }
            else
            {
                throw new ArgumentOutOfRangeException($"Unsupported currency: {currency}");
            }

            string signatureToEncode = $"{timestamp}.{signature}";

            byte[] signatureByte = Encoding.UTF8.GetBytes(signatureToEncode);
            string encodedData   = Convert.ToBase64String(signatureByte);

            return(encodedData);
        }
示例#3
0
        static async Task SigningMessage()
        {
            try
            {
                // Setup
                var url        = "http://127.0.0.1:8502";
                var privateKey = "0x82E41304BB1E81A848BFC705CB06FEDB0554A9906744EB225820A3CF3CF40A79";
                var account    = new Account(privateKey);
                var web3       = new Web3(account, url);
                // An already-deployed SimpleStorage.sol contract on Rinkeby:
                var contractAddress = "0xcf5636b4c062262b52e00455b04b1c89d3c04d11";
                var service         = new StorageService(web3, contractAddress);

                //Signing
                var msg1    = "wee test message 18/09/2017 02:55PM";
                var signer1 = new EthereumMessageSigner();
                var ethKey  = new EthECKey(privateKey);

                var signature1 = signer1.EncodeUTF8AndSign(msg1, ethKey);
                Console.WriteLine($"Signature: {signature1}");
                Console.WriteLine($"Public address from Key: {ethKey.GetPublicAddress()}");
                //get accounts addresses
                var accounts = await web3.Eth.Accounts.SendRequestAsync();

                Console.WriteLine($"Public address from eth Accounts: {accounts[0]}");
                //Recover signature
                var addressRec1 = signer1.EncodeUTF8AndEcRecover(msg1, signature1);
                Console.WriteLine($"Recovered address from signature: {addressRec1}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
示例#4
0
        public void ShouldBuildANewMessageWithANewNonceAndValidateAfterSigning_UsingInMemoryNonceManagement()
        {
            var domain      = "login.xyz";
            var address     = "0x12890d2cce102216644c59daE5baed380d84830c";
            var statement   = "Sign-In With Ethereum Example Statement";
            var uri         = "https://login.xyz";
            var chainId     = "1";
            var siweMessage = new SiweMessage();

            siweMessage.Domain    = domain;
            siweMessage.Address   = address;
            siweMessage.Statement = statement;
            siweMessage.Uri       = uri;
            siweMessage.ChainId   = chainId;
            siweMessage.SetExpirationTime(DateTime.Now.ToUniversalTime().AddHours(1));
            var service       = new SiweMessageService(new InMemoryStorageSessionNonceManagement());
            var message       = service.BuildMessageToSign(siweMessage);
            var messageSigner = new EthereumMessageSigner();
            var signature     = messageSigner.EncodeUTF8AndSign(message,
                                                                new EthECKey("0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7"));

            siweMessage.Signature = signature;
            Assert.True(service.HasMessageDateStartedAndNotExpired(siweMessage));
            Assert.True(service.IsMessageSessionNonceValid(siweMessage));
            Assert.True(service.IsMessageSignatureValid(siweMessage));
            Assert.True(service.IsValidMessage(siweMessage));
        }
        public async void ShouldInValidateChallengeNotValidCertificateSignature()
        {
            var incorrectowner = new Nethereum.Web3.Accounts.Account("0xb1939d6c8c73d6aa5ad97873c2f99a2dfc2b4c356acfd5338caff20392d7960d");
            var signer         = new Nethereum.Web3.Accounts.Account("0xa83369462189d7cc3d2aed78614d0df89f4d9651770fef9fc64b05acf7464a7f");
            //var guardian = new Nethereum.Web3.Accounts.Account("0xa0f2dd3adc8b79603f92736ac50843f1c5344514505b042369efdab105e9442b");
            var immunityCertificate = new ImmunityCertificate();

            immunityCertificate.OwnerAddress  = signer.Address; //owner is the signer so the ow
            immunityCertificate.SignerAddress = signer.Address;
            immunityCertificate.TestKitId     = "TestKit1";
            immunityCertificate.PhotoId       = "QmbtqAxAnEqumx9k8wx8yxyANpC5vVwvQsdSWUQof9NP2o".DecodeBase58();
            immunityCertificate.TestCentreId  = "100";
            // no guardians
            // immunityCertificate.Guardians = new System.Collections.Generic.List<string> { guardian.Address };
            immunityCertificate.SetExpiryDate(DateTime.Now.AddDays(1000));

            var signature = new EthereumMessageSigner().Sign(immunityCertificate.GetHashCertificate(), new EthECKey(signer.PrivateKey));


            var signedCertificate = new SignedImmunityCertificate(immunityCertificate, signature);

            var web3 = _ethereumClientIntegrationFixture.GetWeb3();

            var tokenService = await Covid19CertificationService.DeployContractAndGetServiceAsync(web3, new Covid19CertificationDeployment());

            var challenge       = "testtest";
            var challengeSigner = new EthereumMessageSigner();
            var signatureOwner  = challengeSigner.EncodeUTF8AndSign(challenge, new EthECKey(incorrectowner.PrivateKey));

            Assert.False(await tokenService.VerifyCertificateChallengeSignatureQueryAsync(signedCertificate, challenge, signatureOwner.HexToByteArray()));
        }
        public Task <string> SignMessageAsync(string message)
        {
            Ensure.ArgumentCondition(!string.IsNullOrEmpty(message), "message cannot be null", nameof(message));
            var signer        = new EthereumMessageSigner();
            var signedMessage = signer.EncodeUTF8AndSign(message, new EthECKey(((Web3.Accounts.Account)Account).PrivateKey));

            return(Task.FromResult(signedMessage));
        }
        protected async Task SignMessage()
        {
            var signer1    = new EthereumMessageSigner();
            var key        = new EthECKey(PrivateKey);
            var signature1 = signer1.EncodeUTF8AndSign(Message, key);

            SignedMessage  = signature1;
            AccountAddress = key.GetPublicAddress();
        }
        public async Task <string> GenerateChallengeResponseAsync(string challenge)
        {
            var privateKey = await _secureStorageService.GetPrivateKeyAsync();

            var fullCertificate = await _secureStorageService.GetFullCertificateAsync();

            var signature = _ethereumMessageSigner.EncodeUTF8AndSign(Prefix + challenge, new EthECKey(privateKey));

            return(fullCertificate + ResponseSeparator + signature);
        }
示例#9
0
        public void ShouldSignAndVerifyEncodingMessageAsUTF8()
        {
            var address    = "0x12890d2cce102216644c59dae5baed380d84830c";
            var msg        = "wee test message 18/09/2017 02:55PM";
            var privateKey = "0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7";
            var signer     = new EthereumMessageSigner();
            var signature  = signer.EncodeUTF8AndSign(msg, new EthECKey(privateKey));
            var addressRec = signer.EncodeUTF8AndEcRecover(msg, signature);

            Assert.Equal(address.ToLower(), addressRec.ToLower());
        }
示例#10
0
        private string getTimestampSignature(string privateKey)
        {
            var    signer    = new EthereumMessageSigner();
            string Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();
            string signature = signer.EncodeUTF8AndSign(Timestamp, new EthECKey(privateKey));

            string gluwaSignature = $"{Timestamp}.{signature}";

            byte[] gluwaSignatureByte = Encoding.UTF8.GetBytes(gluwaSignature);
            string encodedData        = System.Convert.ToBase64String(gluwaSignatureByte);

            return(encodedData);
        }
示例#11
0
        public string SignMessage(string aMessage, string aPublicAddress)
        {
            if (!FAddresses.Any())
            {
                GetAddress(0);
                GetAddress(1);
            }
            if (!FAddresses.TryGetValue(aPublicAddress.ToLowerInvariant(), out long lIndex))
            {
                throw new ArgumentException("No private key found for provided address");
            }
            var lPrivateKey = GetPrivateKey(lIndex);
            var lSigner     = new EthereumMessageSigner();

            return(lSigner.EncodeUTF8AndSign(aMessage, new EthECKey(lPrivateKey)));
        }
        //                                      FREE RODRIGO
        public void SignMsg()
        {
            //var privateKey = "0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7";

            //who send the message
            string privateKey = FCryptoCurrencyAdvocacy.GetPrivateKey(1);

            if (this.Fmsg == null)
            {
                Fmsg = "Testing signature message";
            }

            var signer1    = new EthereumMessageSigner();
            var signature1 = signer1.EncodeUTF8AndSign(this.Fmsg, new EthECKey(privateKey));

            //verify msg
            var addressRec1 = signer1.EncodeUTF8AndEcRecover(this.Fmsg, signature1);
        }
示例#13
0
        public void ShouldVerifySignatureEncodingMessageAsUTF8()
        {
            var address    = "0x12890d2cce102216644c59dae5baed380d84830c";
            var msg        = "Hello from Nethereum";
            var privateKey = "0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7";

            var signer = new EthereumMessageSigner();

            var signature = signer.EncodeUTF8AndSign(msg, new EthECKey(privateKey));

            var signatureExpected =
                "0xe20e42c13fbf52a5d65229f4dd1dcd3255691166ce2852456631baf4836afd4630480609a76794ee3018c5514ee3a0592031cf2490e7356dffe4ed202606f5181c";

            Assert.Equal(signatureExpected, signature);

            var addressRec = signer.EncodeUTF8AndEcRecover(msg, signatureExpected);

            Assert.Equal(address.ToLower(), addressRec.ToLower());
        }
示例#14
0
        /// <summary>
        ///
        /// After running an instance of the Wonka engine, this method will:
        ///
        /// 1.) Persist all data to files (metadata, rules, current data, report), zip the files, and then upload the .ZIP to IPFS
        /// 2.) Create the hash of the Zip file
        /// 3.) Create an entry on the ChronoLog contract (including the IPFS URL and hash of the Zip file)
        ///
        /// <param name="poEngine">The instance of the Wonka engine that has just run a RuleTree</param>
        /// <param name="poEngineInitProps">Various properties of this instance of the Wonka engine</param>
        /// <param name="poRecord">This record holds the current snapshot of the data being addressed by the metadata (mentioned in WonkaRefEnvironment)</param>
        /// <param name="poReport">This report holds the verbose results of running the RuleTree</param>
        /// <param name="psIpfsUrl">This URL points to the IPFS node that acts as the read-only gateway</param>
        /// <param name="psWriteIpfsUrl">This URL points to the IPFS node that will be used to upload the Zip file of the results</param>
        /// <param name="psChronoLogContractAddr">This address points to an instance of the ChronoLog contract</param>
        /// <returns>Unique name for entry in the ChronoLog contract</returns>
        /// </summary>
        public static async Task <string> StoreWonkaResultsAsync(this WonkaBizRulesEngine poEngine,
                                                                 Wonka.Eth.Init.WonkaEthEngineInitialization poEngineInitProps,
                                                                 WonkaProduct poRecord,
                                                                 Wonka.Eth.Extensions.RuleTreeReport poReport,
                                                                 string psIpfsUrl,
                                                                 string psWriteIpfsUrl,
                                                                 string psChronoLogContractAddr)
        {
            var RefEnv = WonkaRefEnvironment.GetInstance();

            var signer     = new EthereumMessageSigner();
            var prodMsgXml = new WonkaProductMsgWriter().WriteWonkaMsg(new WonkaProductMessage(poRecord, true));

            var inputSignature
                = signer.EncodeUTF8AndSign(prodMsgXml, new EthECKey(poEngineInitProps.EthPassword));

            string sUniqueChronoLogName = "WI-" + DateTime.Now.ToUniversalTime().ToEpochTime();

            string sZipIpfsUrl =
                await poEngine.UploadInvocationAsync(poEngineInitProps, poRecord, poReport, psIpfsUrl, psWriteIpfsUrl, sUniqueChronoLogName).ConfigureAwait(false);

            var addChronoLogEventFunction =
                new Wonka.Eth.Autogen.ChronoLog.AddChronoLogEventFunction()
            {
                UniqueName = sUniqueChronoLogName,
                EType      = "WONKA_INVOKE",
                Desc       = "", // Empty for now
                Data       = "", // Empty for now
                Hash       = inputSignature,
                Url        = sZipIpfsUrl
            };

            string sTrxHash =
                await poReport.WriteToChronoLog(poEngineInitProps, psChronoLogContractAddr, addChronoLogEventFunction).ConfigureAwait(false);

            return(sUniqueChronoLogName);
        }
示例#15
0
        public string SignPayload(string payload, string privateKey)
        {
            var sign = _signer.EncodeUTF8AndSign(payload, new EthECKey(privateKey));

            return(sign.RemoveHexPrefix());
        }
示例#16
0
        public string EncodeUTF8AndSign(string privateKey, string message)
        {
            var key = new EthECKey(privateKey);

            return(_signer.EncodeUTF8AndSign(message, key));
        }
示例#17
0
        public async Task <string> SignPayloadAsync(string payload)
        {
            var sign = _signer.EncodeUTF8AndSign(payload, new EthECKey(_privateSigningKey));

            return(sign.RemoveHexPrefix());
        }
示例#18
0
        public string SignMessage(string message, string privateKey)
        {
            var signer = new EthereumMessageSigner();

            return(signer.EncodeUTF8AndSign(message, new EthECKey(privateKey)));
        }