public async Task GetPrivateKeyAfterLockCorrectTest()
        {
            var ekey = new EncryptionKey(FakeDataGenerator.DefaultDto.BasicEncryptedMessage, "", true);

            ekey.LoadPassword(FakeDataGenerator.DefaultDto.BasicPassword);
            var key = ekey.GetEncryptedKey();

            Assert.Equal(FakeDataGenerator.DefaultDto.BasicMessage, key);
            ekey.Lock();
            var nkey = ekey.GetEncryptedKey();

            Assert.Null(nkey);
        }
Exemplo n.º 2
0
        public static async Task <(bool, string)> GetCode(string txid, EncryptionKey key)
        {
            var msg    = CreateMessage(txid);
            var signed = await ECDSAProvider.SignMessage(msg, key.GetEncryptedKey());

            return(signed);
        }
        /// <summary>
        /// Load account from "key.txt" file placed in the root exe directory. Doesnt work in WABS
        /// </summary>
        /// <param name="password">Passwotd to decrypt the loaded private key</param>
        /// <param name="filename">Filename with the key. Default name is dogekey.txt</param>
        /// <returns></returns>
        public async Task <bool> LoadAccount(string password, string filename = "dogekey.txt")
        {
            if (FileHelpers.IsFileExists(filename))
            {
                try
                {
                    var k    = FileHelpers.ReadTextFromFile(filename);
                    var kdto = JsonConvert.DeserializeObject <KeyDto>(k);

                    AccountKey = new EncryptionKey(kdto.Key, fromDb: true);
                    AccountKey.LoadPassword(password);
                    AccountKey.IsEncrypted = true;
                    Address = kdto.Address;

                    Secret   = new BitcoinSecret(AccountKey.GetEncryptedKey(), DogeTransactionHelpers.Network);
                    BAddress = Secret.GetAddress(ScriptPubKeyType.Legacy);

                    await StartRefreshingData();

                    return(true);
                }
                catch
                {
                    throw new Exception("Cannot deserialize key from file. Please check file key.txt or delete it for create new address!");
                }
            }
            else
            {
                await CreateNewAccount(password);
            }

            return(false);
        }
        public async Task LoadPrivateKeyCorrectTest()
        {
            var ekey = new EncryptionKey(FakeDataGenerator.DefaultDto.BasicEncryptedMessage, "", true);
            var key  = ekey.GetEncryptedKey(FakeDataGenerator.DefaultDto.BasicPassword);

            Assert.Equal(FakeDataGenerator.DefaultDto.BasicMessage, key);
        }
        /// <summary>
        /// This function will create new account - Doge address and its Private key.
        /// </summary>
        /// <param name="password">Input password, which will encrypt the Private key</param>
        /// <param name="saveToFile">if you want to save it to the file (dont work in the WASM) set this. It will save to root exe path as key.txt</param>
        /// <returns></returns>
        public async Task <bool> CreateNewAccount(string password, bool saveToFile = false)
        {
            try
            {
                await Task.Run(async() =>
                {
                    Key privateKey   = new Key(); // generate a random private key
                    PubKey publicKey = privateKey.PubKey;
                    BitcoinSecret privateKeyFromNetwork = privateKey.GetBitcoinSecret(DogeTransactionHelpers.Network);
                    var address = publicKey.GetAddress(ScriptPubKeyType.Legacy, DogeTransactionHelpers.Network);
                    Address     = address.ToString();

                    // todo load already encrypted key
                    AccountKey           = new Security.EncryptionKey(privateKeyFromNetwork.ToString(), password);
                    AccountKey.PublicKey = Address;
                    Secret   = privateKeyFromNetwork;
                    BAddress = Secret.GetAddress(ScriptPubKeyType.Legacy);

                    if (saveToFile)
                    {
                        // save to file
                        var kdto = new KeyDto()
                        {
                            Address = Address,
                            Key     = AccountKey.GetEncryptedKey(returnEncrypted: true)
                        };
                        FileHelpers.WriteTextToFile("dogekey.txt", JsonConvert.SerializeObject(kdto));
                    }
                });

                await StartRefreshingData();

                return(true);
            }
            catch (Exception ex)
            {
                await InvokeErrorEvent(ex.Message, "Cannot Create Account");
            }

            return(false);
        }
Exemplo n.º 6
0
        public void Update(EncryptionKey key)
        {
            if (string.IsNullOrEmpty(Id))
            {
                if (!string.IsNullOrEmpty(key.Id.ToString()))
                {
                    Id = key.Id.ToString();
                }
                else
                {
                    Id = Guid.NewGuid().ToString();
                }
            }

            IsEncrypted = key.IsEncrypted;
            StoredKey   = key.GetEncryptedKey(returnEncrypted: true);

            if (!string.IsNullOrEmpty(key.PublicKey))
            {
                PublicKey = key.PublicKey;
            }

            if (key.PasswordHash?.Length > 0)
            {
                PasswordHash = key.PasswordHash;
            }
            else
            {
                PasswordHash = null;
            }

            Name = key.Name;
            if (key.RelatedItemId != Guid.Empty)
            {
                RelatedItemId = key.RelatedItemId.ToString();
            }

            Type = (int)key.Type;

            if (!string.IsNullOrEmpty(key.Version))
            {
                Version = key.Version;
            }
            else
            {
                Version = "0.1";
            }
            ModifiedOn = DateTime.UtcNow;

            Deleted = (bool)key.Deleted;

            if (string.IsNullOrEmpty(ModifiedBy) && !string.IsNullOrEmpty(key.CreatedBy))
            {
                ModifiedBy = key.ModifiedBy;
            }
            else if (string.IsNullOrEmpty(ModifiedBy) && string.IsNullOrEmpty(key.ModifiedBy))
            {
                ModifiedBy = "admin";
            }

            if (string.IsNullOrEmpty(CreatedBy) && !string.IsNullOrEmpty(key.CreatedBy))
            {
                CreatedBy = key.CreatedBy;
            }
            else if (string.IsNullOrEmpty(CreatedBy) && string.IsNullOrEmpty(key.CreatedBy))
            {
                CreatedBy = "admin";
            }

            CreatedOn = key.CreatedOn;
        }
        public static async Task <DecryptedMessageResponseDto> DecryptMessage(GetDecryptedMessageDto data)
        {
            try
            {
                if (EconomyMainContext.Wallets.TryGetValue(data.walletId, out var wallet))
                {
                    if (string.IsNullOrEmpty(data.accountAddress))
                    {
                        throw new HttpResponseException((HttpStatusCode)501, $"Cannot decrypt message, account address cannot be empty!");
                    }

                    if (wallet.Accounts.TryGetValue(data.accountAddress, out var account))
                    {
                        var msgtok = await NeblioTransactionHelpers.TokenMetadataAsync(TokenTypes.NTP1, EconomyMainContext.MessagingToken.Id, data.TxId);

                        if (string.IsNullOrEmpty(msgtok.TxId))
                        {
                            throw new Exception("Cannot decrypt message - Cannot find message token data by provided TxId!");
                        }

                        EncryptionKey key = null;

                        IToken prepretoken = null;
                        if (msgtok.Metadata.TryGetValue("InitMessage", out var prevmsginit))
                        {
                            if (prevmsginit != "true")
                            {
                                if (msgtok.Metadata.TryGetValue("PrevTxId", out var prevtxid))
                                {
                                    prepretoken = await NeblioTransactionHelpers.TokenMetadataAsync(TokenTypes.NTP1, TokenId, prevtxid);

                                    if (string.IsNullOrEmpty(prepretoken.TxId))
                                    {
                                        throw new Exception("Cannot send message - Cannot find pre-previous message token metadata and previous message is not init message!");
                                    }
                                }
                                else
                                {
                                    throw new Exception("Cannot send message - Cannot find pre-previous message token metadata and previous message is not init message!");
                                }
                            }
                        }

                        if (msgtok.Metadata.TryGetValue("MessageData", out var prevmsgdatafromMeta))
                        {
                            if (prepretoken != null)
                            {
                                if (prepretoken.MetadataAvailable)
                                {
                                    if (prepretoken.Metadata.TryGetValue("SenderPubKey", out var preprevtokenReceiverKey))
                                    {
                                        var accEncKey = account.AccountKeys.FirstOrDefault(k => k.PublicKey == preprevtokenReceiverKey);
                                        if (accEncKey != null)
                                        {
                                            key = accEncKey;
                                        }
                                    }
                                }
                            }
                        }

                        var resp = new DecryptedMessageResponseDto();

                        if (key != null)
                        {
                            if (msgtok.MetadataAvailable)
                            {
                                if (msgtok.Metadata.TryGetValue("PreviousMessage", out var prevmsg))
                                {
                                    try
                                    {
                                        resp.PrevMsg = AsymmetricProvider.DecryptString(prevmsg, key.GetEncryptedKey(data.Password));
                                    }
                                    catch (Exception ex)
                                    {
                                        ;//todo
                                    }
                                }
                                if (msgtok.Metadata.TryGetValue("MessageData", out var newvmsg))
                                {
                                    try
                                    {
                                        resp.NewMsg = AsymmetricProvider.DecryptString(newvmsg, key.GetEncryptedKey(data.Password));
                                    }
                                    catch (Exception ex)
                                    {
                                        ;//todo
                                    }
                                }
                            }

                            return(resp);
                        }
                        else
                        {
                            throw new Exception("Cannot decrypt message - Key does not exists!");
                        }
                    }
                    else
                    {
                        throw new HttpResponseException((HttpStatusCode)501, $"Cannot decrypt message, Account Not Found!");
                    }
                }
                else
                {
                    throw new HttpResponseException((HttpStatusCode)501, $"Cannot decrypt message, Wallet Not Found!");
                }
            }
            catch (Exception ex)
            {
                log.Error("Cannot decrypt message!", ex);
                throw new HttpResponseException((HttpStatusCode)501, $"Cannot decrypt messagen!");
            }
        }