SocketRocket and iOS certificate pinning

末鹿安然 提交于 2019-12-04 15:14:44

Certificate pinning with SocketRocket is done thus:

First, we need to initialize SocketRocket from an NSURLRequest, rather than from an NSURL.

NSURL *url = [[NSURL alloc] initWithString:@"wss://path-to-socket:1234"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

Then, let's set up the certificate. It's crucial that your certificate be in the binary DER format, rather than the base64-encoded PEM. The certificate file should be in your main bundle.

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;

We then set the request's pinned certificates to an array containing just the one we set up previously.

[request setSR_SSLPinnedCertificates:@[certificate]];

And now we can finalize the socket.

SRWebSocket *socket = [[SRWebSocket alloc] initWithURLRequest:request];       
[socket open];

For the code in Swift:

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!")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!