【问题标题】:ssl socket in an iphone, is it possible?iphone中的ssl套接字,有可能吗?
【发布时间】:2012-05-21 15:21:06
【问题描述】:

在我的 iPhone 应用程序中,我想连接我的 SSL 服务器套接字(Java 语言)。我有自己的证书。我正在尝试将其添加到我的应用程序中,但我不知道该怎么做。

没有 SSL,通信正常:

@interface ViewController ()

@end

@implementation ViewController
@synthesize openResponse;
@synthesize general; 
@synthesize response = _response;

- (void)viewDidLoad
{
 [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{ 
[self setOpenResponse:nil];
[self setGeneral:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (IBAction)open:(id)sender {
    [self initNetworkCommunication];


Byte sendBuffer[4];
sendBuffer[0]=0x6b;
sendBuffer[1]=0x6f;
sendBuffer[2]=0x6c;
sendBuffer[3]=0x61;

[outputStream write:sendBuffer maxLength:4];
 }


- (void)initNetworkCommunication{

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"mypage.com", 4444, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *) writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];

}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
 switch (streamEvent) {

    case NSStreamEventOpenCompleted: {
        NSLog(@"Stream opened");

        break;
    }

    case NSStreamEventHasBytesAvailable: {
        NSLog(@"Data!");

        if (theStream == inputStream) {

            uint8_t buffer[1024];
            int len;

            while ([inputStream hasBytesAvailable]) {
                len = [inputStream read:buffer maxLength:sizeof(buffer)];
                if (len > 0) {

                    NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                    if (nil != output) {
                        NSLog(@"server said: %@", output);
                        self.response = output;
                        NSString *responseData =[[NSString alloc] initWithFormat:@"El servidor dice: %@",self.response];
                        self.openResponse.text = responseData;
                    }
                }
            }
        }
        break;

        break;
    }


    case NSStreamEventErrorOccurred: {
        NSLog(@"Can not connect to the host!");

        break;
    }
    case NSStreamEventEndEncountered: {
        NSLog(@"End encountered");

        break;
    }
    default:
        NSLog(@"Unknown event");
        break;
}
}

@end

如何将我的证书添加到此代码中?

【问题讨论】:

标签: iphone objective-c sockets ssl


【解决方案1】:

我也在解决与这个问题相同的问题。 可能,这个 URL 和我的代码对你有帮助。 但我的代码不确定。

  1. 网址:NSStream SSL on used socket

  2. 代码

NSData *pkcs12data = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"EGNF9784" ofType:@"pfx"]];
CFDataRef inPKCS12Data = (CFDataRef)pkcs12data;

CFStringRef password = CFSTR("enblinkPass");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password };        
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);

CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);

OSStatus securityError = SecPKCS12Import(inPKCS12Data, options, &items);        
CFRelease(options);     
CFRelease(password);        
[pkcs12data release];

if(securityError == errSecSuccess) 
    NSLog(@"Success opening p12 certificate.");

CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef myIdent = (SecIdentityRef)CFDictionaryGetValue(identityDict,
                                                              kSecImportItemIdentity);


SecIdentityRef  certArray[1] = { myIdent };
CFArrayRef myCerts = CFArrayCreate(NULL, (void *)certArray, 1, NULL);

NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3];

[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsExpiredRoots];

[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsExpiredCertificates];

[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];

[settings setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCFStreamSSLValidatesCertificateChain];

[settings setObject:[NSString stringWithFormat:@"%@:%hu",host,port] forKey:(NSString *)kCFStreamSSLPeerName];

[settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString*)kCFStreamSSLLevel];

[settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString*)kCFStreamPropertySocketSecurityLevel];

[settings setObject:(id)myCerts forKey:(NSString *)kCFStreamSSLCertificates];

[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLIsServer];

【讨论】:

    【解决方案2】:

    是的,如果您使用的是 HTTP(如您的主机名“my page.com”所示),查看这篇文章可能很有意义:How to use NSURLConnection to connect with SSL for an untrusted cert? 使用 NSURLClass 将大大简化您的整体设计。

    【讨论】:

    • 不,它不是 HTTP,它只是一个 TCP 套接字,你可以看到端口是 4444 而不是 80
    • 端口与协议无关。我真的在推断,除非您的特定要求另有规定,否则您可能可以使用 HTTP。滚动您自己的协议可能会很棘手。
    猜你喜欢
    • 2017-12-25
    • 2011-02-09
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2011-04-17
    相关资源
    最近更新 更多