Already php sms function convert to C# success - c#

i have already configured SMS gateway & some php code.Now my project is thatone convert it to Csharp with minor changes,
probably i have to write new code.but so.. experienced guys from you i wanted to know is that possible ? Sample code below.
enter code here
$username = "abcdsoft";
$password = "softsoft";
//GET parametrar
//$source = $_GET['sourceaddr'];
//$dest = $_GET['destinationaddr'];
//$message_in = $_GET['message'];
enter code here
$source = $_GET['msisdn'];
$dest = $_GET['shortcode'];
$message_in = $_GET['msg'];
those are most top lines.below code i changed.(php to csharp)
enter code here
string username ='abcdsoft';
string password = 'abcdabcd';
int source = ['sourceaddr'];
int dest = ['shortcode'];
string message_in = ['msg'];
Is this way is correct ?

Almost.
Need to use double-quotes for the string
Request.QueryString is the ASP.NET equivalent to the PHP $_GET.
Also, apparently C# is a bit more strongly typed than PHP, so you need to explicitly convert the query string params to integers.
Code should be like this:
string username = "abcdsoft";
string password = "abcdabcd";
int source = int.Parse(Request.QueryString["sourceaddr"]);
int dest = int.Parse(Request.QueryString["shortcode"]);
string message_in = int.Parse(Request.QueryString["msg"]);

Related

How can I replace the parameters in my request url using C#?

I have n number of request urls, like below
https://{user.id}/{user.name}/testing1
https://{user.number}/{user.name}/testing1
https://{user.age}/{user.height}/testing1
https://{user.gender}/{user.name}/testing1
https://{user.height}/{user.age}/testing1
https://{user.weight}/{user.number}/testing1
I have the below test data class which has n number of values.
public class User{
public string id = "123";
public string name = "456";
public string age = "789";
public string gender = "1478";
public string height = "5454";
public string weight = "54547";
public string number = "88722";
.......
.......
.......
}
And I need to make the url
https://{user.number}/{user.name}/testing1 into
https://{88722}/{456}/testing1
In my code, I will be randomly getting a request url(from a json file) and i need to replace the parameters with the values given in the class. Can this be done? If yes please help. Thanks
I have tried using string.format() - but it doesnot work, because I am randomly getting the url and I am not sure which value needs to be replaced.
I also tried using the interpolation, but found not helpful either unless i can do something like
User user = new User();
string requesturl = GetRequestJSON(filepath);
//The requesurl variable will have a value like
//"https://{user.id}/{user.name}/testing1";
string afterreplacing = $+requesturl;
Update: After some more googling, I found out that my question is very much similar to this. I can use the first answer's alternate option 2 as a temporary solution.
Unless I am clearly missing the point (and lets assume all the values are in when you do new user(); )
You just want
User user = new User();
string requesturl = $"https://{user.id}/{user.name}/testing1";
then all the variables like {user.id} are replaced with values. such as "https://88722/456/testing1" if you need the {} in there you can add extra {{ to go with such as
string requesturl = $"https://{{{user.id}}}/{{{user.name}}}/testing1";

Configuring SMS API

Please all I've got this API from an SMS reseller here in Nigeria. I want to know how to insert my textbox values corectly
API: http://smsmobile24.com/components/com_spc/smsapi.php?username=xxx&password=yyy&sender=##sender##&recipient=##recipient##&message=##message##
I need to insert password, username and of course sender and recipients.
I have tried doing this:
string to, msg;
to = smsRecipientBox.Text;
msg = smsMsgBox.Text;
http://smsmobile24.com/components/com_spc/smsapi.php?username=C***er&password=fath****am&sender=Cmanager&recipient = '"+to+"'&message='"+msg+"';
But I get that red line telling me there is an error.
You can't modify a constant value (variable that is marked with const modifier).
You have two options here:
1) you remove the const from the field
2) use formatting to insert values in placeholders in the constant string:
const string url = "http://smsmobile24.com/components/com_spc/smsapi.php?username=C***er&password=fath****am&sender=Cmanager&recipient={0}&message={1}";
var to = smsRecipientBox.Text;
var msg = smsMsgBox.Text;
string result = string.Format(url, to, msg);

How can I replicate this C# hashing in PHP? (toByteArray(), ComputeHash())

I am trying to replicate the following code in PHP, It is example code for an API I have to interface with (The API & Example code is in C#, My app is in PHP 5.3). I'm not a C# developer and so am having trouble doing this.
// C# Code I am trying to replicate in PHP
var apiTokenId = 1887;
var apiToken = "E1024763-1234-5678-91E0-T32E4E7EB316";
// Used to authenticate our request by the API (which is in C#)
var stringToSign = string.Empty;
stringToSign += "POST"+"UserAgent"+"http://api.com/post";
// Here is the issue, How can I do the following 3 lines in PHP?
// No "secret key" provided?.. How do I do this in PHP?
var hmacsha1 = new HMACSHA1(new Guid(apiToken).toByteArray());
// Make a byte array with ASCII encoding.
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(stringToSign);
// Finally, 'computeHash' of the above (what does this do exactly?!)
var calculatedSignature = Convert.ToBase64String(hmacsha1.ComputeHash(byteArray));
I've tried many variations using pack() and other functions I've found online, but without anything to compare it to, I don't know if i've done it right or not.
Can any C# devs run the above code and post the values generated so I can use that to check/test against?
I've tried checking the MSDN to see what these methods do, but am stuck (and not sure if its correct, as I have nothing to compare it to).
PHP Pseudo Code
// Set vars
$apiToken = 'E1024763-1234-5678-91E0-T32E4E7EB316';
$apiTokenId = '1887';
$stringToSign = "POST"."UserAgent"."http://api.com/post";
// HowTo: Build a `byteArray` of our apiToken? (i think)
// C#: var hmacsha1 = new HMACSHA1(new Guid(apiToken).toByteArray());
// HowTo: Convert our $stringToSign to a ASCII encoded `byteArray`?
// C#: byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(stringToSign);
// HowTo: Generate a base64 string of our (`hmacsha1`.ComputeHash(byteArray))
// C#: var calculatedSignature = Convert.ToBase64String(hmacsha1.ComputeHash(byteArray));
This sounds pretty simple and straightforwaard, but I'm not sure what a few of these C# methods do..
What do these C# methods do/return?
ComputeHash(byteArray) - Computed to what?.. what is returned?
System.Text.Encoding.ASCII.GetBytes(stringToSign); - What does this return?
new HMACSHA1(new Guid(apiToken).toByteArray()); No Secret Key?, what is the key used?
Any resources or help would be much appreciated.
I tried variations of other answers on SO, but no joy.
Can I run the 3 lines of code somewhere online (like JSFiddle but for C#?) so I can see the output of each line?
Update - Bounty Added
Still having trouble with this, I have managed to test the C# code in Visual Studio, but am having trouble getting the same hash generated in PHP.
I would like...
.. the above C# code (specifically, the 3 lines which create the SHA1 hash) to be converted into PHP (Check out the Pseudo Code I posted above). I should be able to match the C# hash using PHP.
If you have any other questions, please ask.
The issue is that the string form of the GUID reverses the order of the 2-character hexadecimal numbers in the first 3 segments of the GUID. For more information see the comments in the example at: http://msdn.microsoft.com/en-us/library/system.guid.tobytearray.aspx
The following code should work:
$apiTokenId = 1887;
$apiToken = "E1024763-1234-5678-91E0-FF2E4E7EB316";
$stringToSign = '';
$hexStr = str_replace('-','',$apiToken);
$c = explode('-',chunk_split($hexStr,2,'-'));
$hexArr = array($c[3],$c[2],$c[1],$c[0],$c[5],$c[4],$c[7],$c[6],$c[8],$c[9],$c[10],$c[11],$c[12],$c[13],$c[14],$c[15]);
$keyStr = '';
for ($i = 0; $i < 16; ++$i) {
$num = hexdec($hexArr[$i]);
$keyStr .= chr($num);
}
$stringToSign .= "POST" . "UserAgent" . "http://api.com/post";
$hmacsha1 = base64_encode(hash_hmac('sha1',$stringToSign,$keyStr,true));
I've tested this code against the C# code you provided above and the output was the same. However, the GUID specified in the original code is not valid so I had to change it slightly.
It's pretty easy, when i don't have to test the code :P
http://php.net/manual/en/function.hash-hmac.php - that's the equivalent of the HMACSHA1 c# class.
string hash_hmac (string $algo , string $data , string $key [, bool $raw_output = false ] )
So $algo = "sha1"
$data is your $stringToSign - since that is already an ascii string (i hope) - the C# was just taking the byte equivalent of the same.
new Guid(apiToken).toByteArray() -> that's a 16 byte (16*8 = 128) representation of the GUID - which is 32*4 = 128 bits. This is the key.
$key is a string so you need the ASCII string equivalent for your $apiToken (which is 32 hex chars - first strip / ignore the dashes in between) - E10247631234567891E0T32E4E7EB316 (correct the key - it cannot have a "T")
function hex2str($hex) {
for($i=0;$i<strlen($hex);$i+=2) $str .= chr(hexdec(substr($hex,$i,2)));
return $str;
}
$hexKey = hex2str($apiToken); //strip the dashes first
http://www.linux-support.com/cms/php-convert-hex-strings-to-ascii-strings/
So the method call now works :
$almostResult = hash_hmac ("sha1" , $stringToSign, $hexKey, true)
This returns a binary string - which you need to convert to base64 encoding.
$final = base64_encode ($almostResult)
That should do it...enjoy :)
I faced almost the same problem and after some googling i found this post:
https://www.reddit.com/r/PHP/comments/2k9tol/string_to_byte_array_using_utf8_encoding/
In PHP strings are already byte arrays. What is the specific problem you are having?
For me the solution was just base64_encode('apikey')

String.Replace doesn't work with a php file?

Why the code below doesnt work ?
string Tmp_actionFilepath = #"Temp\myaction.php";
// change the id and the secret code in the php file
File.Copy(#"Temp\settings.php", Tmp_actionFilepath, true);
string ActionFileContent = File.ReadAllText(Tmp_actionFilepath);
string unique_user_id = textBox5.Text.Trim();
string secret_code = textBox1.Text.Trim();
ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent.Replace("SECRET_CODE", secret_code);
File.WriteAllText(Tmp_actionFilepath, ActionFileContent);
Here is the content of setting.php
<?php
session_start();
$_SESSION["postedData"] = $_POST;
/////////////////////////////////////////////////////////
$_SESSION["uid"] = "UNIQUE_USER_ID";
$_SESSION["secret"] = "SECRET_CODE";
/////////////////////////////////////////////////////////
function findThis($get){
$d = '';
for($i = 0; $i < 30; $i++){
if(file_exists($d.$get)){
return $d;
}else{
$d.="../";
}
}
}
$rootDir = findThis("root.cmf");
require_once($rootDir."validate_insert.php");
What is wrong with the code above ? After compiling the code in c#, i noticed the file myaction.php is created, but the values : UNIQUE_USER_ID and SECRET_CODE doesn't change, I tried also to copy/paste these values to make sure they are same. But the code always doesn't work
String.Replace returns a new string as strings are immutable. It does not replace the string you are calling it on.
You should replace:
ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent.Replace("SECRET_CODE", secret_code);
with:
ActionFileContent = ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent = ActionFileContent.Replace("SECRET_CODE", secret_code);
On top of that you should really change your variable names so they follow the regular C# naming conventions (i.e. use actionFileContent instead of ActionFileContent).
you have to set the result of the replace string method on a string.
string Tmp_actionFilepath = #"Temp\myaction.php";
// change the id and the secret code in the php file
File.Copy(#"Temp\settings.php", Tmp_actionFilepath, true);
string actionFileContent = File.ReadAllText(Tmp_actionFilepath);
string unique_user_id = textBox5.Text.Trim();
string secret_code = textBox1.Text.Trim();
// set the result of the Replace method on the string.
actionFileContent = ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id)
.Replace("SECRET_CODE", secret_code);
File.WriteAllText(Tmp_actionFilepath, actionFileContent);

Is this 64-bit Encoded?

All of the passwords in our User DB look like this where we have == at the end:
91F2FSEYrFOcabeHK/UfNw==
So how can I tell if this is 64-bit encoded? It has to be because I can decode using a decode 64-bit routine I have.
I am trying now to figure out how to decode a literal string to 64-bit..back to the xxxxxxxx== and here is my code:
string passwordToEncrypt = "test";
byte[] passwordToBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(passwordToEncrypt);
result = Convert.ToBase64String(passwordToBytes);
Updated:
I need the text test to come out in Base64 with the == at the end.
you have a typo in there - so the above code does not compile, try
string passwordToEncrypte = "test";
byte[] passwordToBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(passwordToEncrypte);
string result = Convert.ToBase64String(passwordToBytes);
result contains now a "Base64"-encoded password and end with "=="...
BUT the above code works only for passwords containing ASCII... if you want it to work with UTF8 passwords then change it to :
string passwordToEncrypte = "test";
byte[] passwordToBytes = Encoding.UTF8.GetBytes(passwordToEncrypte);
string result = Convert.ToBase64String(passwordToBytes);
to go back from Base64 to the original you need to do:
string Original = Encoding.UTF8.GetString (Convert.FromBase64String(result));
see http://msdn.microsoft.com/en-us/library/86hf4sb8.aspx
and http://msdn.microsoft.com/en-us/library/system.convert.tobase64string.aspx
and http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx
Base64 encoded string doesn't always end with a =, it will only end with one or two = if they are required to pad the string out to the proper length.For more details checkout following link
Padding

Categories

Resources