如何使用 node-forge 创建与 iOS 的 Multipeer Connectivity 兼容的 PKCS12? [英] How to create a PKCS12 compatible with iOS's Multipeer Connectivity with node-forge?

查看:37
本文介绍了如何使用 node-forge 创建与 iOS 的 Multipeer Connectivity 兼容的 PKCS12?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用 X509 证书的客户端身份验证来实现多点连接通信安全.

I am trying to achieve Multipeer Connectivity communications security through clients authentication using X509 certificate.

为此,我使用 node-forge 在我的服务器中生成客户端的证书.首先,创建 X509,然后将其转换为返回给客户端的 PKCS12 base64 字符串.

To do so, I am generating the clients' certificates in my server using node-forge. First, the X509 is created then it is transformed into a PKCS12 base64 string that is returned to the client.

这基本上就是我使用的代码:

That is basically the code I am using :

var username = "client1"

// Create key pair
var pki = forge.pki;
var keys = pki.rsa.generateKeyPair(2048);
var cert = pki.createCertificate();


// Creating the certificate
cert.publicKey = keys.publicKey;
cert.serialNumber = '01'; // TODO : generate random number and have a little custom algo to verify it !!

cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setTime(cert.validity.notBefore.getTime() + msWeek);

var subject = [{
    name : "commonName",
    value : username
}, {
    name : "organizationName",
    value : "My Company"
}, {
    name : "organizationalUnitName",
    value : "MU"
}, {
    name : "stateOrProvinceName",
    value : "Ile-de-France"
}, {
    name : "countryName",
    value : "FR"
}, {
    name : "localityName",
    value : "Paris"
}, {
    name : "emailAddress",
    value : "hello@world.com"
} ];

var issuer = [{
    name : "commonName",
    value : "MPC App"
}, {
    name : "organizationName",
    value : "My Company"
}, {
    name : "organizationalUnitName",
    value : "MU"
}, {
    name : "stateOrProvinceName",
    value : "Ile-de-France"
}, {
    name : "countryName",
    value : "FR"
}, {
    name : "localityName",
    value : "Paris"
}, {
    name : "emailAddress",
    value : "hello@world.com"
} ];
cert.setSubject(subject);
cert.setIssuer(issuer);

// Extensions 
cert.setExtensions([{
    name: 'basicConstraints',
    cA : true
} , {
    name : 'keyUsage',
    digitalSignature : true,
    keyCertSign : true,
    nonRepudiation : true,
    keyEncipherment : true,
    dataEncipherment : true
}, {
    name : 'extKeyUsage',
    clientAuth : true,
    serverAuth : false,
    codeSigning : true,
    emailProtection : false,
    timeStamping : true
}, {
    name : 'nsCertType',
    client : true,
    server : false,
    email : false,
    objsign : true,
    sslCA : false,
    emailCA : false,
    objCA : false
}]);

cert.sign(keys.privateKey);
var asn1Cert = pki.certificateToAsn1(cert);

// Create PKCS#12 from the certificate and encode to base64 string 
var p12Asn1 = forge.pkcs12.toPkcs12Asn1(keys.privateKey , cert, "iPhone");
var p12Der = forge.asn1.toDer(p12Asn1).getBytes();
return forge.util.encode64(p12Der); 

但是,当我将它导入到我的 iOS 应用程序中时,运行时不断崩溃,通过返回 errSecDecode.

However, when I import it in my iOS application, runtime keeps crashing telling me it has failed to read the contents of the PKCS#12 (different error from the bad password error though) by returning errSecDecode.

我不知道我的代码的哪一部分导致了这个错误,尽管我怀疑 扩展 是这些问题的根源,顺便说一句,我真的不知道什么适合最适合我的用例(两个客户端为彼此进行身份验证以与 MultiPeer Connectivity 通信).

I don't know which part of my code is causing this error even though I suspect the extensions to be at the origin of these issues, by the way I don't really know what suits best to my usecase (two clients authenticating themselves for each other in order to communicate with MultiPeer Connectivity).

我还想知道在将 PKCS#12 编码为 base64 字符串 时是否做错了什么?

I would also like to know if I am doing something wrong when I encode my PKCS#12 to a base64 string ?

如果有帮助,以下是我在从服务器恢复 base64 字符串后用于在 iOS 端导入 PKCS#12 的代码.>

If it helps, here is the code I'm using to import the PKCS#12 in the iOS side after recovering the base64 string from the server.

private func generateIdentity (base64p12 : String, password : String?) {
    print("gen id")
    let p12KeyFileContent = NSData(base64EncodedString: base64p12, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)

    if (p12KeyFileContent == nil) {
        NSLog("Cannot read PKCS12 data")
        return
    }

    let options = [String(kSecImportExportPassphrase):password ?? ""]
    var citems: CFArray? = nil
    let resultPKCS12Import = withUnsafeMutablePointer(&citems) { citemsPtr in
        SecPKCS12Import(p12KeyFileContent!, options, citemsPtr)
    }
    if (resultPKCS12Import != errSecSuccess) {
        print("resultPKCS12Import :", resultPKCS12Import)
        return
    }

    let items = citems! as NSArray
    let myIdentityAndTrust = items.objectAtIndex(0) as! NSDictionary
    let identityKey = String(kSecImportItemIdentity)

    identity = myIdentityAndTrust[identityKey] as! SecIdentityRef
    hasCertificate = true
    print("cert cre", identity)
} 

提前致谢

通过使用 node-forge 解码 base64 字符串,我可以看到我在创建证书时输入的信息,而且它们打印得很好,没有渲染不好的字符.

edit : By decoding the base64 string with node-forge, I can see the infos I entered when the certificate was created, also they are well printed without poorly rendered character.

现在我问自己 iOS 是否故意抛出此错误以阻止我使用不是使用其特定工具创建的证书(如果我没记错的话,Apple Keychain).

Now I am asking myself whether iOS is throwing this error on purpose to retain me from using certificates that are not created with their specific tool (Apple Keychain if I remember well).

推荐答案

显然,iOS 的安全框架要求 PKCS#12 使用 TripleDES 加密算法.

Apparently, iOS's Security Framework requires the PKCS#12 to be using TripleDES encryption algorithm.

因此,替换该行:

var p12Asn1 = forge.pkcs12.toPkcs12Asn1(keys.privateKey , cert, "iPhone");

与:

var p12Asn1 = forge.pkcs12.toPkcs12Asn1(keys.privateKey , cert, "iPhone", {algorithm : '3des'});

就像一个魅力.

此时我仍然不明白为什么 Apple 的文档在这个主题上如此详尽:/.

At this point I still don't understand why Apple's documentation is so inexhaustive on the subject :/ .

这篇关于如何使用 node-forge 创建与 iOS 的 Multipeer Connectivity 兼容的 PKCS12?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆