【问题标题】:How to generate a RSA key in Swift using CommonCrypto?如何使用 CommonCrypto 在 Swift 中生成 RSA 密钥?
【发布时间】:2016-01-28 22:49:01
【问题描述】:

我需要编写一个函数来在 OS X 上本地生成一个新的 RSA 私钥,并能够打印出素数、模数等。我不想使用也不存储任何东西在 Keychain 中,只需编写一个简单的命令行工具即可。

过去在 C/Objective-C 中使用 OpenSSL 生成新密钥非常容易:

RSA *keypair = RSA_generate_key(1024, 3, NULL, NULL);

但 OpenSSL 已被弃用,所以我的问题是如何使用原生 CommonCrypto 框架在 Swift 中编写等价物。它没有很好的记录,到目前为止我可以找到任何对我有用的东西。

任何人都可以分享一个代码sn-p吗?谢谢

【问题讨论】:

标签: swift openssl cryptography rsa commoncrypto


【解决方案1】:

CommonRSACryptor 标头可以在以下位置找到:

http://opensource.apple.com/source/CommonCrypto/CommonCrypto-60026/Source/CommonCryptoSPI/CommonRSACryptor.h

您可以使用以下代码创建桥接头:

typedef int32_t CCCryptorStatus;
typedef struct _CCRSACryptor *CCRSACryptorRef;
CCCryptorStatus CCRSACryptorGeneratePair(size_t keysize, uint32_t e, CCRSACryptorRef *publicKey, CCRSACryptorRef *privateKey);
CCCryptorStatus CCRSACryptorExport(CCRSACryptorRef key, void *out, size_t *outLen);
void CCRSACryptorRelease(CCRSACryptorRef key);

之后,您可以使用 Swift 中的 CCRSACryptorGeneratePair、CCRSACryptorExport、CCRSACryptorRelease 函数。

var privateKey: CCRSACryptorRef = nil
var publicKey: CCRSACryptorRef = nil
var status = CCRSACryptorGeneratePair(keySize, 65537, &publicKey, &privateKey)
guard status == noErr else {
    throw error("CCRSACryptorGeneratePair failed \(status)")
}
defer { CCRSACryptorRelease(privateKey) }
defer { CCRSACryptorRelease(publicKey) }

var privKeyDataLength = 8192
let privKeyData = NSMutableData(length: privKeyDataLength)!
var pubKeyDataLength = 8192
let pubKeyData = NSMutableData(length: pubKeyDataLength)!

status = CCRSACryptorExport(privateKey, privKeyData.mutableBytes, &privKeyDataLength)
guard status == noErr else {
    throw error("CCRSACryptorExport privateKey failed \(status)")
}
status = CCRSACryptorExport(publicKey, pubKeyData.mutableBytes, &pubKeyDataLength)
guard status == noErr else {
    throw error("CCRSACryptorExport publicKey failed \(status)")
}

privKeyData.length = privKeyDataLength
pubKeyData.length = pubKeyDataLength

SwCrypt 库做同样的事情。

【讨论】:

  • 在我的 mac (osx sierra) 上,我在 /usr/include/CommonCrypto 中找不到 CommonRSACryptor。我错过了什么?