Encrypt and decrypt parameter passed in on query string - c#

I'm using (or attempting to!) the code for encrypting/decrypting a string found in this post Encrypting & Decrypting a String in C#.
If I call the functions directly, i.e.
StringHelper sHelp = new StringHelper();
var encryptMe = sHelp.EncryptString("comahony#centlaw.com", "myPassphrase");
Returns /sx3sL4DE7sM2klGKN3V+CQKdP02ZxbVxANjDh2yfGo= which is perfect
and if I then call
var decryptMe = sHelp.DecryptString(encryptMe, "myPassphrase");
Returns comahony#centlaw.com which again is what I'm after.
But if I pass the encrypted string on parameter on the querystring. i.e.
http://localhost:12345/sso?c=/sx3sL4DE7sM2klGKN3V+CQKdP02ZxbVxANjDh2yfGo=
and call the decryption function using:
var decryptMe = sHelp.DecryptString(Request.QueryString["c"].ToString(), "myPassphrase");
I'm getting the error of "Invalid length for a Base-64 char array or string."
From digging around on the net it appears to be something to do with the parameter needing to be URLEncoded but try as I might I just can't get past this error.
Could something shed some light please?
Thanks,
C

Related

NBitcoin and generating addresses from xpub key

I'm attempting to write an algorithm that generates public bitcoin addresses from a known xpubkey. The key I'm using for testing can be found at blockchain.info at
https://blockchain.info/xpub/xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz
I'm trying something like this to generate the address on the path 0,0,0, as below:
var pubkey = new ExtPubKey(Encoding.ASCII.GetBytes("6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz"));
Console.Writeline(pubkey.Derive(0).Derive(0).Derive(0).PubKey.GetAddress(Network.Main));
but I'm not fully understanding something because I get a 'Invalid point encoding 103' when trying to instantiate the ExtPubKey.
Via https://bitcointalk.org/index.php?topic=1242247.0
var pubkey = ExtPubKey.Parse("xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz");
var newAddress = pubkey.Derive(0).Derive(0).PubKey.GetAddress(Network.Main);
Console.WriteLine(newAddress);
Tested, generates expected first address.
You get invalid encoding, because you are trying to encode
"6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz"
instead of
"xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz"
You are missing xpub from the beginning.

coin.mx keeps giving me 403 forbidden error on my web request

I have been trying to make a query to the coin.mx site in a C# app, and I keep getting a 403 forbidden error. Their example uses python:
base64.b64encode(str(HMAC(YOUR_SECRET, PATH+'?'+S, sha512).digest())),
where PATH is a http path (e.x. "/api/v2/trader/info")
given my secret is a hex string of the form "d1e2a3d4", I calculate my signature as follows:
HMACSHA512 mHasher512 = new HMACSHA512(secret);
var path = "/api/v2/trader/info?nonce=123"
var msg = Encoding.ASCII.GetBytes( path );
var hash = mHasher512.ComputeHash(msg);
var hashb64 = Convert.ToBase64String(hash);
return hashb64;
Does this seem right?
For reference: https://coin.mx/coinmx_api_en.pdf
I was having the same issue and found this question while searching for a solution. I finally fixed the problem by removing ? in the path string. Try changing your path variable as follows (this is just for getting the hash string, the GET request still needs the ? of course).
var path = "/api/v2/trader/infononce=123"
Note the documentation seems incorrect. I figured this out by looking at the sample python code.

Using FileReader.readAsDataUrl to upload image to Web Api service

I am trying to use the FileReader to obtain the base-64 representation of an image and submit that to a .net WebApi service for image uploading.
My problem is that the contents of fileReader.result are not valid as a base-64 encoded image, at least according to .net.
I am just using a very simple method, and testing with fiddler to post to the service. If I post the complete result string from filereader.result, I get an error "Invalid length for a Base-64 char array or string" when I try and read the string using FromBase64String.
public void Post([FromBody]string imgString)
{
var myString = imgString.Split(new char[]{','});
byte[] bytes = Convert.FromBase64String(myString[1]);
using (MemoryStream ms = new MemoryStream(bytes))
{
Image image = Image.FromStream(ms);
image.Save("myBlargyImage.jpg");
}
}
Is cut+paste into fiddler doing something to the string that I need to account for here, or is there something else I am not doing correctly? This seems like it should be straightforward: Encode the image as a string, send the string, decode the string, save the image.
For example, using filereader to display a preview of the image on the client, I get the following in filereader.result:
src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAyADIAAD/...oBUA00AqYL/AMCg3//Z"
I have tried both sending the entire string ("data...Z"), and just the Base64 string. Currently, I am splitting the string server side to get the Base64 string. Doing this, I always get the invalid length error.
Alternatively, I have tried sending just the base64 string. Not knowing if the leading / was actually part of the string or not, I deleted it in the post body. Doing THIS, I can actually read the value into a byte array, but then I get an error using Image.FromStream that the array is not a valid image.
So, either I get an error that the entire string as provided by filereader is an invalid length, or, I hack it up and get an error that even if it is a valid length, it is not a valid image (when reading the bytearray). That is what makes me wonder if there is some issue of translation or formatting between the filereader.read, dev tools in chrome, then cutting and pasting into fiddler.
UPDATE:
I tried a more realistic implementation by just taking the filereader.result and putting it in a $.post() call, and it works as expected.
It appears I was right, that I, or notepad++, or fiddler, are doing something to the data when I touch it to cut and paste filereader.result into a service call.
If someone knows exactly what that might be, or how one can verify they are sending a valid base-64 encoding of an image to a service, it might help others who are attempting the same thing in the future.
Again, if in the browser filereader.result yielded 'data:image/jpeg;base64,somestring', I was simply copying that string from the developer tools panel, creating a fiddler call and in the request body including the copied string: "=data:image/jpeg;base64,somestring". Somehow, the base-64 'somestring' was getting munched in the cut+paste.
function readURL(input) {
if (input.files && input.files[0]) {
reader = new FileReader();
reader.onload = function (e) {
$('#imgPreview').attr('src', e.target.result);
$.post('/api/testy/t/4',
{'':e.target.result}
);
};
reader.readAsDataURL(input.files[0]);
reader.onloadend = function (e) {
console.log(e.target.result);
};
}
}
$("#imgUpload").change(function () {
readURL(this);
});
Don't forget to remove the 'noise' from a dataUrl,
For example in
data:image/png;base64,B64_DATA_HERE
you have to remove the data:image/png;base64, part before, so you process only the base 64 portion.
With js, it would be
var b64 = dataUrl.split("base64,")[1];
Hope this helps. Cheers
A data uri is not a base64 encode string, it may contain a base64 encoded string at the end of it. In this case it does, so you need to only send the base64 encoded string part.
var imagestr = datauri.split(',')[1];
sendToWebService(imagestr);
Make sure fiddler is not truncating the Base 64 String

Trying to Encrypt/Decrypt using AES. Progress == null;

Edit.
I guess I had a problem with creating a correct input into the encrypt/decrypt methods: These lines of code do the trick:
string encrypted = en.Encrypt(stringBuilder.ToString(), "username", "password");
string decrypted = en.Decrypt(encrypted, "username", "password");
mainWindow.ChangeTextBox = encrypted + Environment.NewLine + decrypted;
I am just playing around and trying to figure out how encryption/decryption by using AES works. I am referring to this article (pretty much copy and paste :( Trying to learn).
There they give me complete encryption/decryption methods which I have tried to modify. I am trying to pass a list of entries created by ArrayList then binded with string builder. It seems like I am able to encrypt data but decryption causes error:
Length of the data to decrypt is invalid.
at line with code:
ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
How can I implement this code to be useful with my program and work correctly?
Regards.
I haven't looked through the code in detail, but it seems that the order of the parameters on the calls to Encrypt and Decrypt doesn't match the definition of the methods. In the calls to these methods you appear to have username, password, plain/cyphertext; whereas the methods have the signature plain/cyphertext, password, username.
Am I right it's caused for an empty or null string as plaintext? ;-)
"lol1" can not be decrypted as it's not a valid ciphertext length (padding!) not to say it wouldn't make any sense.

Difference in SHA hashes between ruby and C#

I'm developing an application, that makes use of some REST web services.
It's technical documentation says that I should pass SHA256 hash of some string in the request.
In an example request (in the documentation) a string:
hn-Rw2ZHYwllUYkklL5Zo_7lWJVkrbShZPb5CD1expires=1893013926label[0]=any/somestatistics=1d,2d,7d,28d,30d,31d,lifetimestatus=upl,livetitle=a
After executing:
digest = Digest::SHA256.digest(string_to_sign)
signature = Base64::encode64(digest).chomp.gsub(/=+$/, '')
results in a hash:
YRYuN2zO+VvxISNp/vKQM5Cl6Dpzoin7mNES0IZJ06U
This example is in ruby, as the documentation is for ruby developers.
I'm developing my application in C# and for the exactly same string, when I execute:
byte[] rawHash = sha256.ComputeHash(rawRequest, 0, rawRequest.Length);
string friendlyHash = Convert.ToBase64String(rawHash);
and remove the trailing "=" signs, I get:
Vw8pl/KxnjcEbyHtfNiMikXZdIunysFF2Ujsow8hyiw
and therefore, the application fails to execute resulting in an signature mismatch error.
I've tried changing the encoding while converting the string to a byte array preceding the hashing and nothing changed.
Any ideas?
Based on the document here, you are missing a - (that is a dash) in your string. Seems that Acrobat helpfully removes it in a copy paste from the document...
Here is some code that I splatted together that gets the same value as the example (well it would if you trimmed the final =)
string s = "hn-Rw2ZH-YwllUYkklL5Zo_7lWJVkrbShZPb5CD1expires=1893013926label[0]=any/somestatistics=1d,2d,7d,28d,30d,31d,lifetimestatus=upl,livetitle=a";
SHA256Managed sh = new SHA256Managed();
byte[] request = System.Text.UTF8Encoding.UTF8.GetBytes(s);
sh.Initialize();
byte[] b4bbuff = sh.ComputeHash(request, 0, request.Length);
string b64 = Convert.ToBase64String(b4bbuff);

Categories

Resources