首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SocketRocket和iOS证书锁定

SocketRocket和iOS证书锁定
EN

Stack Overflow用户
提问于 2013-08-14 13:32:36
回答 2查看 2.9K关注 0票数 2

我目前正在使用SocketRocket作为我的iOS应用程序的WebSocket实现,并希望将我的服务器的CA固定为具有SR_SSLPinnedCertificates属性的受信任证书。我正在寻找一个加载一个或多个证书以传递到SocketRocket的好例子。我有以下代码可以工作,但我不确定它是正确的,或者是否有更直接的方法。

代码语言:javascript
复制
CFArrayRef keyref = NULL;
NSString *path = [[NSBundle mainBundle] pathForResource:@"certificate" ofType:@"p12"];
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
OSStatus status = SecPKCS12Import((__bridge CFDataRef)data, (__bridge CFDictionaryRef)[NSDictionary dictionaryWithObject:@"eftl_key_pass" forKey:(__bridge id)kSecImportExportPassphrase], &keyref);
if (status == noErr) {
    CFDictionaryRef identityDict = CFArrayGetValueAtIndex(keyref, 0);
    SecIdentityRef identityRef = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
    SecCertificateRef certRef = NULL;
    SecIdentityCopyCertificate(identityRef, &certRef);
}
EN

回答 2

Stack Overflow用户

发布于 2014-08-30 09:28:13

使用SocketRocket进行证书锁定的过程如下:

首先,我们需要从NSURLRequest初始化SocketRocket,而不是从NSURL。

代码语言:javascript
复制
NSURL *url = [[NSURL alloc] initWithString:@"wss://path-to-socket:1234"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

然后,让我们设置证书。证书必须是二进制DER格式,而不是Base64编码的PEM。证书文件应该在您的主包中。

代码语言:javascript
复制
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"myOwnCertificate" ofType:@"cer"];
NSData *certData = [[NSData alloc] initWithContentsOfFile:cerPath];
CFDataRef certDataRef = (__bridge CFDataRef)certData;
SecCertificateRef certRef = SecCertificateCreateWithData(NULL, certDataRef);
id certificate = (__bridge id)certRef;

然后,我们将请求的固定证书设置为一个数组,该数组仅包含我们之前设置的数组。

代码语言:javascript
复制
[request setSR_SSLPinnedCertificates:@[certificate]];

现在我们可以最终确定套接字了。

代码语言:javascript
复制
SRWebSocket *socket = [[SRWebSocket alloc] initWithURLRequest:request];       
[socket open];
票数 5
EN

Stack Overflow用户

发布于 2016-08-02 05:39:04

对于Swift中的代码:

代码语言:javascript
复制
if let pinnedCertificatePath = NSBundle.mainBundle().pathForResource("subdomain.yourwebsite.com", ofType: "der"),
let pinnedCertificateData = NSData(contentsOfFile: pinnedCertificatePath),
let cert = SecCertificateCreateWithData(nil, pinnedCertificateData) {
    request.SR_SSLPinnedCertificates = [cert]

    // make the websocket call!
    let ws = SRWebSocket(URLRequest: request)
    // configure the websocket
    ws.open()
} else {
    NSLog("Failed to open websocket, could not find pinned certificate!")
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18223885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档