I am attempting to compute a MD5 hash within an iOS app, in an effort to compare hashes between the file saved within the app and the same file stored on a web server using PHP.
This is the code for the iOS app:
unsigned char result[CC_MD5_DIGEST_LENGTH];
NSData* data = [NSData dataWithContentsOfFile:#"advert.png"];
const void* src = [data bytes];
CC_MD5(src, [data length], result);
NSString *imageHash = [[NSString stringWithFormat:
#"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]]
lowercaseString];
NSLog(#"%#", imageHash);
The code for the web server:
$file = 'advert.png';
echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
The app generates: D41D8CD98F00B204E9800998ECF8427E
The PHP generates: 3ef9386b1dd50e8e166efbe48f0f9401
md5sum generates: 3ef9386b1dd50e8e166efbe48f0f9401
UPDATE:
Just ran the app through the simulator and it correctly computes the hash: 3ef9386b1dd50e8e166efbe48f0f9401.
When ran on my iPhone 4 running iOS 5.1 it calculates as: ddf017003e063e353a5e4ec2cc4a5095
D41D8CD98F00B204E9800998ECF8427E is the MD5 sum of an empty file. Your don't read the file correctly, the reason is probably that dataWithContentsOfFile: needs an absolute path.
Try:
NSString *path = [[NSBundle mainBundle] pathForResource:#"advert" ofType:#"png"];
NSData *plistData = [NSData dataWithContentsOfFile:path];
My guess is that you have just witnessed the iPhone PNG optimizer in action.
Related
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);
I am trying to pass a date from Xcode to a PHP page (stores the Date to a mysql DB) however NSData doesn't seem to like the format of the Date.
//Format date for mysql & PHP
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *strToday = [dateFormatter stringFromDate:[NSDate date]];
NSString *strURL = [NSString stringWithFormat:#"http://www.TESTSERVER.com/Items.php?uID=123456789&item1=30&item2=5&startDate=%#&endDate=%#", strToday, strToday];
//strURL=[strURL stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSLog(#"%#", strURL);
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
I have tested the PHP page by entering data manually and it works without any issues. However when I ran the code above it doesn't work, I've isolated the issue to the date and I believe that NSData has a problem with the space in my Date Format (between the Date and Time).
I tried filling the gap with %20 (URL encoding etc.) and the connection is made to the db but the date field is not in the right format so it appears as null in the mysql database.
I'd rather not start parsing strings in my PHP, does anyone know how to fix this?
Below is my PHP code: -
<?PHP
$hostname = "XXX";
$username = "XXX";
$password = "XXX";
$database = "XXX";
$db_handle = mysql_connect($hostname, $username, $password);
$db_found = mysql_select_db($database, $db_handle);
$uID = $_GET['uID'];
$item1 =$_GET['item1'];
$item2 =$_GET['item2'];
$startDate =$_GET['startDate'];
$endDate =$_GET['endDate'];
if ($db_found) {
$sql = "INSERT INTO Items (uID, item1, item2, startDate, endDate) VALUES ('$uID','$item1','$item2','$startDate','$endDate');";
//$cleanSQL = str_replace("%20"," ",$sql);
$result = mysql_query($sql);
mysql_close($db_handle);
print "Records added to the database";
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
There's a many problems with this code, but it's impossible to diagnose what precisely is causing the problem you describe on the basis of the limited information provided. A few observations:
You definitely need to percent escape the date string. The space is not acceptable in a URL (nor the body of a standard x-www-form-urlencoded request).
If you are inserting data, you should be issuing POST request, not adding this stuff to a URL, in effect issuing GET request.
You should not be issuing request with dataWithContentsOfURL. Not only is that GET, but it's synchronous and doesn't report the error.
If you still have problems, you should observe this request with Charles or similar tool. Observe the same request that you have working via web browser and compare and contrast.
Personally, when I have problems, I temporarily change my PHP code to return the data I passed to it, so I can make sure that everything was received correctly. It's a simple, but effective, way to confirm that everything was received properly.
If you are passing date strings to the server, you generally should use GMT timezone, to avoid problems stemming from the server not knowing what time zone the user's device is located. Likewise, you should use en_US_POSIX locale, to avoid problems with non-gregorian calendars. See Apple Technical Q&A 1480.
Pulling that all together, you end up with something more like:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; // if you REALLY want to use local timezone, eliminate this line, but I'd really advise sticking with GMT when using formatters to create and parse date strings that you're sending to a remote server
NSString *strToday = [dateFormatter stringFromDate:[NSDate date]];
NSURL *url = [NSURL URLWithString:#"http://www.TESTSERVER.com/Items.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *body = [[NSString stringWithFormat:#"uID=123456789&item1=30&item2=5&startDate=%#&endDate=%#", strToday, strToday] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"]; // not necessary, but good practice
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// use the data/error/response objects here
if (data) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"responseString = %#", responseString);
} else {
NSLog(#"error = %#", error);
NSLog(#"response = %#", response);
}
}];
[task resume];
// don't try to use the string here, because the above happens asynchronously
Frankly, I don't like this overly simplistic mechanism of setting the body (if any of the fields included special characters like + or &, the above wouldn't work). But if the parameters are precisely as you've outlined them in your question, this simplistic solution should work. But, if you want something a little more robust in this regard, see the encodePostParameters method shown in https://stackoverflow.com/a/22887238/1271826.
By the way, I'd suggest considering using AFNetworking, as that gets you out of the weeds of manually constructing requests.
But, going back to your original question, we cannot advise you further without seeing the server code or you doing more debugging (Charles, confirming that the values are correctly being received, etc.).
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
I'm trying to retrieve json data from mysql database in iphone. This is my .php file.
I would like to retrieve this data so that I have some code in my .m
- (void)jsonParse{
NSString* path = #"http://phdprototype.tk/getResultData.php";
NSURL* url = [NSURL URLWithString:path];
NSString* jsonString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary* resultDic = [dic objectForKey:#"maxid"];
NSString* recData = [resultDic objectForKey:#"recommendData"];
NSString* rData = [resultDic objectForKey:#"room"];
NSString* lData = [resultDic objectForKey:#"level"];
NSLog(#"recommendData = %#, room = %#, level = %#",recData,rData,lData);}
What I expect is to get data from recommendData, room, and level, but the debugger windows shows it did not get anything. This is what the debugger shows
2014-03-12 15:13:21.500 Semantic Museum[24289:907] recommendData = (null), room = (null), level = (null)
do I miss something??
Looks a problem with the server response headers.
I am seeing the Content-Type come back as
text/html
but it should be something like
application/json
This issue is coming because it's static text(try to View Source in your browser, it's returning extra parameter with JSON). If it's JSON, you need to check that from PHP the header value is set properly.
Within my application, I am trying to post the gps coordinates of a users position to a server for storage so that I can eventually design a map that displays all the users locations. I am using HTTP get and a custom PHP API to handle the data passing from app to db. The problem I have is, every time didUpdateLocations is called, I update the server. It works sometimes, but then sometimes my query string says there is an undefined variable and blank data is being posted int he db. Why is sometimes it undefined, and sometimes not? Also, is there a better way to handle the data passing? I was going to use ASIHTTPRequest but I am using ARC and so that is no help to me.
Code:
- (void)postLocationUpdateFor:(NSString *)deviceToken withDeviceID:(NSString*)deviceID withLatitude:(NSString *)latitude andLongitude:(NSString *)longitude {
NSString *apiURL = [NSString stringWithFormat:ServerApiURL2, deviceToken, deviceID, latitude, longitude];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:apiURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *currentLocation = [locations lastObject];
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] stringForKey:#"deviceToken"];
NSString *latitude = [NSString localizedStringWithFormat:#"%f",currentLocation.coordinate.latitude];
NSString *longitude = [NSString localizedStringWithFormat:#"%f",currentLocation.coordinate.longitude];
NSLog(#"Entered new Location with the coordinates Latitude: %# Longitude: %#", latitude, longitude);
[self postLocationUpdateFor:#"123" withDeviceID:deviceToken withLatitude:latitude andLongitude:longitude];
}
didUpdateLocations
can be called when you actually lost your location: entered into an Elevator / building. That's why is sometimes empty.
I would check and validate that location values before I will send the server.