swift - 如何使用 CommonCrypto 在 Swift 中生成 RSA key ?

标签 swift openssl cryptography rsa commoncrypto

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

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

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

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

任何人都可以分享一个执行此操作的代码片段吗?谢谢

最佳答案

可以在以下位置找到 CommonRSACryptor header :

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图书馆做同样的事情。

关于swift - 如何使用 CommonCrypto 在 Swift 中生成 RSA key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35073656/

相关文章:

c++ - 运行 Casablanca 程序失败,在 Mac OS 上找不到 'openssl/conf.h' 文件

java - 如何实现IDEA?

c# - 在 C#.NET 中从 BlackBerry 解密 PKCS #1 v2.1 密码

ios - 组合:监听内部集合变化

ios - Swift SKView textureFromNode 出错

arrays - 拆分行而不省略 Swift 中的空行

objective-c - 找不到接受提供的参数的 'println' 的重载

java - Tomcat、OpenSSL、SSL 错误,keytool : Keystore was tampered with, 或密码不正确

java - SSL 连接重置

python - P12 中 pyOpenSSL 中的 RSA key 参数