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.)