Giter Site home page Giter Site logo

samkeychain's Introduction

SAMKeychain

Version CocoaPods Carthage compatible

SAMKeychain is a simple wrapper for accessing accounts, getting passwords, setting passwords, and deleting passwords using the system Keychain on Mac OS X and iOS.

Adding to Your Project

Simply add the following to your Podfile if you're using CocoaPods:

pod 'SAMKeychain'

or Cartfile if you're using Carthage:

github "soffes/SAMKeychain"

To manually add to your project:

  1. Add Security.framework to your target
  2. Add SAMKeychain.h, SAMKeychain.m, SAMKeychainQuery.h, and SAMKeychainQuery.m to your project.

SAMKeychain requires ARC.

Note: Currently SAMKeychain does not support Mac OS 10.6.

Working with the Keychain

SAMKeychain has the following class methods for working with the system keychain:

+ (NSArray *)allAccounts;
+ (NSArray *)accountsForService:(NSString *)serviceName;
+ (NSString *)passwordForService:(NSString *)serviceName account:(NSString *)account;
+ (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account;
+ (void)setAccessibilityType:(CFTypeRef)accessibilityType;
+ (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account;

Easy as that. (See SAMKeychain.h and SAMKeychainQuery.h for all of the methods.)

Documentation

Use prepared documentation

Read the online documentation.

Debugging

If your saving to the keychain fails, use the NSError object to handle it. You can invoke [error code] to get the numeric error code. A few values are defined in SAMKeychain.h, and the rest in SecBase.h.

NSError *error = nil;
SAMKeychainQuery *query = [[SAMKeychainQuery alloc] init];
query.service = @"MyService";
query.account = @"soffes";
[query fetch:&error];

if ([error code] == errSecItemNotFound) {
    NSLog(@"Password not found");
} else if (error != nil) {
	NSLog(@"Some other error occurred: %@", [error localizedDescription]);
}

Obviously, you should do something more sophisticated. You can just call [error localizedDescription] if all you need is the error message.

Disclaimer

Working with the keychain is pretty sucky. You should really check for errors and failures. This library doesn't make it any more stable, it just wraps up all of the annoying C APIs.

You also really should not use the default but set the accessibilityType. kSecAttrAccessibleWhenUnlocked should work for most applications. See Apple Documentation for other options.

Thanks

This was originally inspired by EMKeychain and SDKeychain (both of which are now gone). Thanks to the authors. SAMKeychain has since switched to a simpler implementation that was abstracted from SSToolkit.

A huge thanks to Caleb Davenport for leading the way on version 1.0 of SAMKeychain.

samkeychain's People

Contributors

andraskadar avatar blommegard avatar calebd avatar danielyuen avatar dcu avatar dorshorst avatar edgy360 avatar elfanek avatar eugene-gubin avatar fxtentacle avatar gabriel avatar grigorym avatar hashier avatar hyperspacemark avatar imaks avatar jparise avatar jpsim avatar lgauthier avatar lufthansa747 avatar mattshedlick avatar mau888 avatar mbbischoff avatar nicolasgomollon avatar paulmelnikow avatar radex avatar sanekgusev avatar soffes avatar sonnyfazio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

samkeychain's Issues

Setting Password data?

I just updated to the newest version of SSKeychain, but only has setPassword using a nsstring, what happened to setPasswordData?

iOS 8 issues (simulator: errSecDefault, device: errSecParam)

I'm having two issues doing unit testing for some keychain code in iOS 8 Beta 3 (today's release).

  1. On the simulator, I'm unable to write to the keychain in XCTest-based application unit tests. I get errSecDefault whenever I try to call a save method.
  2. On the device, running the same unit tests, I get a different error. This time, it's a later delete operation in the tests that fails, with errSecParam.

Perhaps these are new or existing iOS 8 beta bugs. Anyone else seeing this?

SSKeychainQuery how does accessGroup work?

Hi,

I'm trying to play around with SSKeychainQuery but what value should I set as the accessGroup to be sure to share between two iOS applications?

Could you give an example of accessGroup value? "com.mycompany.myapp" ?

I tried something like this on my second app:

    SSKeychainQuery *query = [[SSKeychainQuery alloc] init];
    query.accessGroup = @"com.mycompany.myapp";
    query.password = password;
    query.account = account;
    [query save:error];

But I can't manage to get a password.

Keychain Group not working in release build configs

I've been setting up an Apple Watch app which shares a keychain with its parent app. Things have been working out fine in the debug build configuration, but unfortunately when i try to make a release build it stops working. I verified this by turning off all optimizations and sure enough it worked again. Any idea for a workaround/fix?

Using SSKeychain v 1.2.2

Alway get error -34018 when enter foreground .

Hi everyone , I use sskeychain in a simple project for test .
And I found a strange thing , If I press the home button let my sample app enter background .
Than I go to select other apps on my iphone6+ , ex camera , FaceTime ,podcast ... etc
About 10 apps , after than go back to the my app , It always get data fail , and the error code is -34018.
Does anyone has the same issue lime mine ???

SSKeychain/SSKeychainQuery.h file not found.

Hi, I added the SSKeychain class files manually as mentioned in the read me. Also added the Header Search path to the folder. Still I am getting this error. Following are the steps i followed

To manually add to your project:

  1. Add Security.framework to your target
  2. Add SSKeychain.h, SSKeychain.m, SSKeychainQuery.h, and SSKeychainQuery.m to your project.

Very slow

SSKeychain save passwords more than 5 times slower than SFHFKeychainUtils. This is really strange. So, if your save 10 passwords on iPhone 4S there is gonna be lag for about 1/4 sec.

passwordCString is not zeroterminated

code like below seems imperfect bc passwordCString is actually not null terminated at least in Mac OSX 10.6.4 per my testing

OSStatus returnStatus = SecKeychainFindGenericPassword(NULL, strlen(serviceNameCString), serviceNameCString, strlen(usernameCString), usernameCString, &passwordLength, (void **)&passwordCString, &item);
if (returnStatus != noErr || !item) {       
    return nil;
}
NSString *passwordString = [NSString stringWithCString:passwordCString encoding:NSUTF8StringEncoding];

Renaming SSKeychainQuery's method from `delete:` to `deleteItem:` should have been done by bumping the MAJOR version of the library

Commit 9677aae renamed the method, but only the minor version number was bumped. This violates semantic versioning because this is an incompatible API change. (Cocoapods are expected to follow semantic versioning.)

This change is insidious because the compiler wont flag calls to delete:UIResponder adds delete: to NSObject via a class category, but doesn't provide a default implement there.

FYI @soffes

NSString from NSData

Hello,
I'm having troubles to retrieve NSString from a previous generated NSData from RNCryptor.
In my app I generate an NSData from NSString using RNCryptor. This NSData is stored in Keychain ( previously converted to base 64 NSString ).
When I need this information, I retrieve this NSString from keychaing and convert to NSData ( using reverse base 64 ).

Once I have this NSDate I apply RNDecryptor in order to have the original NSString.
The problem I have is that RNDecryptor returns an NSData that I try to convert into NSString using NSUTF8StringEncoding but it returns an error.

 NSData *data=[RNDecryptor decryptData:datafrombase64 withPassword:pass error:&error];
    if(error){
        return NO;
    }
    NSString *srcString=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Does someone know the way to retrieve NSString?
Thanks

i18n is broken in pod

When I pod install this project, I do not get en.lproj/SSKeychain.strings. The only way I can find to attach readable error messages to the strings is to add SSKeychain.strings to my own project's en.lproj etc.

This seems wrong. I would think the pod itself should contain the .strings file, so that when more strings are added, they update through cocoapods.

No keychain item being created in Snow Leopard

Being trying to debug an issue in Snow Leopard where no entries get created in the keychain. I receive no errors from SSKeychain but don't see anything listed in Keychain Access. The same code is working perfectly fine on Lion and many other machines I have sent the app out to.

Are there any known issues with SSKeychain under Snow Leopard or anyone know why it might not be working without firing up an error?

Apart from that, love SSKeychain it has made working with the Keychain much easier!

Thanks!

Invalid characters produce uncaught exceptions

When an active SSKeychain attempts a write to the sec API with credentials containing characters that are non-traditional (not letters or integers), the sec API will throw a muted exception (I say that because it is undetectable without a breakpoint on lines 222 and 234), which can also be caught with a breakpoint on all exceptions. The problem, being, that in setting said breakpoint on all exceptions, the exception will cause the program currently being debugged to exit through main().

The credential server on OS X obviously has a problem with usernames for services such as email, and as such, SSKeychain should default to the more appropriate SecKeychainAdd/FindInternetPassword methods for these types of credentials in order to avoid this exception.

No sync with iCloud

Hello!
Shouldn't SSKeychain passwords be synced with other devices?

I write the password with:
[SSKeychain setPassword:passw forService:@"Login" account:user];
Which works local, but the other device (both with 7.1.1) don't get the account data.

I test it with:
NSArray *arr=[SSKeychain accountsForService:@"Login"];
for (NSString *s in arr) {
NSLog(@"Account: %@",s);
}
As result I get (only one of more entries):

2014-05-10 20:01:48.765 LocalButler[13695:60b] Account: {
acct = "[email protected]";
agrp = "3B4384Z34A.de.gondomir.LocalButler";
cdat = "2014-05-10 11:34:57 +0000";
mdat = "2014-05-10 11:34:57 +0000";
pdmn = ak;
svce = Login;
sync = 0;
tomb = 0;
}
But only the local accounts are shown. Do I miss something?

XCTest on device

Hi.

When starting the tests on the simulator there are no failed tests, however when starting the tests on the device the tests fail with the following error

SSKeychain[268] <Error>:  SecOSStatusWith error:[-34018] The operation couldn’t be completed. (OSStatus error -34018 - Remote error : The operation couldn’t be completed. (OSStatus error -34018 - client has neither application-identifier nor keychain-access-groups entitlements))

Any help on this is appreciated.

Thanks.

Project path must be added to Header Search Paths when manually added to project

I'm not sure if I'm being silly here, but when adding the project as a submodule I get error:

[...]/Frameworks/sskeychain/SSKeychain/SSKeychain.h:9:9: 'SSKeychain/SSKeychainQuery.h' file not found

In order to allow the app to compile I have added "$(SRCROOT)/Frameworks/sskeychain" to my Header Search Paths value in both my main target and my test target. This was not required until the 97e07c2 commit

A couple of notes about the project:

  • I'm using Xcode 6.3 and Swift
  • SSKeychain is added via a submodule:
[submodule "Frameworks/sskeychain"]
    path = Frameworks/sskeychain
    url = https://github.com/soffes/sskeychain

If I've simply included the project wrong that'd be great, but this could simply be a limitation of Xcode/the project, I have no idea.

Error -34018 (errSecDefault)

Sometimes I'd see the following error

(lldb) po error
Error Domain=com.samsoffes.sskeychain Code=-34018 "errSecDefault" UserInfo=0x17d3f070 {NSLocalizedDescription=errSecDefault}

But I have no idea what errSecDefault (code -34018) means nor how to resolve it. Any ideas?

Keychain Sharing

I found a discussion thread in the past that talked about adding the capability of keychain sharing to SSKeychain, specifically access group. I also found a commit with code changes addressing this issue. However, in the latest version, I only found accessGroup in SSKeychainQuery, but there is no way to set this property through SSKeychain.

I wonder what is the correct way of setting access group using this library. Thanks!

Developer ID signed Mac apps using SSKeychain constantly log errors.

Hi Sam!

Thanks so much for SSKeychain, it's a huge help. I am working on a developer ID signed Mac app at the moment and I noticed that every time I call an SSKeychain method, I am getting the following logged in console:

2015-02-19 4:35:36.855 PM secd[327]:  securityd_xpc_dictionary_handler Top Hat[68317] copy_matching The operation couldn’t be completed. (OSStatus error -34018 - client has neither application-identifier nor keychain-access-groups entitlements)
2015-02-19 4:35:36.855 PM Top Hat[68317]:  SecOSStatusWith error:[-34018] The operation couldn’t be completed. (OSStatus error -34018 - Remote error : The operation couldn‚Äôt be completed. (OSStatus error -34018 - client has neither application-identifier nor keychain-access-groups entitlements))

The issue is that this is not a Mac App Store app, so it has no entitlements file. SSKeychain is defaulting to using keychain synchronization and secd is having none of it. The app continues to work as expected but it's not ideal to be dumping stuff in logs. A work-around is to avoid the convenience methods on SSKeychain and use SSKeychainQuery directly instead, configured to SSKeychainQuerySynchronizationModeNo.

Release a new version to support carthage

There were some important things happening after the last version, so it would be nice to have a new version released. This would also fix the carthage integration (which is stated in the README but does not work).
I made my own release on my fork and now carthage integration works perfectly.

Here are the diffs since the last release: v1.2.2...master

Keychain data seems to be disappearing

SSKeychain has been working well for almost a year while I'm developing my app. I've run into a problem recently though that I haven't seem to be able to trace. Once in a while (and it seems random at times), the data I store in the keychain will now disappear. I'm not doing anything differently than before, so I'm not sure why the data isn't persisting.

I'm currently on iOS 7.1.1 on an iPhone 5S. Using Xcode6-beta6 and AppCode 3.0.4.

When I check [SSKeychain allAccounts] in debug, the array is empty.

Here's my code to create a new device ID, for example:

+ (NSUUID *)getDeviceID:(BOOL)refresh {
    NSError *error;
    NSString *deviceKey = [self getAppConfiguration:refresh][DEVICE_KEY];
    NSString *deviceUUID = [SSKeychain passwordForService:KEYCHAIN_SERVICE_IDENTIFIER account:deviceKey error:&error];
    if (deviceUUID) {
        return [[NSUUID UUID] initWithUUIDString:deviceUUID];
    }

    if (error) {
        NSLog(@"Unable to retrieve the device ID because of an error: %@", [error localizedDescription]);
    }

    // one does not exist, so create one
    NSUUID *newUUID = [NSUUID UUID];
    deviceUUID = [newUUID UUIDString];
    [SSKeychain setPassword:deviceUUID forService:KEYCHAIN_SERVICE_IDENTIFIER account:deviceKey];
    return newUUID;
}

Anyone else see this happening or have some ideas on what might be causing the issue?

Crashing on passwordObject

I am using the code currently on the branch but when unarchiveObjectWithData: is called it causes an exception. I cannot explain it and I do not know how to get around it. The exception provides no information in the latest version of Xcode.

Any ideas?

  • (id)passwordObject {
    if ([self.passwordData length]) {
    return [NSKeyedUnarchiver unarchiveObjectWithData:self.passwordData];
    }
    return nil;
    }

Error in Mac OS X: Use of undeclared identifiers `kSecReturnAttributes` and `kSecMatchLimitAll`

Importing the given SSKeychain.h and SSKeychain.m files into an OS X project gives the following errors:

Use of undeclared identifier kSecReturnAttributes
Use of undeclared identifier kSecMatchLimitAll

The readme says that SSKeychain will work for both OS X and iOS, is that true?

Are there any additional dependencies to resolve the errors listed above?

I have already added Security.framework to my target.

Will sskeychain support arm64 ?

you know, apple will reject any app that doesn't support arm64 before next Feb. That means all third-party frameworks in my project need support arm64. sskeychain is a good framework, so will it support arm64 proccessor?

Add released Carthage framework

I ran into some problems with CircleCI and distribution certificates so I thought maybe you should a prebuilt binary to the GitHub release. I built it for you and attached it my GH release.

Reset Keychain

A Reset Keychain Message, as in the apple provided "keychain wrapper" would be great!

Error in ARC project

Error at line 51 [query setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnAttributes];

Cast of C pointer type 'CFTypeRef' (aka 'const void *') to Objective-C pointer type 'id' requires a bridged cast
Use __bridge to convert directly (no change in ownership)
Use __bridge_transfer to transfer ownership of a +1 'CFTypeRef' (aka 'const void *') into ARC

After add -fno-objc-arc flag, the error was been fixed.

Hashing Passwords

Hi, thanks for developing this keychainWrapper. I followed a tutorial on raywenderlich which creates a keyChainWrapper with ability of hashing passwords which increase security of password.
do you have any idea of adding this functionality to your keychainWrapper?

NSSecureCoding requires 10.8 or iOS 6.0

Tried to add this to a project with Cocoapods,

the project is targeting 10.7

in this commit there is a switch from NSCoding to NSSecureCoding

622516e

those protocols are only available in the latest SDKs on both platforms.

should probably update the podspec file to reflect those OS requirements

What versions of iOS does this support

I need to support iOS 5.x to iOS 7.x. I noticed the Security framework was listed under iOS 7. Will this work for me? Maybe put a paragraph in your readme about supported platforms.

SSKeychain doesn't retain/restore its data when app gets updated from iTunes

First thanks for having such library 👍 .

I have been using this open source library for storing the data securely in my iOS app. Yesterday, I face an issue ,SSKeychain wasn't able to retain its data when I updated my app from v1.0 to v2.0 from iTunes.

Here is the cope snippet :

NSString *retrieveuuid = [SSKeychain passwordForService:@"com.name.appname" account:@"AppName"];
if (retrieveuuid == nil) {
    NSString *uuid  = [self createNewUUID];

    //Store the password in Keychain
    NSError *error = nil;
    [SSKeychain setPassword:uuid forService:@"com.name.appname" account:@"AppName" error:&error];

    if ([error code] == SSKeychainErrorNotFound) {
        NSLog(@"ID not found");
    }
}

Over here, I generated a unique device string and used the keychain to store the same and the app heavily depends on unique string since from iOS5 to iOS7 there are lots of transformations done by Apple in concerned to Unique Identifier, as the methods got deprecated.

So, is this something that keychain won't be able to retain its values/identifier, when the app gets updated from Apple OR am I missing out at some point. Please help out if its possible to store the Identifier permanently in device, irrelevant of Installing, uninstalling ,reset and updating the app.

Thanks,

SSKeychainQuery::save failing on iOS 8

Hi. I've run through the code with the debugger and this line is failing with return code -34018, which is currently undocumented.

status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);

I hope this helps.

What is the copyright of SSKeyChain?

Isn't copyright supposed to appear on top of SSKeychain.h, SSKeychain.m, SSKeychainQuery.h, and SSKeychainQuery.m?

And what is the copyright?

Cannot compile as framework

When using the Cocoapod flag use_frameworks! SSKeychain generates couple redefinition/duplicate errors and won't compile. I don't have a good idea of what's going on but need to use this flag so I can use a swift framework in my project :(

(Thank you so much for this library!)

Keychain sharing

Could you add support for easily sharing and finding shared keychains?

System Keychain Support

Hello,

First of all thanks for your code.

Now i want to store password and SharedSecretKey in System Keychain as i want to use that in VPN Connection so it must be stored in SYSTEM Keychain and to store in system keychain we need root access.

I have used the Helper Tool like we have in Apple's EvenBetterAuthorizationSample now i have the User's Authorization as NSData so how can i use this in you sample.

Can you guide me in this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.