Convert Javascript HMAC to C# - c#

hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secret_buffer);
hmac.update(path, secret_buffer);
var Sign= hmac.finalize();
var signature = base64_encode(Sign);
Already Tried with C# as like but unable to get the same answer
var key1 = sha1.ComputeHash(Encoding.UTF8.GetBytes("Test"));
var key2 = key1.Concat(Encoding.UTF8.GetBytes("Test"));
var key3 = sha1.ComputeHash(key2);
var hmac= Convert.ToBase64String(key3);
Please give some solution ?

Your JS code is equivalent to the following code (assuming that your base64_encode() method is implemented correctly):
var secret_buffer = "secret";
var path = "text";
signature = CryptoJS.HmacSHA256(path, secret_buffer).toString(CryptoJS.enc.Base64);
console.log(signature);
In ะก#, the equivalent would be:
string secret_buffer = "secret";
string path = "text";
using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret_buffer)))
{
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(path));
var signature = Convert.ToBase64String(hash);
Console.WriteLine(signature);
}

Related

How to get Bitcoin Private Key from an ExtPrivKey using NBitcoin

So, I am trying to send some money over using NBitcoin, there is a step where i am failing and that is creating de bitcoin secret to sign the transaction, I have the address, and the ExtPrivKey but i haven't gotten any luck signing it, any recommendation, this is my code below.
var priv = mbwallet.SelectedWallet.PrivateKeys[0].ToWif();
//var ool = new BitcoinSecret(base58, App.Network);
var privkey = mbwallet.SelectedWallet.PrivateKeys[0].PrivateKey.GetBitcoinSecret(App.Network).ToWif();
var key = Key.Parse(privkey, App.Network);
var keysT = key.GetWif(App.Network);
//var myaddress = mbwallet.SelectedWallet.PrivateKeys[0].PrivateKey.PubKey.GetAddress(App.Network);
var myaddress = mbwallet.SelectedWallet.CurrentAddress;
string address = Address.Text;
var destination = BitcoinAddress.Create(address, App.Network);
decimal value = Convert.ToDecimal(Value.Text);
var coins2 = GetCoins(value);
TransactionBuilder txBuilder = new TransactionBuilder();
var tx = txBuilder.AddCoins(coins2)
.AddKeys(keysT)
.SetChange(myaddress)
.Send(destination, new Money(value, MoneyUnit.BTC))
.SendFees("0.0002");
//.BuildTransaction(true);
var tx2 = txBuilder.BuildTransaction(true);
//Console.WriteLine(txBuilder.Verify(tx));
var hello = tx2.ToHex();
var txRepo = new NoSqlTransactionRepository();
//txRepo.Put(tx.GetHash(), tx);
//Assert(txBuilder.Verify(tx)); //check fully signed
List<ICoin> GetCoins(decimal sendAmount)
{
//var mbwallet = (root.DataContext as MainWindowViewModel);
var amountMoney = new Money(sendAmount, MoneyUnit.BTC);
var client = new QBitNinjaClient(App.Network);
var txInAmount = Money.Zero;
var coins1 = new List<ICoin>();
foreach (var balance in client.GetBalance(mbwallet.SelectedWallet.CurrentAddress,//MBWallet.Wallet.Address,
true).Result.Operations)
{
var transactionId = balance.TransactionId;
var transactionResponse =
client.GetTransaction(transactionId).Result;
var receivedCoins = transactionResponse.ReceivedCoins;
foreach (Coin coin in receivedCoins)
{
if (coin.TxOut.ScriptPubKey ==
mbwallet.SelectedWallet.CurrentAddress.ScriptPubKey)//MBWallet.Wallet.BitcoinPrivateKey.ScriptPubKey) // this may not be necessary
{
coins1.Add(coin);
txInAmount += (coin.Amount as Money);
}
}
}
return coins1;
}
For what I see in the code you already add the private key to the builder so basically you only need to sign , something like this
Transaction signed = txBuilder.SignTransaction(tx2);

Filling textboxes with strings

I have a windows form application that has a slew of textboxes that I fill using a bunch of strings. My question is...the code works fine but it seems like a lot of wasteful typing. Can you fill the textboxes from the strings in a loop functions? Matching up the textbox with the approriate string?
Here is what I have.
var client = new WebClient { Credentials = new NetworkCredential(username, password) };
var financials = client.DownloadString("https://api.intrinio.com/data_point?identifier="+conver+"&item=beta,marketcap,52_week_high,52_week_low,adj_close_price,short_interest,analyst_target_price,next_earnings_date,percent_change,yr_percent_change,implied_volatility, dividendyield,listing_exchange,sector,average_daily_volume");
var jss = client.DownloadString("https://api.intrinio.com/companies?identifier=" + conver + "");
JObject rss = JObject.Parse(jss);
JObject fin = JObject.Parse(financials);
string RRSTITLE = (string)rss["legal_name"];
string beta = (string)fin.SelectToken("data[0].value");
string marketcap = (string)fin.SelectToken("data[1].value");
string weekhigh = (string)fin.SelectToken("data[2].value");
string weeklow = (string)fin.SelectToken("data[3].value");
string adj_close = (string)fin.SelectToken("data[4].value");
string short_interest = (string)fin.SelectToken("data[5].value");
string analyst_target = (string)fin.SelectToken("data[6].value");
string earnings = (string)fin.SelectToken("data[7].value");
string percent_change = (string)fin.SelectToken("data[8].value");
string yr_percent_change = (string)fin.SelectToken("data[9].value");
string implied = (string)fin.SelectToken("data[10].value");
string divyield = (string)fin.SelectToken("data[11].value");
string exchange = (string)fin.SelectToken("data[12].value");
string sector = (string)fin.SelectToken("data[13].value");
string volume = (string)fin.SelectToken("data[14].value");
company_textbox.Text = RRSTITLE;
beta_box.Text = beta;
marketCap_box.Text = marketcap;
wekhighbox.Text = weekhigh;
weklowbox.Text = weeklow;
adjclosebox.Text = adj_close;
shortbox.Text = short_interest;
targetestbox.Text = analyst_target;
next_earnings.Text = earnings;
Close_box.Text = percent_change;
percentytd.Text = yr_percent_change;
implivolbox.Text = implied;
divyieldbox.Text = divyield;
exchangebox.Text = exchange;
sectorbox.Text = sector;
daily_Volume_text.Text = volume;
Like #Jacky said, the straight forward answer is no. But a really hacky way would be to create two Dictionaries. Something like this
Dictionary<string, TextBox> TextBoxLookup = new Dictionary<string, TextBox>();
Dictionary<string, string> ValueLookup = new Dictionary<string, string>();
TextBoxLookup["beta"] = beta_box;
TextBoxLookup["marketcap"] = marketCap_box;
TextBoxLookup["weekhigh"] = wekhighbox;
ValueLookup["beta"] = beta;
ValueLookup["marketcap"] = marketcap;
ValueLookup["weekhigh"] = weekhigh;
foreach(string key in TextBoxLookup.Keys)
{
TextBoxLookup[key].Text = ValueLookup[key];
}
You'll have to add each textbook and its value to their respective dictionaries with the same key and iterate through the assignment foreach block everytime you need to assign.
Does this help?

How do I hardcode my accesskey and secret access key in my .net source code?

var ec2Client = new AmazonEC2Client();
string amiID = "ami;
string keyPairName = "aaaa";
// List<string> groups = new List<string>() ;
var launchRequest = new RunInstancesRequest()
{
ImageId = amiID,
InstanceType = "tttt",
MinCount = 1,
MaxCount = 1,
KeyName = kkkk,
SubnetId = "bbbb",
};
How do I hard-code my access key and secret access key ?
var awsCreds = new BasicAWSCredentials("ACCESS_KEY", "SECRET_KEY");
var ec2Config = new AmazonEC2Config() {
// add configurations here,
// such as ServiceURL and RegionEndpoint
}
var ec2Client = new AmazonEC2Client(awsCreds, ec2Config);
Learn more:
AmazonEC2Client Class
AmazonEC2Config Class
Anyway, hard-coding access key and secret key is not recommended. Please be really cautious, especially when you are going to share your code to a public repository.

Return Single result from mongo doc

Hi I am trying to make a generic method to return a single value from the database
I am not sure where to put the return result, value is returned as a BSON document.I need 1 value from it....
public static string SearchMongoSingleValue(string key, string value, string ducument, string datatable)
{
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase(datatable);
var collection = database.GetCollection(ducument);
var query = Query.EQ(key, value);
var oneDocument = collection.FindOne(query);
return oneDocument[value];
Thanks
I think you need oneDocument[key] and not oneDocument[value]. Just tested this code:
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
var client = new MongoClient("mongodb://localhost");
var coll = client.GetServer().GetDatabase("local").GetCollection("test1");
var doc = new BsonDocument();
doc.Add("Name","John");
doc.Add("Color","Red");
coll.Insert(doc);
var query = Query.EQ("Name", "John");
var doc2 = coll.FindOne(query);
var value = doc2["Color"];
It returns "Red" allright

extract left of the question mark

Is there a quick way to grab everything left of the question mark?
http://blah/blah/?blah
to
http://blah/blah/
Uri uri = new Uri(#"http://blah/blah/?blah");
string leftPart = uri.OriginalString.Replace(uri.Query,string.Empty);
Basically, you want to use string.Split:
string url = #"http://blah/blah/?blah";
var parts = url.Split('?');
string bitToLeftOfQuestionMark = parts[0];
It looks like you essentially want to get the scheme, authority and path of the URI.
You can use the Uri.GetComponents Method for this:
var uri = new Uri("http://blah/blah/?blah");
var result = uri.GetComponents(
UriComponents.SchemeAndServer | UriComponents.Path,
UriFormat.UriEscaped);
// result == "http://blah/blah/"
Try this:
string httpString = "http://blah/blah/?blah"
int questionMarkLocation = httpString.indexOf('?');
string newString = httpString.Substring(questionMarkLocattion+1);
Just to give a different answer:
var url = "http://blah/blah/?blah";
var leftPart = Regex.Match(url, #"[^?]+").Value;

Categories