I am doing some work in php try to encrypt a string by SHA1. However, I need to match the result to the result of someone else who has done in Xcode.
What he has written in Xcode is as following:
NSString *saltedPassword = [NSString stringWithFormat:#"%#%#",_myTextField.text,saltKey];
NSString *hashedPassword = nil;
unsigned char hashedPasswordData[CC_SHA1_DIGEST_LENGTH];
NSData *saltedData = [saltedPassword dataUsingEncoding:NSUTF8StringEncoding];
if (CC_SHA1([saltedData bytes], [saltedData length], hashedPasswordData)) {
hashedPassword = [[NSString alloc] initWithBytes:hashedPasswordData length:sizeof(hashedPasswordData) encoding:NSASCIIStringEncoding];
} else {
NSLog(#"ERROR: registerAction, should not be here");
abort();
}
I don't know Xcode very well. My understand of what he has done is:
concatenate the string with the key to get a new string, let's call it "string1".
encode the string1 as UTF-8,let's call the encodes string "string2"
use SHA1 to encrypt string2, length is 20 (CC_SHA1_DIGEST_LENGTH is 20,right?),let's call the encrypted string "string3"
encode "string3" as ASCII to get the final result.
So, based on my understanding above, I wrote the code in php as following:
$password.=$configs['key'];
$password=mb_convert_encoding($password, "UTF-8");
$codedPassword=sha1($password, $raw_output = TRUE);
$codedPassword=mb_convert_encoding($codedPassword, "ASCII");
echo($codedPassword);
$password is the string I want to encrypt.
But the result I got is different from the result from Xcode. We use the same key.
For example:
If the input is "123456", the output of Xcode is "Õÿ:>/
o×NVÛ²¿+(A7", the output of php is "|J? ?7b?a?? ?=?d???". (I am not sure if these are the exact string or the string itself contains some characters that cannot be displayed.)
Does anyone know how to change the php code to get the same result?(It would be perfect that your solution is about how to change the PHP code. Because I cannot change the Xcode for the moment. My job is to write the PHP code to match the Xcode's result.)
You seem to be describing:
NSData *saltedData = [saltedPassword dataUsingEncoding:NSUTF8StringEncoding];
as 'encode the string1 as UTF-8,let's call the encodes string "string2"' and doing:
$password=mb_convert_encoding($password, "UTF-8");
However that step is converting the string into a byte array, look at for instance the answers to this question String to byte array in php, it seems you should do something like this in that step:
$bytes = unpack("H*",$password);
Related
I need to sync up PHP and Objective-C clients such that they can log in using the same credentials. I've found several different methods to hash passwords for each, but the problem is that none of their outputs match!
Does anyone have code for both PHP and Objective-C that will apply a SHA256 (or equivalent) hashing algorithm such that their output is identical?
Currently I'm using this for Objective-C:
//salt the password
NSString *saltedPassword = [NSString stringWithFormat:#"%#%#", #"<passwd input>", kSalt];
//prepare the hashed storage
NSString* hashedPassword = nil;
unsigned char hashedPasswordData[CC_SHA1_DIGEST_LENGTH];
//hash the pass
NSData *data = [saltedPassword dataUsingEncoding: NSUTF8StringEncoding];
if (CC_SHA1([data bytes], [[NSNumber numberWithInt:[data length]] doubleValue], hashedPasswordData)) {
hashedPassword = [[NSString alloc] initWithBytes:hashedPasswordData length:sizeof(hashedPasswordData) encoding:NSASCIIStringEncoding];
}
And this for PHP:
$password = "<passwd input>" . "<salt>";
$password = sha1($password);
Also, this Github post seems it would be extremely helpful, but the objective-c portion doesn't work: https://gist.github.com/pcperini/2889493
Like the title says, my UITextView is setup to print data found within "userName". Instead of behaving appropriately, it prints "userName".
PHP code:
<?php
header('Content-Type: application/json');
$arr = array ('userName'=>'derekshull', 'userBio'=>'This is derekshulls bio','userSubmitted'=>'15');
echo json_encode($arr);
?>
Objective C:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *myURL = [[NSURL alloc]initWithString:#"http://techinworship.com/json.php"];
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];
if(!error)
{
for (id element in jsonArray) {
textview.text = [NSString stringWithFormat:#"%#", [element description]];
// text view will contain last element from the loop
}
}
else{
textview.text = [NSString stringWithFormat:#"Error--%#",[error description]];
}
}
What am I missing here? Also, when run, the application does not crash and give error. However, the following is documented in the DeBug Area.
2014-03-24 20:20:53.258 testtest[11434:60b] Unknown class textview in Interface Builder file.
I don't currently have a OSX computer available so I can't evaluate my code.
It seems like the array you have in you PHP code is an associative array and the JSON will be similar. When you are parsing the JSON string in your Obj-C code try assigning it to a NSDictionary, this way you will have access to the associative array.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];
When using the data in the jsonArray don't iterate it, use the NSDictionary method objectForKey to get get the value you want.
As an example, to get the value of userName, you can do this:
[jsonArray objectForKey: #"userName"] // jsonArray is not actually a array, but a dictionary now
And to change the text of the textview, you can do the following:
textview.text = [NSString stringWithFormat:#"%#", [jsonArray objectForKey: #"userName"]];
Ask if something is unclear!
Cheers!
I have This PHP Code With Arrays And Loops, Trying to convert it into Objective-c "iOS"
foreach($arr as $item)
{
$data[$item[date]][]=$var;
}
What i did so far is :
for(id theKey in result)
{
leEvent[[NSString stringWithFormat:#"%#",[theKey objectForKey:#"event_date"]]]=#"asd";
}
but it still overlaps each other if same key.
So any Idea ? Thanks in advance.
UPDATE :
I have this JSON:
[{"id":"1","title":"test","event_date":"2014-01-28","description":"this
is a test desc ","time_stamp":"2014-01-28
13:04:12"},{"id":"2","title":"test2","event_date":"2014-01-29","description":"this
is a test desc2 ","time_stamp":"2014-01-28
13:21:36"},{"id":"3","title":"test3","event_date":"2014-01-29","description":"this
is a test desc3","time_stamp":"2014-01-28 13:21:36"}]
I want To make out of it Array That They key of Array is the Date : and inside each date other information
Expmple $data['2014-01-29'] should have 2 arrays in side it but i want to do it in iOS
We have "for in" loop in objective C
For example:
for( NSNumber *num in numArray)
{
//Write your code here
}
Let me know if this is not what you want or you need some more info
Update:
You don't need a ForLoop in here.
Let's say result is your NSDictionary object.
So,
[result objectForKey:#"event_date"]
will give object for key "event_date".
By your code.. It seems like you are trying to set value for the key "event_date".
So your code would be something like this,
[result setObject:#"asd" forKey:#"event_date"];
Let me know if it does not help.
I would suggest you to use JSONSerialization. This might ease up your task.
NSError* err = nil;
NSString* myJSONFile = [[NSBundle mainBundle] pathForResource:#"myFileName" ofType:#"json"];
NSArray* dataTypes = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:myJSONFile] options:kNilOptions error:&err];
NSLog(#"Imported data Types: %#", dataTypes);
//This will print the data you just imported..
NSMutableArray *myArray= [[NSMutableArray alloc]init];
[dataTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
if([obj objectForKey:#"event_date"] isEqualTo:#"myDate")
{
[myArray addObject:obj];
}
}];
I've checked this code... Working fine.. Let me know if any issues are there
I have a PHP script on a server, all working fine for most of the thing I need it to do. I'm now setting up special user privileges for certain users.
I check if the logged in user is registered on a special user database, then return the name of their privleges or 'blank' using the following:
private function checkSpecialUser($userID)
{
$db = new DbConnect();
$result = $db->query("SELECT privelege FROM special_users WHERE userID = $userID");
if ($privName = $result->fetch_object())
{
echo $privName->privelege;
}
else
{
echo 'blank';
}
$db->close();
}
In Xcode, I have set up a simple function to return the string which is returned by the PHP script (I'll leave out the connection part since that all works fine):
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&requestError];
NSString *packName = (NSString *)[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
packName = [packName stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"packName is %#", packName);
if([packName isEqualToString:#"blank"])
{
NSLog(#"user is not special");
}
else
{
NSLog(#"User is special :-)");
}
return packName;
Now to the problem I have. If the user does not have special privileges then the first NSLog prints "packName is blank" which is exactly what I would expect. However, the if statement should then pick up that packName is equalToString "blank", which it doesn't. It always reaches 'else' and prints "User is special :-)".
I've double checked with users who ARE registered, and although it returns the string I would expect, again it doesn't trigger an equalToString response.
Do PHP echoes have hidden characters in them that I would need to remove, or am I somehow getting the value from the database incorrectly? In the database each row is simply a userID which is a varchar, and the name of their privilege which is also a varchar.
If anyone has any tips I'd be really grateful. Thanks.
Try, instead of sending back "blank", sending back nothing, or an empty string. Then, instead of matching the word "blank", test the length of the string. This will at least tell you if there are other characters in packName... you might remove more than just space whitespace, if I had to guess I'd say you've got a newline in there.
Please help me with my problem in posting a JSON decoded emoji character.
I have a UITextView, this text view may have a emoji character. I am posting the data to a web server with the UITextView.text presented as JSON, the problem is when the text has a an emoji, I am not able to get the data. What I do is:
$postData = file_get_contents("php://input") to get the data.
then I use
$post = json_decode($postData,true);
to decode the data and have a assoc array and insert the data in database.
here is a code snippet when I insert my data into database.
$postData = file_get_contents("php://input");
//$postData = '{"body":"characters here ","subject":"subject here","username":"janus","from_id":"185","to_id":"62"}';
$post = json_decode($postData,true);
$data=array(
'user_id_from'=>mysql_real_escape_string($post['from_id']),
'user_id_to'=>mysql_real_escape_string($post['to_id']),
'subject'=>mysql_real_escape_string($post['subject']),
'message'=>mysql_real_escape_string($post['body']));
$messages_obj->insert($data);
Without an emoji character found, it works fine. no problem. the problem is when an emoji character found, the data in $post (decoded data) is null.
I tried to use dummy data (line 2 in code snippet)
//$postData = '{"body":"characters here ","subject":"subject here","username":"janus","from_id":"185","to_id":"62"}';
and I succesfully inserted the emoji characters in database. I dont know why but It dont work the same when the data is from the device ($postData = file_get_contents("php://input"))
This is how I encode and post my data in client.
NSMutableDictionary *messageDetails = [[NSMutableDictionary alloc] init];
[messageDetails setObject:[loginItems objectForKey:#"user_id"] forKey:#"from_id"];
[messageDetails setObject:recipientID forKey:#"to_id"];
[messageDetails setObject:#"subject here" forKey:#"subject"];
[messageDetails setObject:newMessageField.text forKey:#"body"];
[messageDetails setObject:[loginItems objectForKey:#"username"] forKey:#"username"];
NSString *strPostData = [messageDetails JSONRepresentation];
[messageDetails release];
NSData *postData = [NSData dataWithBytes:[strPostData UTF8String] length:[strPostData length]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
Once the data is sent to your php script you need to convert it to a multibyte string:
$content = mb_convert_encoding($content, 'UTF-8');
You can use this function:
function cb($content){
if(!mb_check_encoding($content, 'UTF-8')
OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
$content = mb_convert_encoding($content, 'UTF-8');
}
return $content;
}
Edit: The data was probably of type application/x-www-form-urlencoded for us and that function converted it correctly.
emoji characters are most likely transcoded in UNICODE, so it should be sufficient to just send, receive and manage your data in UTF-8.
When receiving with this
$postData = file_get_contents("php://input")
(I suppose that is a real URL), make sure your php script sends an Content-Encoding header (like the following, choose a MIME-type that suits you)
header("Content-Type: text/html; charset=utf-8");
Please follow following steps:
Convert Emoji characters to base64 and send to server.
On server side save base64 in database without decode.
When you want to display Emoji on Application then retrieve same base64 data from server.
Decode retrieve string and display on app.
Your Emoji character will display properly.