4

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

このコードに証明書を追加するにはどうすればよいですか?

4

2 に答える 2

4

私もこの問題と同じ問題を解決しています。おそらく、この URL と私のコードが役に立ちます。しかし、私のコードはわかりません。

  1. URL :使用済みソケットの NSStream SSL

  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];
于 2012-07-26T16:20:40.990 に答える
0

はい、HTTP について話している場合は、この投稿を見るのが理にかなっているかもしれません (ホスト名「my page.com」で示されているようです): How to use NSURLConnection to connect with SSL for an untrusted cert? NSURLClass を使用すると、全体的な設計が大幅に簡素化されます。

于 2012-05-21T15:38:25.850 に答える