Skip to content

Instantly share code, notes, and snippets.

@espresso3389
Last active June 1, 2016 20:18
Show Gist options
  • Save espresso3389/c05519d1c7f0bed3173b58a806c74614 to your computer and use it in GitHub Desktop.
Save espresso3389/c05519d1c7f0bed3173b58a806c74614 to your computer and use it in GitHub Desktop.
Key-chain Access Test (Obj-C++)
#include <stdio.h>
#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/NSURLCredentialStorage.h>
#import <Foundation/NSURLCredential.h>
#import <Foundation/NSURLProtectionSpace.h>
#import <Foundation/NSString.h>
#import <Foundation/NSException.h>
class CredentialStore
{
public:
CredentialStore(const char* protocol, const char* hostname, int port, const char* realm)
{
@try
{
NSString* s_hostname = [NSString stringWithUTF8String: hostname];
NSString* s_protocol = [NSString stringWithUTF8String: protocol];
NSString* s_realm = [NSString stringWithUTF8String: realm];
m_protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost: s_hostname
port: port
protocol: s_protocol
realm: s_realm
authenticationMethod: NSURLAuthenticationMethodDefault];
}
@catch (NSException* e)
{
printf("%s: %s\n",
[[e name] UTF8String],
[[e reason] UTF8String]);
}
}
void setCredential(const char* userId, const char* password)
{
NSURLCredential *credential = nil;
@try
{
NSString* s_user = [NSString stringWithUTF8String: userId];
NSString* s_password = [NSString stringWithUTF8String: password];
credential = [[NSURLCredential alloc]
initWithUser: s_user
password: s_password
persistence: NSURLCredentialPersistencePermanent]; //NSURLCredentialPersistenceForSession
[[NSURLCredentialStorage sharedCredentialStorage]
setDefaultCredential: credential
forProtectionSpace: m_protectionSpace];
}
@catch (NSException* e)
{
printf("%s: %s\n",
[[e name] UTF8String],
[[e reason] UTF8String]);
}
@finally
{
if(credential)
[credential release];
}
}
void getCredential()
{
NSURLCredential *credential = nil;
@try
{
NSURLCredential *credential = nil;
credential = [[NSURLCredentialStorage sharedCredentialStorage]
defaultCredentialForProtectionSpace: m_protectionSpace];
printf("UserID: %s\nPassword: %s\n",
[[credential user] UTF8String],
[[credential password] UTF8String]);
}
@catch (NSException* e)
{
printf("%s: %s\n",
[[e name] UTF8String],
[[e reason] UTF8String]);
}
@finally
{
if(credential)
[credential release];
}
}
~CredentialStore()
{
[m_protectionSpace release];
}
NSURLProtectionSpace* m_protectionSpace;
};
int main()
{
CredentialStore store(
"http", "www.cuminas.jp", 80, "authenticate.aspx:test1");
store.setCredential("foobar", "pa$$word");
store.getCredential();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment