Home / IOS Development / ios – Problem with decrypting a Java RSA / ECB / PKCS1Padding-encrypted string in Swift

ios – Problem with decrypting a Java RSA / ECB / PKCS1Padding-encrypted string in Swift



My iOS app needs to decrypt a string that was encrypted on a Java backend. Backend encrypts the string using these parameters: Cipher.getInstance("RSA/ECB/PKCS1

Padding").

As a simple proof of the concept, using OpenSSL from the terminal, I retrieved the private key from the pfx certificate that they sent me:

$ openssl pkcs12 -in certificate.pfx -nocerts -out key.pem -nodes
$ openssl rsa -in key.pem -out server.key

Then I hardcoded the private key as a string in my code and tried to decrypt the encrypted message using SwiftyRSA lib:

import UIKit
import SwiftyRSA

class ViewController: UIViewController {

    private let rsaPemPrivateKey = """
      -----BEGIN RSA PRIVATE KEY-----
      THE ACTUAL PRIVATE KEY...
      -----END RSA PRIVATE KEY-----
      """

    private let encryptedString = "ciSvTLKRAMqz8d8SEX8epvkyyrfAoiX28Sd1RhYbsz7oOg3/taXZxZkTeCbVeFXB8Mf8eWn2SGMcVIrmFGuxqyRoC5SluJDgrup0wcG/XRg7lrt7oD6esVBAGZT5nmS79mUoAC4CKW5cHclCh66JUysATSIvI9qrrXNUnBApGJc="

    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            try decryptWithPrivateKey()
        } catch {
            print("Exception:")
            print(error)
        }
    }

    private func decryptWithPrivateKey() throws {
        let privateKey = try PrivateKey(pemEncoded: rsaPemPrivateKey)
        let encrypted = try EncryptedMessage(base64Encoded: encryptedString)
        let clear = try encrypted.decrypted(with: privateKey, padding: SecPadding.PKCS1)

        print("Decrypted string is: (try clear.string(encoding: .utf8))")
    }
}

This results in the following error when the method encrypted.decrypted is called:

Exception:
chunkDecryptFailed(index: 0)

I also tried with other libraries, but similar errors occurred.

Here is the result with SwiftRSA lib:

Exception:
decryptionFailed(error: Optional(Error Domain=NSOSStatusErrorDomain Code=-50 "RSAdecrypt wrong input (err -1)" UserInfo={NSDescription=RSAdecrypt wrong input (err -1)}))

And here is the result with SwCrypt lib:

Exception:
decodeError

I’m not sure what could be wrong here. At first I thought the problem might be with the private key, but none of the libraries throw an exception when I instantiate their equivalent PrivateKey objects with it. Maybe the problem is with the encrypted string I am trying to decrypt, but it seems that no base64 decoding is required, EncryptedMessage the object expects a string 64-encoded string anyway.

Is there anything else I can try to decrypt this RSA / ECB / PKCS1Padding-encrypted string in Swift? (although in Java they pass the ECB as a mode of operation, it looks like they do not use the ECB under the hood, so I do not think I need to implement any custom block size control on the encrypted string as they say here).


Source link