Post

Replies

Boosts

Views

Activity

error when trying to decrypt an RSA 2048 encrypted string
Getting the below error when trying to decrypt an encrypted string sent from my server. Printing description of error: ▿ Optional<Unmanaged<CFErrorRef>> ▿ some : Unmanaged<CFErrorRef> - _value : Error Domain=NSOSStatusErrorDomain Code=-50 "<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, 2048 bits (block size: 256), addr: 0x600000cb16c0>: sign - input buffer bad size (344 bytes)" UserInfo={numberOfErrorsDeep=0, NSDescription=<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, 2048 bits (block size: 256), addr: 0x600000cb16c0>: sign - input buffer bad size (344 bytes)} I generated the RSA 2048 public private key pairs using private func getRsaKeyPair()->(String,SecKey)?{ let publicKeyAttr: [NSObject: Any] = [ kSecAttrIsPermanent: true, kSecAttrApplicationTag: "com.appname.one.rsa.public".data(using: String.Encoding.utf8)!, kSecClass: kSecClassKey, kSecReturnData: kCFBooleanTrue as Any] let privateKeyAttr: [NSObject: Any] = [ kSecAttrIsPermanent:true, kSecAttrApplicationTag:"com.appname.one.rsa.private".data(using: String.Encoding.utf8)!, kSecClass: kSecClassKey, kSecReturnData: kCFBooleanTrue as Any] var keyPairAttr = [NSObject: Any]() keyPairAttr[kSecAttrKeyType] = kSecAttrKeyTypeRSA keyPairAttr[kSecAttrKeySizeInBits] = 2048 keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttr keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAttr var error: Unmanaged<CFError>? = nil let privateKey = SecKeyCreateRandomKey(keyPairAttr as CFDictionary, &error) if let privateKey { var resultPublicKey: AnyObject? let statusPublicKey = SecItemCopyMatching(publicKeyAttr as CFDictionary, &resultPublicKey) if statusPublicKey == noErr { if let publicKey = resultPublicKey as? Data { return(publicKey.base64EncodedString(), privateKey) } } } return nil } i then sent the public key to my node js server which then returned me a string encrypted with the said public key. I decrypt it as follows guard let key = data.encStr?.data(using: .utf8) else{ return } print("encStr Size: \(key.count) bytes") var error: Unmanaged<CFError>? = nil if let plaintext = SecKeyCreateDecryptedData(privateKey, .rsaEncryptionPKCS1 , key as CFData, &error) as? Data{ print("HURRAY:\(plaintext)") if let plainTextStr = String(data: plaintext, encoding: .utf8){ print(plainTextStr) } }else{ print(error.debugDescription) } But i get the above mentioned error when decrypting using my private key.
1
1
516
Feb ’24