swiftencryptionswift3base64rncryptor

Decrypt a base64 encoded and aes encrypted string using RNCryptor


I am just new to RNCryptor but I have been given a sample string which is encrypted and base64 encoded. I am trying to use the RNCryptor decrypt func to see the string in plain text.

I tried the following:

func decryptStr(_ sample : String){

    let sampleBase64Decoded = sample.fromBase64Data()

    do {
        let decryptedNSData = try RNCryptor.decrypt(data: sampleBase64Decoded!, withPassword: "secretPass")
        let decryptedNSString = NSString(data: decryptedNSData, encoding: String.Encoding.utf8.rawValue)
        print("decrypted : \(decryptedNSString)")
    }
    catch let error as NSError {
        print("issue decrypting :\(error.localizedDescription)")
    }

}

and I am calling it like so:

decryptStr("R79gQDNTt/0+cjU7pduqfA==")

and the fromBase64 looks like so:

extension String {

func fromBase64() -> String? {
    guard let data = Data(base64Encoded: self, options: NSData.Base64DecodingOptions(rawValue: 0)) else {
        return nil
    }

    return String(data: data, encoding: String.Encoding.utf8)!
}

}

I am receiving the error connect.RNCryptor.Error error 2. Why would this be? Is it in any way related to the fact that the string is both base 64 encoded and also encrypted?

The password is correct.


Solution

  • Your Base-64 data (R79gQDNTt/0+cjU7pduqfA==) is not an RNCryptor message (the first byte is incorrect, and it's too short).

    There is no "standard" format for AES encryption. You have to match the decryptor to the encryptor. RNCryptor implements a specific format that implements important security benefits that are missing in most ad hoc solutions. If this data comes from a server, you'll need to use an RNCryptor implementation there as well, or rewrite your Swift code to implement whatever format your server is using (this looks like an ad hoc custom format, so I can't say how to implement that).