How do I decode a signed request in Objective-C?
Basically, how do I translate this Ruby code to Objective-C or C?
# Facebook sends a signed_requests to authenticate certain requests.
# http://developers.facebook.com/docs/authentication/signed_request/
def decode_signed_request(signed_request)
encoded_signature, encoded_data = signed_request.split('.')
signature = base64_url_decode(encoded_signature)
expected_signature = OpenSSL::HMAC.digest('sha256', #secret, encoded_data)
if signature == expected_signature
JSON.parse base64_url_decode(encoded_data)
end
rescue Exception => e
puts $!, $#
end
def base64_url_decode(string)
"#{string}==".tr("-_", "+/").unpack("m")[0]
end
SSToolKit Base64 decode NSString looks helpful.
Do you want to verify the signature on the data or just "decode" it? If it's the latter, you can just ignore the signature:
NSString *signedData = ...;
NSString *base64EncodedData = [[signedData componentsSeparatedByString:#"."] objectAtIndex:1];
NSString *jsonString = [NSString stringWithBase64String:base64EncodedData];
id jsonObject = ...;
I leave using the Facebook SDK and choosing a suitable JSON framework (I recommend JSONKit) up to you.
Your comment indicates that you want to verify the HMAC included with the message. In that case:
unsigned int length = 0;
unsigned char *expectedHmac = HMAC(EVP_sha256(), [key bytes], [key length], [base64EncodedData UTF8String], [base64EncodedData length], NULL, &length);
NSData *expectedHmacData = [NSData dataWithBytes:expectedHmac length:length];
// compare expected hmac
Related
My application uses AES 256 encryption to encrypt a string. The same code that was used before is generating a different result. This problem started when iOS 13 was released. And it happens only to applications that are shipped to the store or built with Xcode 11.
Here is the code used for the encryption:
- (NSData *)encrypt:(NSData *)plainText key:(NSString *)key iv:(NSString *)iv {
char keyPointer[kCCKeySizeAES256+2],// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053
ivPointer[kCCBlockSizeAES128+2];
BOOL patchNeeded;
bzero(keyPointer, sizeof(keyPointer)); // fill with zeroes for padding
patchNeeded= ([key length] > kCCKeySizeAES256+1);
if(patchNeeded)
{
NSLog(#"Key length is longer %lu", (unsigned long)[[self md5:key] length]);
key = [key substringToIndex:kCCKeySizeAES256]; // Ensure that the key isn't longer than what's needed (kCCKeySizeAES256)
}
//NSLog(#"md5 :%#", key);
[key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding];
[iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding];
if (patchNeeded) {
keyPointer[0] = '\0'; // Previous iOS version than iOS7 set the first char to '\0' if the key was longer than kCCKeySizeAES256
}
NSUInteger dataLength = [plainText length];
//see https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CCryptorCreateFromData.3cc.html
// For block ciphers, the output size will always be less than or equal to the input size plus the size of one block.
size_t buffSize = dataLength + kCCBlockSizeAES128;
void *buff = malloc(buffSize);
size_t numBytesEncrypted = 0;
//refer to http://www.opensource.apple.com/source/CommonCrypto/CommonCrypto-36064/CommonCrypto/CommonCryptor.h
//for details on this function
//Stateless, one-shot encrypt or decrypt operation.
CCCryptorStatus status = CCCrypt(kCCEncrypt, /* kCCEncrypt, etc. */
kCCAlgorithmAES128, /* kCCAlgorithmAES128, etc. */
kCCOptionPKCS7Padding, /* kCCOptionPKCS7Padding, etc. */
keyPointer, kCCKeySizeAES256, /* key and its length */
ivPointer, /* initialization vector - use random IV everytime */
[plainText bytes], [plainText length], /* input */
buff, buffSize,/* data RETURNED here */
&numBytesEncrypted);
if (status == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];
}
free(buff);
return nil;
}
- (NSString *) encryptPlainTextWith:(NSString *)plainText key:(NSString *)key iv:(NSString *)iv {
return [[[[CryptLib alloc] init] encrypt:[plainText dataUsingEncoding:NSUTF8StringEncoding] key:[[CryptLib alloc] sha256:key length:32] iv:iv] base64EncodedStringWithOptions:0];
}
/**
* This function computes the SHA256 hash of input string
* #param key input text whose SHA256 hash has to be computed
* #param length length of the text to be returned
* #return returns SHA256 hash of input text
*/
- (NSString*) sha256:(NSString *)key length:(NSInteger) length{
const char *s=[key cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];
uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};
CC_SHA256(keyData.bytes, (CC_LONG)keyData.length, digest);
NSData *out=[NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
NSString *hash=[out description];
hash = [hash stringByReplacingOccurrencesOfString:#" " withString:#""];
hash = [hash stringByReplacingOccurrencesOfString:#"<" withString:#""];
hash = [hash stringByReplacingOccurrencesOfString:#">" withString:#""];
if(length > [hash length])
{
return hash;
}
else
{
return [hash substringToIndex:length];
}
}
##
I would like to know if something in the code path has changed in the way it works. The method called to do the encryptions is "encryptPlainTextWith". Thanks in advance.
Inside:
- (NSString*) sha256:(NSString *)key length:(NSInteger) length
I replaced
NSString *hash=[out description];
To
NSString *hash=[out debugDescription];
And everything got back to normal. Cheers Happy coding.
Alternative Solution as per #Rob Napier
create separate function for converting NSData to Hex
#pragma mark - String Conversion
-(NSString*)hex:(NSData*)data{
NSMutableData *result = [NSMutableData dataWithLength:2*data.length];
unsigned const char* src = data.bytes;
unsigned char* dst = result.mutableBytes;
unsigned char t0, t1;
for (int i = 0; i < data.length; i ++ ) {
t0 = src[i] >> 4;
t1 = src[i] & 0x0F;
dst[i*2] = 48 + t0 + (t0 / 10) * 39;
dst[i*2+1] = 48 + t1 + (t1 / 10) * 39;
}
return [[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding];
}
After that Inside:
- (NSString*) sha256:(NSString *)key length:(NSInteger) length
I replaced
NSString *hash=[out description];
To
NSString *hash = [self hex:out];
I suspect that your key is longer than 32 UTF-8 bytes. In that case, this code is incorrect. Your patchNeeded conditional is basically creating a garbage key. The contents of buffer aren't promised if this function return returns false, but you're relying on them.
There is no secure way to truncate a key you were given, so I'm not really certain what behavior you want here. It depends on what kinds of strings you're passing.
This code is also incorrect if iv is shorter than 16 UTF-8 bytes. You'll wind up including random values from the stack. That part can be fixed with:
bzero(ivPointer, sizeof(ivPointer));
But if your previous version relied on random values, this will still be different.
Assuming you need to match the old behavior, the best way to debug this is to run your previous version in a debugger and see what keyPointer and ivPointer wind up being.
(Note that this approach to creating a key is very insecure. It's drastically shrinking the AES keyspace. How much depends on what kind of strings you're passing, but it's dramatic. You also should never reuse the same key+iv combination in two messages when using CBC, which this looks like it probably does. If possible, I recommend moving to a correct AES implementation. You can look at RNCryptor for one example of how to do that, or use RNCryptor directly if you prefer.)
I have to create a amazon MWS integration with an iOS application the issue is that I am not able to create and sign the request please help me providing some code sample would be very good if you have any.
I have tried with going through documentation and creating the string but it says that the signature is invalid
First of all You have to include the Crypto definitions to digest your Request
#import <CommonCrypto/CommonHMAC.h>
By using this function You can digest Your request. The key is the secret key provided by Amazon
NSString *calcSignature(NSString *aString, NSString *key)
{
const char *cKey = [key cStringUsingEncoding: NSUTF8StringEncoding];
const char *cData = [aString cStringUsingEncoding: NSUTF8StringEncoding];
// Calculate SHA256-signature
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
length:sizeof(cHMAC)];
// return Base64 encoded
return [HMAC base64EncodedStringWithOptions:0];
}
Digest the following sample requestString
POST /Feeds/2009-01-01 HTTP/1.1
Content-Type: x-www-form-urlencoded
Host: mws.amazonservices.com
User-Agent: <Your User Agent Header>
AWSAccessKeyId=0PExampleR2
&Action=CancelFeedSubmissions
&FeedSubmissionIdList.Id.1=1058369303
&FeedTypeList.Type.1=_POST_PRODUCT_DATA_
&FeedTypeList.Type.2=_POST_PRODUCT_PRICING_DATA_
&MWSAuthToken=amzn.mws.4ea38b7b-f563-7709-4bae-87aeaEXAMPLE
&Marketplace=ATExampleER
&SellerId=A1ExampleE6
&SignatureMethod=HmacSHA256
&SignatureVersion=2
&Timestamp=2009-02-04T17%3A34%3A14.203Z
&Version=2009-01-01
Now You can calc the signature
NSString *signatureString = calcSignature(requestString, amazonSecretKey);
These signature is appended to the request and You should get the result. You can test a little and control if You sending the correct signature by using Amazon Scratchpad.
as I'm only a beginner in this field this question may seem to be very trivial, but I beg your pardon. I've a Java code as follows:
String passwordSalt = "somesalt";
byte[] bsalt = base64ToByte(passwordSalt);
byte[] thePasswordToDigestAsBytes = ("somepassword").getBytes("UTF-8");
System.out.println("------------------------------"+passwordSalt);
MessageDigest digest = MessageDigest.getInstance("SHA-512");
digest.reset();
digest.update(bsalt);
byte[] input = digest.digest(thePasswordToDigestAsBytes);
System.out.println("------------------------------"+byteToBase64(input));
I want to achieve the same in Objective-C and I'm using the following code :
NSData *saltdata = [Base64 decode:#"some base64 encoded salt"];
NSString *passwordDgst;
passwordDgst = #"somepassword";
NSData *input = [passwordDgst dataUsingEncoding: NSUTF8StringEncoding];
unsigned char hash[CC_SHA512_DIGEST_LENGTH];
CC_SHA512_CTX context;
CC_SHA512_Init(&context);
CC_SHA512_Update(&context, [saltdata bytes], (CC_LONG)[saltdata length]);
CC_SHA512_Update(&context, [input bytes], (CC_LONG)[input length]);
CC_SHA512_Final(hash, &context);
input = [NSMutableData dataWithBytes:(const void *)hash length:sizeof(unsigned char)*CC_SHA512_DIGEST_LENGTH];
passwordDgst = [input encodeBase64WithNewlines:NO];
But this seems to generate a different hash than the Java Code? Why is that? Can anybody clarify me that? Thanks in advance :)
I am trying to create a 16 byte and later 32 byte initialization vector in objective-c (Mac OS). I took some code on how to create random bytes and modified it to 16 bytes, but I have some difficulty with this. The NSData dumps the hex, but an NSString dump gives nil, and a cstring NSLog gives the wrong number of characters (not reproduced the same in the dump here).
Here is my terminal output:
2012-01-07 14:29:07.705 Test3Test[4633:80f] iv hex <48ea262d efd8f5f5 f8021126 fd74c9fd>
2012-01-07 14:29:07.710 Test3Test[4633:80f] IV string: (null)
2012-01-07 14:29:07.711 Test3Test[4633:80f] IV char string t^Q¶�^��^A
Here is the main program:
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//NSString *iv_string = [NSString stringWithCString:iv encoding:NSUTF8StringEncoding];
testclass *obj = [testclass alloc];
NSData *iv_data = [obj createRandomNSData];
//[iv_string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"iv hex %#",iv_data);
//NSString *iv_string = [[NSString alloc] initWithBytes:[iv_data bytes] length:16 encoding:NSUTF8StringE$
NSString *iv_string = [[NSString alloc] initWithData:iv_data encoding:NSUTF8StringEncoding];
NSLog(#"IV string: %#",iv_string);
NSLog(#"IV char string %.*s",[iv_data bytes]);
return 0;
]
(I left in the above some commented code that I tried and did not work also).
Below is my random number generater, taken from a stack overflow example:
#implementation testclass
-(NSData*)createRandomNSData
{
int twentyMb = 16;
NSMutableData* theData = [NSMutableData dataWithCapacity:twentyMb];
for( unsigned int i = 0 ; i < twentyMb/4 ; ++i )
{
u_int32_t randomBits = arc4random();
[theData appendBytes:(void*)&randomBits length:4];
}
NSData *data = [NSData dataWithData:theData];
[theData dealloc];
return data;
}
#end
I am really quite clueless as to what could be the problem here. If I have data as bytes, it should convert to a string or not necessarily? I have looked over the relevant examples here on stackoverflow, but none of them have worked in this situation.
Thanks,
Elijah
An arbitrary byte sequence may not be legal UTF8 encoding. As #Joachim Isaksson notes, there is seldom reason to convert to strings this way. If you need to store random data as a string, you should use an encoding scheme like Base64, serialize the NSData to a plist, or similar approach. You cannot simply use a cstring either, since NULL is legal inside of a random byte sequence, but is not legal inside of a cstring.
You do not need to build your own random byte creator on Mac or iOS. There's one built-in called SecRandomCopyBytes(). For example (from Properly encrypting with AES with CommonCrypto):
+ (NSData *)randomDataOfLength:(size_t)length {
NSMutableData *data = [NSMutableData dataWithLength:length];
int result = SecRandomCopyBytes(kSecRandomDefault,
length,
data.mutableBytes);
NSAssert(result == 0, #"Unable to generate random bytes: %d",
errno);
return data;
}
When converting NSData to NSString using an UTF8 encoding, you won't necessarily end up with the same number of bytes since not all binary values are valid encodings of characters. I'd say using a string for binary data is a recipe for problems.
What is the use of the string? NSData is exactly the datatype you want for storing binary data to begin with.
I need to work out a decryption/encryption algorithm, but I'm confused regarding SHA256 / CBC / Salt / IV etc.
An example of a correctly encrypted string is:
U2FsdGVkX19IfIZtJ/48wk8z3ZRGDK8RD8agyQRhMrsOMsoIlVEcrzraOLo5IRBXjDkN1JUFnNrkvi2NA22IOTv00U97065tUNBQKEVXcaL0UJirtcqHlq8lN4pEm14ZokKXv8mUP8GkUKrOf37GhOugi/F/CQiILb57kIPrYPk=
It is Base64 encoded then Rijndael encoded. The first 8 characters are 'Salted__' and the next 8 characters I assume is some sort of salt (randomly generated).
The key I provided to encrypt this data is '12345678'.
The decrypted data should be:
2358442189442905:ZGF2aWQ=:1324515293:1.9.12:1:MC4wLjAuMCxub25lLzA=:LfcTMMYyUcwgL8keu3sMoNC/PFEKZy8fWFvo3rJvSdo
Apparently it is following Crypt::CBC::VERSION 2.29
I can't seem to decrypt the correctly encrypted string above. I have tried the following:
NSString *key = #"12345678";
NSData *test = [NSData dataFromBase64String:#"U2FsdGVkX19IfIZtJ/48wk8z3ZRGDK8RD8agyQRhMrsOMsoIlVEcrzraOLo5IRBXjDkN1JUFnNrkvi2NA22IOTv00U97065tUNBQKEVXcaL0UJirtcqHlq8lN4pEm14ZokKXv8mUP8GkUKrOf37GhOugi/F/CQiILb57kIPrYPk="];
unsigned char salt[8]; //get the salt out
[test getBytes:salt range:NSMakeRange(8, 8)];
NSData *saltData = [NSData dataWithBytes:salt length:8];
unsigned char data[128-16]; // remove the Salted__ and the 8 character salt
[test getBytes:data range:NSMakeRange(8, 128-8)];
test = [NSData dataWithBytes:data length:128-8];
NSMutableData *aeskey = [NSMutableData dataWithData:[key dataUsingEncoding:NSUTF8StringEncoding]];
[aeskey appendData:saltData]; // add the salt to the end of the key?
NSData *test2 = [test decryptedAES256DataUsingKey:key error:nil]; //Using a NSData+CommonCrypto library
Any ideas on how to decrypt this properly?
EDIT: more information: this is code related to what I am trying to implement.
elsif ($header_mode eq 'salt') {
$self->{salt} = $self->_get_random_bytes(8) if $self->{make_random_salt};
defined (my $salt = $self->{salt}) or croak "No header_mode of 'salt' specified, but no salt value provided"; # shouldn't happen
length($salt) == 8 or croak "Salt must be exactly 8 bytes long";
my ($key,$iv) = $self->_salted_key_and_iv($self->{passphrase},$salt);
$self->{key} = $key;
$self->{civ} = $self->{iv} = $iv;
$result = "Salted__${salt}";
}
my $self = shift;
my ($pass,$salt) = #_;
croak "Salt must be 8 bytes long" unless length $salt == 8;
my $key_len = $self->{keysize};
my $iv_len = $self->{blocksize};
my $desired_len = $key_len+$iv_len;
my $data = '';
my $d = '';
while (length $data < $desired_len) {
$d = md5($d . $pass . $salt);
$data .= $d;
}
return (substr($data,0,$key_len),substr($data,$key_len,$iv_len));
Here is an implementation that I don't fully understand: http://pastebin.com/R0b1Z7GH http://pastebin.com/aYWFXesP
unsigned char salt[8]; //get the salt out
[test getBytes:salt range:NSMakeRange(8, 8)];
NSData *saltData = [NSData dataWithBytes:salt length:8];
unsigned char data[128-16]; // remove the Salted__ and the 8 character salt
[test getBytes:data range:NSMakeRange(8, 128-8)];
test = [NSData dataWithBytes:data length:128-8];
I think in your second block of code you are copying the wrong data. Try this:
unsigned char data[128-16]; // remove the Salted__ and the 8 character salt
[test getBytes:data range:NSMakeRange(16, 128-16)];
test = [NSData dataWithBytes:data length:128-16];
Your comment indicates that you want to skip both the Salted__ and the salt itself.
Note that I haven't got a clue where the salt should go -- that's up to the protocol that you're trying to integrate with -- so I hope you've got that well-documented from another source.