I'm using the following code:
+ (void)createKeychainItem:(NSString *)name
{
// Don't create if one already exists
if ([self getKeychainItem:name] != nil) return;
NSData *encodedName = [name dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *attributes = #{
(id)kSecAttrAccount : encodedName,
(id)kSecAttrGeneric : encodedName,
(id)kSecAttrLabel : name,
(id)kSecAttrService : name,
(id)kSecClass : (id)kSecClassGenericPassword,
};
OSStatus result = SecItemAdd((CFDictionaryRef)attributes, NULL);
}
+ (NSDictionary *)getKeychainItem:(NSString *)name
{
// Build the query
NSData *encodedName = [name dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *query = #{
(id)kSecAttrAccount : encodedName,
(id)kSecAttrGeneric : encodedName,
(id)kSecAttrService : name,
(id)kSecClass : (id)kSecClassGenericPassword,
(id)kSecMatchLimit : (id)kSecMatchLimitOne,
(id)kSecReturnAttributes : (id)kCFBooleanTrue,
};
NSDictionary *output = nil;
OSStatus result = SecItemCopyMatching((CFDictionaryRef)query, (CFTypeRef *)&output);
// Convert the password if it exists
NSData *passwordData = [output objectForKey:kSecValueData];
if (passwordData != nil) {
NSMutableDictionary *mutableOutput = [[output mutableCopy] autorelease];
NSString *password = [[[NSString alloc] initWithBytes:passwordData length:passwordData.length encoding:NSUTF8StringEncoding] autorelease];
[mutableOutput setObject:password forKey:(id)kSecValueData];
output = [[mutableOutput copy] autorelease];
}
return output;
}
+ (void)updateKeychainItem:(NSString *)name value:(NSString *)value attribute:(id)attribute
{
// Get the item
NSDictionary *values = [self getKeychainItem:name];
// If we got nothing back, build it
if (values == nil) {
[self createKeychainItem:name];
}
// Create a query to update
NSData *encodedName = [name dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *query = #{
(id)kSecAttrAccount : encodedName,
(id)kSecAttrGeneric : encodedName,
(id)kSecAttrService : name,
(id)kSecClass : (id)kSecClassGenericPassword,
};
NSDictionary *attributes = nil;
if (attribute == kSecValueData) {
attributes = #{ (id)kSecValueData : [value dataUsingEncoding:NSUTF8StringEncoding] };
} else {
attributes = #{ attribute : value };
}
OSStatus result = SecItemUpdate((CFDictionaryRef)query, (CFDictionaryRef)attributes);
}
Setting a value with [self updateKeychainItem:AuthTokenIdentifer value:authToken attribute:kSecValueData]; works and I can see it in Keychain Access.
Fetching the results with NSDictionary *values = [self getKeychainItem:AuthTokenIdentifer]; works, but the kSecValueData is not set in the dictionary. Everything else is set, like the create and modified dates, just not the secure data.
Any ideas? This happens on iOS and Mac.
You need to use the attributes dictionary from getKeychainItem: to fetch the value. Something like
NSMutableDictionary *dataQuery = [attrs mutableCopy];
[dataQuery setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
[dataQuery setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
CFTypeRef resultData;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)(dataQuery), &resultData);
NSData *tokenData = CFBridgingRelease(resultData);
Related
I am using this class to load and save a userid and password to the ios keychain.
Every once in a while either the load or save is failing on a real device. I can't tell which.
Am I doing anything wrong in this code?
Is there a better way I should be doing this?
This code is based on code at https://gist.github.com/mlapointe/6e88a9f059f1cc0dabec
#import <Foundation/Foundation.h>
#interface KeychainHelper : NSObject
#property (strong, nonatomic) NSMutableDictionary * keychainItem;
- (void)saveKeychainWithUserId:(NSString *)userId andPassword: (NSString *)password;
- (NSString *)getPassword;
- (NSString *)getUserId;
#end
#import <Security/Security.h>
#interface KeychainHelper ()
#end
#implementation KeychainHelper
- (NSMutableDictionary *)createEmptyKeychainItem {
//Let's create an empty mutable dictionary:
_keychainItem = [NSMutableDictionary dictionary];
//Populate it with the data and the attributes we want to use.
_keychainItem[(__bridge id)kSecClass] = (__bridge id)kSecClassInternetPassword;
_keychainItem[(__bridge id)kSecAttrAccessible] = (__bridge id)kSecAttrAccessibleAfterFirstUnlock;
_keychainItem[(__bridge id)kSecAttrServer] = #"myapp.com";
_keychainItem[(__bridge id)kSecReturnData] = (__bridge id)kCFBooleanTrue;
_keychainItem[(__bridge id)kSecReturnAttributes] = (__bridge id)kCFBooleanTrue;
return nil;
}
- (void)saveKeychainWithUserId: (NSString *) userId andPassword: (NSString *)password {
[self createEmptyKeychainItem];
// Check if this keychain item already exists.
if(SecItemCopyMatching((__bridge CFDictionaryRef)_keychainItem, NULL) == noErr) {
// Item Already Exists == Update instead
[self updateKeychainWithUserId:userId andPassword:password];
} else {
//Item does not exist -- create new
_keychainItem[(__bridge id)kSecValueData] = [password dataUsingEncoding:NSUTF8StringEncoding];
_keychainItem[(__bridge id)kSecAttrAccount] = userId;
OSStatus sts = SecItemAdd((__bridge CFDictionaryRef)_keychainItem, NULL);
if (sts != noErr) {
NSLog(#"Error Code while inserting keychain: %d", (int)sts);
}
}
}
- (void)updateKeychainWithUserId:(NSString *)userId andPassword:(NSString *)password {
NSMutableDictionary *attributesToUpdate = [NSMutableDictionary dictionary];
attributesToUpdate[(__bridge id)kSecValueData] = [password dataUsingEncoding:NSUTF8StringEncoding];
attributesToUpdate[(__bridge id)kSecAttrAccount] = userId;
// Must set these back to false for SecItemUpdate to work
_keychainItem[(__bridge id)kSecReturnData] = (__bridge id)kCFBooleanFalse;
_keychainItem[(__bridge id)kSecReturnAttributes] = (__bridge id)kCFBooleanFalse;
OSStatus sts = SecItemUpdate((__bridge CFDictionaryRef)_keychainItem, (__bridge CFDictionaryRef)attributesToUpdate);
if (sts != noErr) {
NSLog(#"Error Code while updating keychain: %d", (int)sts);
}
}
- (NSString *)getPassword {
CFDictionaryRef result = nil;
[self createEmptyKeychainItem];
OSStatus sts = SecItemCopyMatching((__bridge CFDictionaryRef)_keychainItem, (CFTypeRef *)&result);
if (sts == noErr) {
NSDictionary *resultDict = (__bridge_transfer NSDictionary *)result;
NSData *passwordData = resultDict[(__bridge id)kSecValueData];
NSString *password = [[NSString alloc] initWithData:passwordData encoding:NSUTF8StringEncoding];
return password;
} else {
NSLog(#"No Keychain found while getting password, Error Code: %d", (int)sts);
return nil;
}
}
- (NSString *)getUserId {
CFDictionaryRef result = nil;
[self createEmptyKeychainItem];
OSStatus sts = SecItemCopyMatching((__bridge CFDictionaryRef)_keychainItem, (CFTypeRef *)&result);
if (sts == noErr) {
NSDictionary *resultDict = (__bridge_transfer NSDictionary *)result;
return resultDict[(__bridge id)kSecAttrAccount];
} else {
NSLog(#"No Keychain found while getting userId, Error Code: %d", (int)sts);
return nil;
}
}
#end
I have a class which saves an NSDictionary into KeyChain. It worked fine but suddenly, when I try to load the NSDictionary I get nil value.
This is the class:
//
// KeyChainHandler.m
//
//
#import "KeyChainHandler.h"
#define IDENTIFIER #"Identifier"
#interface KeyChainHandler ()
#property (strong, nonatomic, readwrite) NSDictionary *applicationData;
#end
#implementation KeyChainHandler
// Make this class a singleton
static KeyChainHandler *instance = nil;
+ (KeyChainHandler*)sharedKeyChain
{
#synchronized(self)
{
if (!instance) {
instance = [[self alloc] init];
}
}
return instance;
}
- (id)init
{
self = [super init];
if (self)
{
[self load];
}
return self;
}
- (void)saveObject:(NSDictionary*)data
{
self.applicationData = data;
[self storeDictionary:data toKeychainWithKey:IDENTIFIER];
}
- (NSDictionary*)load
{
NSDictionary *data = [KeyChainHandler dictionaryFromKeychainWithKey:IDENTIFIER];
self.applicationData = data;
return data;
}
- (void)remove
{
[self deleteDictionaryFromKeychainWithKey:IDENTIFIER];
}
- (void)storeDictionary:(NSDictionary*)data toKeychainWithKey:(NSString*)aKey
{
// serialize dict
NSData *serializedDictionary = [NSKeyedArchiver archivedDataWithRootObject:data];
// encrypt in keychain
// first, delete potential existing entries with this key (it won't auto update)
[self remove];
// setup keychain storage properties
NSDictionary *storageQuery = #{
(__bridge id)kSecAttrAccount: aKey,
(__bridge id)kSecValueData: serializedDictionary,
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleWhenUnlocked
};
OSStatus osStatus = SecItemAdd((__bridge CFDictionaryRef)storageQuery, nil);
if(osStatus != noErr) {
// do someting with error
}
}
+ (NSDictionary*)dictionaryFromKeychainWithKey:(NSString *)aKey
{
// setup keychain query properties
NSDictionary *readQuery = #{
(__bridge id)kSecAttrAccount: aKey,
(__bridge id)kSecReturnData: (id)kCFBooleanTrue,
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword
};
CFDataRef serializedDictionary = NULL;
OSStatus osStatus = SecItemCopyMatching((__bridge CFDictionaryRef)readQuery, (CFTypeRef *)&serializedDictionary);
if(osStatus == noErr) {
// deserialize dictionary
NSData *data = (__bridge NSData *)serializedDictionary;
NSDictionary *storedDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
return storedDictionary;
}
else {
// do something with error
return nil;
}
}
- (void)deleteDictionaryFromKeychainWithKey:(NSString*)aKey
{
// setup keychain query properties
NSDictionary *deletableItemsQuery = #{
(__bridge id)kSecAttrAccount: aKey,
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitAll,
(__bridge id)kSecReturnAttributes: (id)kCFBooleanTrue
};
CFArrayRef itemList = nil;
OSStatus osStatus = SecItemCopyMatching((__bridge CFDictionaryRef)deletableItemsQuery, (CFTypeRef *)&itemList);
// each item in the array is a dictionary
NSArray *itemListArray = (__bridge NSArray *)itemList;
for (NSDictionary *item in itemListArray) {
NSMutableDictionary *deleteQuery = [item mutableCopy];
[deleteQuery setValue:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
// do delete
osStatus = SecItemDelete((__bridge CFDictionaryRef)deleteQuery);
if(osStatus != noErr) {
// do something with error
}
}
}
#end
At AppDelegate when I print [[KeyChainHandler sharedHandler] load]; I get the correct data, then on login screen I try to do it again and I get nil. Then when I restart (just with CMD + R) the app, I don't get nil, I get the correct data again..
What seems to be the problem? maybe it's some kind of Apple's bug?
Why: call [[KeyChainHandler sharedHandler] load];, the property is already loaded at singleton creation and if changed the property would also be updated.
You do need to set the property to nil in remove.
Instead just use:
NSDictionary *dict = [KeyChainHandler sharedKeyChain].applicationData;
Note: the code is: sharedKeyChain, the example call is: sharedHandler.
So I've been trying to use the iOS 8 Network Extension Framework to setup a VPN connection when the users presses a UIButton.
I've used the following tutorial: http://ramezanpour.net/post/2014/08/03/configure-and-manage-vpn-connections-programmatically-in-ios-8/
But for some reason it keeps asking for the vpn password and shared secret. Even though I set the passwordReference and sharedSecretReference.
And if I enter these details when installing the profile it will still not work. It just doesn't do anything when starting the connection using the framework. When trying to connect using the settings app it gives a "there's no sharedSecret" error.
This is the code I use to set up the connection.
func toggleConnection(sender: UIButton) {
if(!self.connected){
self.manager.loadFromPreferencesWithCompletionHandler { (error) -> Void in
if((error) != nil) {
println("VPN Preferences error: 1")
}
else {
var p = NEVPNProtocolIPSec()
p.username = "$username"
p.serverAddress = "$vpn"
p.passwordReference = KeychainService.dataForKey("vpnPassword")!
println(p.passwordReference)
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = KeychainService.dataForKey("sharedSecret")!
println(p.sharedSecretReference)
p.localIdentifier = "vpn"
p.remoteIdentifier = "vpn"
p.disconnectOnSleep = false
self.manager.`protocol` = p
self.manager.onDemandEnabled = true
self.manager.localizedDescription = "VPN"
self.manager.saveToPreferencesWithCompletionHandler({ (error) -> Void in
if((error) != nil) {
println("VPN Preferences error: 2")
println(error)
}
else {
var startError: NSError?
self.manager.connection.startVPNTunnelAndReturnError(&startError)
if((startError) != nil) {
println("VPN Preferences error: 3")
println(startError)
}
else {
println("Start VPN")
}
}
})
}
}
}
}
These are the functions I use as a keychain reference.
class func save(service: NSString, key: String, data: NSString) {
var dataFromString: NSData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPassword, service, key, dataFromString], forKeys: [kSecClass, kSecAttrService, kSecAttrAccount, kSecValueData])
SecItemDelete(keychainQuery as CFDictionaryRef)
if data == "" { return }
var status: OSStatus = SecItemAdd(keychainQuery as CFDictionaryRef, nil)
println(status)
}
class func load(service: NSString, key: String) -> NSData? {
var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPassword, service, key, kCFBooleanTrue, kSecMatchLimitOne, kCFBooleanTrue], forKeys: [kSecClass, kSecAttrService, kSecAttrAccount, kSecReturnData, kSecMatchLimit, kSecReturnPersistentRef])
var dataTypeRef :Unmanaged<AnyObject>?
let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
println(status)
if (status != errSecSuccess) {
return nil
}
let opaque = dataTypeRef?.toOpaque()
var contentsOfKeychain: NSData? = nil
if let op = opaque {
let retrievedData = Unmanaged<NSData>.fromOpaque(op).takeUnretainedValue()
contentsOfKeychain = retrievedData
}
println(contentsOfKeychain)
return contentsOfKeychain
}
Any help is appreciated!
So I had to eventually replace the Swift library I used to access the keychain with the following Obj-C methods. This solved my problem as far as I'm currently able to tell.
+ (void) storeData: (NSString * )key data:(NSData *)data {
NSLog(#"Store Data");
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
NSData *encodedKey = [key dataUsingEncoding:NSUTF8StringEncoding];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrGeneric];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrAccount];
[dict setObject:#"VPN" forKey:(__bridge id)kSecAttrService];
[dict setObject:(__bridge id)kSecAttrAccessibleAlwaysThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
[dict setObject:data forKey:(__bridge id)kSecValueData];
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);
if(errSecSuccess != status) {
NSLog(#"Unable add item with key =%# error:%d",key,(int)status);
}
}
+ (NSData *) getData: (NSString *)key {
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
NSData *encodedKey = [key dataUsingEncoding:NSUTF8StringEncoding];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrGeneric];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrAccount];
[dict setObject:#"VPN" forKey:(__bridge id)kSecAttrService];
[dict setObject:(__bridge id)kSecAttrAccessibleAlwaysThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
[dict setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
[dict setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnPersistentRef];
CFTypeRef result = NULL;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)dict,&result);
if( status != errSecSuccess) {
NSLog(#"Unable to fetch item for key %# with error:%d",key,(int)status);
return nil;
}
NSData *resultData = (__bridge NSData *)result;
return resultData;
}
I am looking to get the Modulus and Exponent from a public key in iOS. I have looked at many different sites and looked at Apple, but cannot just get it working.
This is my code so far:
- (void)generateKeyPairPlease
{
OSStatus status = noErr;
NSMutableDictionary *privateKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary *publicKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary *keyPairAttr = [[NSMutableDictionary alloc] init];
NSData * publicTag = [NSData dataWithBytes:publicKeyIdentifier
length:strlen((const char *)publicKeyIdentifier)];
NSData * privateTag = [NSData dataWithBytes:privateKeyIdentifier
length:strlen((const char *)privateKeyIdentifier)];
SecKeyRef publicKey = NULL;
SecKeyRef privateKey = NULL;
[keyPairAttr setObject:(__bridge id)kSecAttrKeyTypeRSA
forKey:(__bridge id)kSecAttrKeyType];
[keyPairAttr setObject:[NSNumber numberWithInt:2048]
forKey:(__bridge id)kSecAttrKeySizeInBits];
[privateKeyAttr setObject:[NSNumber numberWithBool:YES]
forKey:(__bridge id)kSecAttrIsPermanent];
[privateKeyAttr setObject:privateTag
forKey:(__bridge id)kSecAttrApplicationTag];
[publicKeyAttr setObject:[NSNumber numberWithBool:YES]
forKey:(__bridge id)kSecAttrIsPermanent];
[publicKeyAttr setObject:publicTag
forKey:(__bridge id)kSecAttrApplicationTag];
[keyPairAttr setObject:privateKeyAttr
forKey:(__bridge id)kSecPrivateKeyAttrs];
[keyPairAttr setObject:publicKeyAttr
forKey:(__bridge id)kSecPublicKeyAttrs];
status = SecKeyGeneratePair((__bridge CFDictionaryRef)keyPairAttr,
&publicKey, &privateKey);
// error handling...
NSData *ppp = [NSData dataWithBytes:publicKey length:strlen((const char *)publicKey)];
NSString *responseString, *responseStringASCII, *responseStringUTF8;
responseStringASCII = [[NSString alloc] initWithData:ppp encoding:NSASCIIStringEncoding];
if (!responseStringASCII)
{
responseString = [[NSString alloc] initWithData:ppp encoding:NSUTF8StringEncoding];
}
else
{
responseStringUTF8 = [[NSString alloc] initWithData:ppp encoding:NSUTF8StringEncoding];
if(responseStringUTF8 != nil && [responseStringUTF8 length] < [responseStringASCII length])
{
responseString = [responseStringUTF8 retain];
}
else
{
responseString = [responseStringASCII retain];
}
[responseStringUTF8 release];
}
publicKeyString = responseString;
if(publicKey) CFRelease(publicKey);
if(privateKey) CFRelease(privateKey);
NSData *exp = [self getPublicKeyExp];
NSData *mod = [self getPublicKeyMod];
NSString *expString = [[NSString alloc] initWithData:exp encoding:NSUTF8StringEncoding];
NSString *modString = [[NSString alloc] initWithData:mod encoding:NSUTF8StringEncoding];
NSLog(#"exponent = %# \n modulus = %#", expString, modString);
}
- (NSData *)getPublicKeyBits: (NSString*) publicKeyIdentifier {
OSStatus sanityCheck = noErr;
NSData * publicKeyBits = nil;
CFTypeRef pk = NULL;
NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];
NSData* publicTag = [publicKeyIdentifier dataUsingEncoding:NSUTF8StringEncoding];
// Set the public key query dictionary.
[queryPublicKey setObject:(__bridge_transfer id)kSecClassKey forKey:(__bridge_transfer id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(__bridge_transfer id)kSecAttrApplicationTag];
[queryPublicKey setObject:(__bridge_transfer id)kSecAttrKeyTypeRSA forKey:(__bridge_transfer id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge_transfer id)kSecReturnData];
// Get the key bits.
sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, &pk);
if (sanityCheck != noErr)
{
publicKeyBits = nil;
}
publicKeyBits = (__bridge id)pk;
NSLog(#"public bits %#",publicKeyBits);
return publicKeyBits;
}
- (NSData *)getPublicKeyExp
{
NSData* pk = [self getPublicKeyBits:publicKeyString];
if (pk == NULL) {
return NULL;
}
int iterator = 0;
iterator++; // TYPE - bit stream - mod + exp
[self derEncodingGetSizeFrom:pk at:&iterator]; // Total size
iterator++; // TYPE - bit stream mod
int mod_size = [self derEncodingGetSizeFrom:pk at:&iterator];
iterator += mod_size;
iterator++; // TYPE - bit stream exp
int exp_size = [self derEncodingGetSizeFrom:pk at:&iterator];
return [pk subdataWithRange:NSMakeRange(iterator, exp_size)];
return pk;
}
- (NSData *)getPublicKeyMod
{
NSData* pk = [self getPublicKeyBits:publicKeyString];
if (pk == NULL) {
return NULL;
}
int iterator = 0;
iterator++; // TYPE - bit stream - mod + exp
[self derEncodingGetSizeFrom:pk at:&iterator]; // Total size
iterator++; // TYPE - bit stream mod
int mod_size = [self derEncodingGetSizeFrom:pk at:&iterator];
return [pk subdataWithRange:NSMakeRange(iterator, mod_size)];
}
- (int)derEncodingGetSizeFrom:(NSData*)buf at:(int*)iterator
{
const uint8_t* data = [buf bytes];
int itr = *iterator;
int num_bytes = 1;
int ret = 0;
if (data[itr] > 0x80) {
num_bytes = data[itr] - 0x80;
itr++;
}
for (int i = 0 ; i < num_bytes; i++) ret = (ret * 0x100) + data[itr + i];
*iterator = itr + num_bytes;
return ret;
}
However, when I get to retrieving the Modulus and Exponent from the relevant methods, they keep returning NULL?
I am trying to pull an LDAP "jpegPhoto" attribute from an openLDAP server using a iOS openLDAP framework. The framework pulls the data as a dictionary of NSStrings.
I need to convert the NSString of "jpegPhoto" (which also appears to be base64 encoded) to UIImage, with the end result being that I display the jpegPhoto as the user's image when they login.
More Info:
-(NSDictionary *)doQuery:(NSString *)query:(NSArray *)attrsToReturn {
...
while(attribute){
if ((vals = ldap_get_values_len(ld, entry, attribute))){
for(int i = 0; vals[i]; i++){
//Uncomment if you want to see all the values.
//NSLog(#"%s: %s", attribute, vals[i]->bv_val);
if ([resultSet objectForKey:[NSString stringWithFormat:#"%s",attribute]] == nil){
[resultSet setObject:[NSArray arrayWithObject:[NSString stringWithFormat:#"%s",vals[i]->bv_val]] forKey:[NSString stringWithFormat:#"%s",attribute]];
}else{
NSMutableArray *array = [[resultSet objectForKey:[NSString stringWithFormat:#"%s",attribute]] mutableCopy];
[array addObject:[NSString stringWithFormat:#"%s",vals[i]->bv_val]];
[resultSet setObject:array forKey:[NSString stringWithFormat:#"%s",attribute]];
}
}
ldap_value_free_len(vals);
};
ldap_memfree(attribute);
attribute = ldap_next_attribute(ld, entry, ber);
};
...
}
-(UIIMage *)getPhoto{
NSString *query = [NSString stringWithFormat:#"(uid=%#)",self.bindUsername];
NSArray *attrsToReturn = [NSArray arrayWithObjects:#"cn",#"jpegPhoto", nil];
NSDictionary *rs = [self doQuery:query:attrsToReturn];
NSString *photoString = [[rs objectForKey:#"jpegPhoto"] objectAtIndex:0];
NSLog(#"The photoString is: %i %#",[photoString length],#"characters long"); //returns 4
NSData *photoData = [NSData dataWithBase64EncodedString:photoString];
UIImage *userPhoto = [UIImage imageWithData:photoData];
return userPhoto;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.studentNameLabel.text = [NSString stringWithFormat:#"Hi %#!",[self.ldap getFullName]];
self.studentPhotoImage.image = [self.ldap getPhoto];
[self checkForProctor];
}
Try this code
NSData *dataObj = [NSData dataWithBase64EncodedString:beforeStringImage];
UIImage *beforeImage = [UIImage imageWithData:dataObj];
There are many similar questions in Stackoverflow.. Please refer the following links
UIImage to base64 String Encoding
UIImage from bytes held in NSString
(Since there has been no working code posted for getting the image data from LDAP, I wanted to add this answer for the benefit of future visitors.)
The missing piece was reading the binary data into an NSData object rather than an NSString when you have binary data that might contain NULL (zero) values within it, such as images or GUIDs.
value = [NSData dataWithBytes:vals[0]->bv_val length:vals[0]->bv_len];
+ (NSArray *)searchWithBaseDN:(const char *)baseDN andFilter:(const char *)filter andScope:(int)scope {
...
while(entry)
{
// create a dictionary to hold attributes
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
attribute = ldap_first_attribute(ld, entry, &ber);
while(attribute)
{
if ((vals = ldap_get_values_len(ld, entry, attribute)))
{
if (ldap_count_values_len(vals) > 1) {
NSMutableArray *values = [[NSMutableArray alloc] init];
for(int i = 0; vals[i]; i++) {
[values addObject:[NSString stringWithUTF8String:vals[i]->bv_val]];
}
[dictionary setObject:values forKey:[NSString stringWithUTF8String:attribute]];
} else {
NSObject *value = nil;
if (strcmp(attribute, "thumbnailPhoto") == 0 || strcmp(attribute, "objectGUID") == 0) {
value = [NSData dataWithBytes:vals[0]->bv_val length:vals[0]->bv_len];
} else {
value = [NSString stringWithFormat:#"%s", vals[0]->bv_val];
}
[dictionary setObject:value forKey:[NSString stringWithUTF8String:attribute]];
}
ldap_value_free_len(vals);
};
ldap_memfree(attribute);
attribute = ldap_next_attribute(ld, entry, ber);
};
...
}