Я сгенерировал закрытый ключ в swift, используя следующий код:
let publicKeyAttr: [NSObject: NSObject] = [
kSecAttrIsPermanent:true as NSObject,
kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.public2".data(using: String.Encoding.utf8)! as NSObject] // added this value
let privateKeyAttr: [NSObject: NSObject] = [
kSecAttrIsPermanent:true as NSObject,
kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.private2".data(using: String.Encoding.utf8)! as NSObject] // added this
var keyPairAttr = [NSObject: NSObject]()
keyPairAttr[kSecAttrKeyType] = kSecAttrKeyTypeRSA
keyPairAttr[kSecAttrKeySizeInBits] = 2048 as NSObject
keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttr as NSObject
keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAttr as NSObject
statusCode = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)
И затем я использую закрытый ключ для подписи части данных, используя алгоритм SecKeyAlgorithm.rsaEncryptionPKCS1
.
Код для подписи выглядит следующим образом:
public func sign(privateKey myPrivateKey: SecKey, value: String, base64EncodingOptions: Data.Base64EncodingOptions = []) throws -> String?
{
enum LoginErrors: Error {
case badUsername
case badPassword
}
guard #available(iOS 10.0, watchOS 3.0, tvOS 10.0, *) else {
return "Not available"
}
let data = value.data(using: .utf8)!
var error: Unmanaged<CFError>?
guard let signedData = SecKeyCreateSignature(myPrivateKey,
SecKeyAlgorithm.rsaEncryptionPKCS1,
data as CFData,
&error) as Data? else
{
return nil
}
return "(signedData.base64EncodedString())"
}
Я получаю это исключение:
[0] (null) "NSDescription" : "algid:encrypt:RSA:PKCS1: algorithm not supported by the key <SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 2048 bits, addr: 0x280a0e5a0>"