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.

But i get the above mentioned error when decrypting using my private key.

There are so many ways that this can go wrong. If you post a specific example — including hex dumps of the private key, the cyphertext you got from the server, and the plaintext that you’re expecting it to be — I may be able to help you figure it out.

ps It looks like you’ve been cribbing code from an old source. Specifically:

  • You’re storing the public and private key, which is no longer necessary, because SecKeyCopyPublicKey lets you derive the former from the latter.

  • You’re using SecItemCopyMatching to get the key bits, which is no longer necessary because we have SecKeyCopyExternalRepresentation.

And, while I’m not a crypto expert, there are some IMO questionable security practices here:

  • RSA is generally not a good idea these days.

  • RSA with PKCS#1 padding is a very bad idea.

  • The code you posted suggests your using RSA to encrypt your data directly. That’s a very bad idea from a cryptographic perspective. As a general rule you should use a symmetric encryption scheme, one that’s authenticated and using a random symmetric key, to encrypt your data and then use your asymmetric crypto to protect the symmetric key.

I recommend that you discuss your encryption scheme with an expert before you deploy it to customers.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

error when trying to decrypt an RSA 2048 encrypted string
 
 
Q