In a simple methods to delete Certs by CN (the certs have previously been put there by SecItemAdd from a PKCS12 import); I am getting the error:
Property list invalid for format: 200 (property lists cannot contain objects of type 'SecIdentity')
Where based on https://developer.apple.com/documentation/security/1395547-secitemdelete I think I am following the instruction:
To delete an item identified by a transient reference, specify the
kSecMatchItemList search key with a reference returned by using the
kSecReturnRef return type key in a previous call to the
SecItemCopyMatching or SecItemAdd functions.
to the letter. Code below:
NSDictionary * attributes;
NSString * cnString = #"/CN=foo";
attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(__bridge id)(kSecClassIdentity), kSecClass,
cnString, kSecMatchSubjectContains,
kSecMatchLimitAll, kSecMatchLimit,
kCFBooleanTrue, kSecReturnRef,
nil];
CFArrayRef result;
status = SecItemCopyMatching((__bridge CFDictionaryRef)(attributes),
(CFTypeRef *)&result);
if (status == noErr) {
for(int i = 0; i < CFArrayGetCount(result); i++) {
SecIdentityRef item = (SecIdentityRef) CFArrayGetValueAtIndex(result, i);
NSLog(#"Item #%d: %#", i, item);
attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(__bridge id)(kSecClassIdentity), kSecClass,
[NSArray arrayWithObject:(__bridge id)item], kSecMatchItemList,
kSecMatchLimitOne, kSecMatchLimit,
nil];
status = SecItemDelete((__bridge CFDictionaryRef)(attributes));
if (status != noErr || status != errSecItemNotFound)
NSLog(#"Delete %d/%#failed: %ld (ignored)", i,item, status);
};
};
The output on the console is:
Item #0: <SecIdentityRef: 0xc7359ff0>
straight after the find (and if the search is widened we get an array of these).
And then from deep inside Security.dylib:
Property list invalid for format: 200 (property lists cannot contain objects of type 'SecIdentity')
To ultimately bail with:
Delete 0/<SecIdentityRef: 0xc7359ff0>failed: -50 (ignored)
What am I doing wrong?
To quote from the documentation found in the header file SecItem.h, part of the Security framework:
By default, this function deletes all items matching the specified query.
You can change this behavior by specifying one of the follow keys:
To delete an item identified by a transient reference, on iOS,
specify kSecValueRef with a item reference. On OS X, give a
kSecMatchItemList containing an item reference.
To delete an item identified by a persistent reference, on iOS,
specify kSecValuePersistentRef with a persistent reference returned by
using the kSecReturnPersistentRef key to SecItemCopyMatching or
SecItemAdd. On OSX, use kSecMatchItemList with a persistent reference
returned by using the kSecReturnPersistentRef key with
SecItemCopyMatching or SecItemAdd.
This has been fixed in the latest GM drop. Reality is now in sync with the documentation.
Related
I made one JSON string from the NSDictionary. The JSON string which I created doesn't come present the items in the order I entered keys and value pair in the NSDictionary .
Now I need all keys and value pairs returned as JSON string in alphabetic order. I tried lot of ways but not getting sorting of JSON string in alphabetic order.
Here's an example of the way the final string is being presented:
{
"SubscriberID" : "603",
"Amount" : "1",
"MerchantID" : "100012",
"Channel" : "Wallet",
"RequestCode" : "0331",
"PosID" : "0465F35F5577CUST",
"TID" : "0000014",
"Stan" : "NA"
}
How do I ensure the items are presented the way I entered them? Or how can I specify the items are alphabetically sorted?
SBJson is able to do this, set sortKeys to YES on SBJsonWriter
http://superloopy.io/json-framework/
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
writer.sortKeys = YES;
// Turn on humanReadable if you also need it pretty-printed
// writer.humanReadable = YES;
NSData *result = [writer dataWithObject:myDictionary];
Like many key-value storage classes, NSDictionary does not guarantee order of the elements you've added. It is a mistake to assume that the key/value pairs, or keyset, will be returned with any particular order.
Further, JSON objects are unordered in the same fashion. You should not care about the order in which the objects are added. Nor should you (or your recipient) rely on being provided a JSON object with 'sorted' keys, as that's not really a valid concept with these particular structures. While ordering the keys might result in an iterator traversing the keys in the order you expect, it's not a guarantee, and should not be relied on.
I think you should revisit why you need the keys sorted in the first place, and see if you can find a way to avoid a dependency on their alphabetical ordering.
Edit: You mention the server requires an SHA hash of the JSON string. If you must, you can create a sorted JSON string by sorting the keys in an NSMutableArray, then creating the JSON string from those keys.
NSMutableArray *sortedKeys = [NSMutableArray arrayWithArray:[myDict allKeys]];
[sortedKeys sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
NSMutableString *jsonString = [[NSMutableString alloc] init];
[jsonString appendString:#"{"];
for (NSString *key in sortedKeys) {
[jsonString appendFormat:#"\"%#\"", key];
[jsonString appendString:#":"];
[jsonString appendFormat:#"\"%#\"", [myDict objectForKey:key]];
[jsonString appendString:#","];
}
if ([jsonString length] > 2) {
[jsonString deleteCharactersInRange:NSMakeRange([jsonString length] - 1, 1)];
}
[jsonString appendString:#"}"];
This code hasn't been tested, so you might need to play with it a bit. Thought it would be much better if you could find a JSON library to do this for you, although you might not have as much control over the key ordering.
You can't do it (or at least you can't rely on that). JSON objects are unordered sets as you can read on JSON.org.
Actually,the system method [NSString stringWithFormat:] is what you need.So here is the easy way:
NSDictionary* inputDictionary = #{
#"SubscriberID" : #"603",
#"Amount" : #"1",
#"MerchantID" : #"100012",
#"Channel" : #"Wallet",
#"RequestCode" : #"0331",
#"PosID" : #"0465F35F5577CUST",
#"TID" : #"0000014",
#"Stan" : #"NA"
};
NSString* sortedJsonStr = [NSString stringWithFormat:#"%#", inputDictionary];
NSLog(#"sorted json string is %#", sortedJsonStr);
The result is:
{
Amount = 1;
Channel = Wallet;
MerchantID = 100012;
PosID = 0465F35F5577CUST;
RequestCode = 0331;
Stan = NA;
SubscriberID = 603;
TID = 0000014;
}
The question does not make sense, and therefore cannot be answered in its current form.
If you encode some JSON as {"keyB":"valueB","keyA":"valueA"}, take it's checksum, and then transmit the encoded JSON and the checksum to the remote site, the remote site has little choice but to take the checksum of the JSON as received and compare that. To do the checksum on sorted values it would have to decode the received JSON string into an NSDictionary, re-encode into "sorted" JSON, and then take the checksum of the reconstituted JSON, and that would be a lot of extra effort for no reason.
Far more likely is that there is some difference in either the way the checksum is being computed (padding of the SHA256 input, eg) or some difference in the JSON strings being used -- code page differences, escaped characters, one end is doing it on Base64 and the other not, etc.
I am using the following JSON: http://www.kb.dk/tekst/mobil/aabningstider_en.json
When I try to parse it by the key "location" as such:
// get response in the form of a utf-8 encoded json string
NSString *jsonString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
// get most parent node from json string
NSDictionary *json = [jsonString JSONValue];
// get key-path from jason up to the point of json object
NSDictionary *locations = [json objectForKey:#"location"];
NSLog( #"%#", locations );
// iterate through all of the location objects in the json
for (NSDictionary *loc in locations )
{
// pull library name from the json object
NSString *name = [loc valueForKey:#"name"];
// add library data table arrays respectively
[ libraryNames addObject: ( ( name == nil | name.length > 0 ) ? name : #"UnNamed" ) ];
}
When I print the the object locations via NSLog:
{
address = "Universitetsparken 4, 3. etage, 2100 K\U00f8benhavn \U00d8";
desc = "";
lastUpdated = "";
latlng = "55.703124,12.559596";
link = "http://www.farma.ku.dk/index.php?id=3742";
name = "Faculty of Pharmaceutical Sciences Library";
parts = {
part = {
hour = {
day = "5.June Constitution Day (Denmark)";
open = Closed;
};
hours = {
hour = {
day = Friday;
open = "10-16";
};
};
name = main;
};
};
}
Which is only the last value for the "location" keys. Am I doing something wrong?
I tried validating the JSON via http://jsonlint.com/, however when I'd put in the JSON URL as above, it said "valid" - still only the last "locations" key was shown", however if I copy-paste it, it will not validate the JSON, and has to be fixed by removing new-lines from the string.
Also, when i try to parse the JSON and get the "name" fields, I get the following exception:
2012-05-08 15:37:04.941 iPhone App Tabbed[563:f803] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x68bfe70> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.'
*** First throw call stack:
(0x13dc052 0x156dd0a 0x13dbf11 0x9d2f0e 0x941841 0x940ca9 0x4593 0xf964e 0x114b89 0x1149bd 0x112f8a 0x112e2f 0x1148f4 0x13ddec9 0x365c2 0x3655a 0x25b569 0x13ddec9 0x365c2 0x3655a 0xdbb76 0xdc03f 0xdbbab 0x25dd1f 0x13ddec9 0x365c2 0x3655a 0xdbb76 0xdc03f 0xdb2fe 0x5ba30 0x5bc56 0x42384 0x35aa9 0x12c6fa9 0x13b01c5 0x1315022 0x131390a 0x1312db4 0x1312ccb 0x12c5879 0x12c593e 0x33a9b 0x281d 0x2785)
terminate called throwing an exception(lldb)
It would make more sense if the "locations" tag was an array object enclosed by square brackets ([]), however right now it's only an sequence of normal key-value pairs... Sadly, that's the JSON I have to work with.
Please help and thanks a great deal! :)
Sincerely,
Piotr.
The JSON you've got to work with may be valid, but it doesn't make much sense. It has one big dictionary with the location key repeated many times. Most JSON parser will simply return the last value for the repeated key. It would be best if you could change the structure to use an array instead, but if you cannot there's still hope. You can read the stream and stuff the values from the location keys into an array as they come out of it. This is how you'd do that:
#interface BadJsonHelper : NSObject
#property(strong) NSMutableArray *accumulator;
#end
#implementation BadJsonHelper
- (void)parser:(SBJsonStreamParser *)parser foundArray:(NSArray *)array {
// void
}
- (void)parser:(SBJsonStreamParser *)parser foundObject:(NSDictionary *)dict {
[accumulator addObject:dict];
}
#end
You can drop that little helper class at the top of your file, outside the #implementation section of the class where you're doing your work. (There's no need for the #interface and #implementation being in different files.)
In your code, you would use it like this:
BadJsonHelper *helper = [[BadJsonHelper alloc] init];
helper.accumulator = [NSMutableArray array];
SBJsonStreamParserAdapter *adapter = [[SBJsonStreamParserAdapter new] init];
adapter.delegate = helper;
adapter.levelsToSkip = 1;
SBJsonStreamParser *parser = [[SBJsonStreamParser alloc] init];
parser.delegate = adapter;
switch ([parser parse: responseData]) {
case SBJsonStreamParserComplete:
NSLog(#"%#", helper.accumulator);
break;
case SBJsonStreamParserWaitingForData:
NSLog(#"Didn't get all the JSON yet...");
break;
case SBJsonStreamParserError:
NSLog(#"Error: %#", parser.error);
break;
}
This example was originally adapted from the following test:
https://github.com/stig/json-framework/blob/master/Tests/StreamParserIntegrationTest.m
Update: I created a fully functional example project that loads the JSON asynchronously and parses it. This is available from github.
The JSON is valid, however there is a basic problem regarding the definition of the array of items.
Instead of defining an array of locations using brackets, the JSON redefines the same location key/value pair over and over again. In other words JSON initially says the value of location is the collection with name "The Black Diamond", but immediately after it redefines it with the collection with name "Faculty Library of Humanities" and so on till the last location Faculty of Pharmaceutical Sciences Library".
The same is true for parts and hours.
If you can't fix the result of the JSON and you really need to get it working you may want to modify the JSON removing the "location" keys and adding brackets properly.
Edit
Alternatively you may use an NSScanner and process the JSON result manually. Kinda hacky but it will work as long as the JSON format doesn't change significantly.
Edit
This snipped of code should do the work...
NSString *jsonString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
int indx = 1;
for (;;)
{
NSRange locationRange = [jsonString rangeOfString:#"\"location\":"];
if (locationRange.location == NSNotFound) break;
jsonString = [jsonString stringByReplacingCharactersInRange:locationRange
withString:[NSString stringWithFormat:#"\"location%d\":", indx++]];
}
NSDictionary *locations = [json objectForKey:#"location"];
As you can see, the result of JSON parsing by SBJson is a NSDictionary. A dictionary contains key/value pairs, and the keys are unique identifiers for the pairs.
The JSON data you need to handle is valid but not a good one. Per RFC 4627 - 2.2:
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.
Things like jQuery can parse the JSON also, but the result is the same as SBJson (the last one as the one). See Do JSON keys need to be unique?.
It is not a MUST, but it's still not a good practice. It would be much easier if you are able to change the structure of the JSON data on the server side (or even on the client side after receiving it) rather than parsing it as is.
I use this code http://wiki.effectiveprogramming.com/index.php?title=CocoaEncryption&redirect=no in my application to implement Login function. But I have a error method saveRSAPublicKey:
+ (BOOL)saveRSAPublicKey:(NSData*)publicKey appTag:(NSString*)appTag overwrite:(BOOL)overwrite {
//Error here (when first call) - Program received signal: "EXC_BAD_ACCESS" -> crash
OSStatus status = SecItemAdd((CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassKey, kSecClass,
(id)kSecAttrKeyTypeRSA, kSecAttrKeyType,
(id)kSecAttrKeyClassPublic, kSecAttrKeyClass,
kCFBooleanTrue, kSecAttrIsPermanent,
[appTag dataUsingEncoding:NSUTF8StringEncoding], kSecAttrApplicationTag,
publicKey, kSecValueData,
kCFBooleanTrue, kSecReturnPersistentRef,
nil],
NULL); //don't need public key ref
DebugLog(#"result = %#", [KeychainUtil fetchStatus:status]);
if(status == noErr)
return YES;
else if(status == errSecDuplicateItem && overwrite == YES)
return [CryptoUtil updateRSAPublicKey:publicKey appTag:appTag];
return NO;
}
When I call saveRSAPublickey for first time, I can't create OSStatus and my application is crashed.
When I call saveRSAPublickey for second time: status == errSecDuplicateItem and run [CryptoUtil updateRSAPublicKey:publicKey appTag:appTag] -> success.
It's difficult to find this problem when debugging because it just only appear in new device ( have never been installed my app). Finally, I have found the error by the way: set new appTag before call saveRSAPublicKey. I see in system.log:
Apr 6 12:30:29 MACs-MacBook-Pro securityd[4372]: unable to access hwaes key
Please help me !!!
Thanks all.
If you pass NULL for the 2nd arg (where your result would come out), then you're not allowed to have a Return Type Key set when calling SecItemAdd() (change kCFBooleanTrue, kSecReturnPersistentRef to kCFBooleanFalse, kSecReturnPersistentRef or just delete it).
I submitted a bug report on this just now.
I would guess that publicKey or, more likely, appTag don't contain what you think they do. Try logging them out.
I am developing an App that stores contacts in the address book . I would like to add notes field in my implementation , I know that to add a phone number this is the code to be used :
ABMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiRealPropertyType);
ABMultiValueAddValueAndLabel(multiPhone, (__bridge_retained CFStringRef)Tel, kABWorkLabel, NULL);
ABMultiValueAddValueAndLabel(multiPhone, (__bridge_retained CFStringRef)Fax, kABPersonPhoneWorkFAXLabel, NULL);
ABRecordSetValue(contact, kABPersonPhoneProperty, multiPhone, nil);
CFRelease(multiPhone);
I know that the equivalent of kABPersonPhoneProperty is kABNoteProperty but what is the equivalent of kABWorkLabel for the note field?
Thanks
The note property, identified by kABNoteProperty, is a single-value property, not a multi-value property, so there's no corresponding label. The phone property is multi-value: it can contain several different values at the same time, so you need labels to distinguish the values. The note property is like the first name or last name property -- these can only have one value at a time. Use ABRecordSetValue() for this:
bool ABRecordSetValue (
ABRecordRef record,
ABPropertyID property,
CFTypeRef value,
CFErrorRef *error
);
There is no equivalent of kABWorkLabel for kABNoteProperty, because the note property is a single string, not a multivalue.
CFErrorRef error;
if (!ABRecordSetValue(contact, kABNoteProperty, (__bridge CFStringRef)#"hello world", &error)) {
// handle error
}
I am writing an iPhone app using S7Graphview and I have saved some dates and results to a .plist as keys and values in a dictionary, both as strings. My plist looks like this:
<dict>
<key>2011-05-11</key>
<string>23</string>
<key>2011-05-12</key>
<string>23</string>
<key>2011-05-13</key>
<string>23</string>
<key>2011-05-14</key>
<string>43</string>
<key>2011-06-14</key>
<string>43</string>
</dict>
Then I use this loop to load those values into the graphview:
NSMutableDictionary* dictionary = [[NSMutableDictionary alloc]init];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
int i = 1;
if ([dictionary count] > 0) {
for (NSString* key in dictionary){
NSString* verdiString = [dictionary objectForKey:key];
CGFloat verdi = [verdiString intValue];
NSDate *dato = [[NSDate alloc]init];
NSLog(#"key=%# value=%#", key, [dictionary objectForKey:key]);
dato = [self stringTilDato:key];
[items.list_ addObject:[[GraphInfo alloc] initWithID:i name:verdiString value:verdi date:dato]];
i++;
}
}
The "stringTilDato" method converts the date string to a NSDate. The values get loaded into the items.list, but in the wrong order! The NSLog reports:
key=2011-05-14 value=43
key=2011-05-13 value=23
key=2011-05-12 value=23
key=2011-06-14 value=43
key=2011-05-11 value=23
key=2011-05-14 value=43
key=2011-05-13 value=23
key=2011-05-12 value=23
key=2011-06-14 value=43
key=2011-05-11 value=23
(Don't know why it goes through the keys twice, btw, but I dont't believe that's important). I thought the keys would be read alphabetically, or at least in the order of the plist. Why does the plist get loaded into the dictionary in this order, or is it my loading loop that is the problem?
Hope there is someone out there who can help me :)
A dictionary is not an ordered data structure. You can assume no particular order of the keys, and adding or removing a key can change the order completely. If you need an ordered data structure then use an array, or after getting all the keys sort them.
The documentation for NSDictionary says specifically:
The order of the elements in the array
is not defined.
However, if you want the keys sorted in a particular order, there are at least three methods that return a sorted array of keys. Look at the NSDictionary reference page for methods starting with "keysSortedBy..."
Dictionaries do not ensure an ordered key output. If you want the keys displayed in a particular order, you will have to sort them prior to accessing their values and printing the result.