I am using RNCryptor in Swift and C#.NET . I need a cross platform AES encryption and because of this, I am using RNCryptor. When I encrypt some plain text in Swift,I can decrypt it in Swift correctly without any error. But when I encrypt some text in C# and then I want to decrypt it in Swift,I got an error " The operation couldn’t be completed. (RNCryptorError error 2.)"
My code in C# :
public static string EncryptQRCode(string qrCodeString){
var qrEncryptor = new Encryptor ();
return qrEncryptor.Encrypt (qrCodeString, "password");
}
public static string DecryptQRCode(string qrEncryptedString){
var qrDecryptor = new Decryptor();
return qrDecryptor.Decrypt (qrEncryptedString, "password");
}
My Code in Swift:
func Encrypt(msg:String, pwd:String) -> String{
let data = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let chiper = RNCryptor.encryptData(data!, password: pwd)
let base = chiper.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let stringBase = String(data: base, encoding: NSUTF8StringEncoding)
return stringBase!
}
func Decrypt(msg:String, pwd:String) -> String{
let encodedData:NSData = NSData(base64EncodedString: msg, options: NSDataBase64DecodingOptions(rawValue: 0))!
do{
let decryptedData = try RNCryptor.decryptData(encodedData, password: pwd)
let decrypytedString = String(data: text, encoding: NSUTF8StringEncoding)
return decryptedString!
}
catch let error as NSError{
print(error.localizedDescription)
print(error.localizedDescription)
}
return "AN ERROR OCCURED"
}
For example:
"ABC", with password "behdad" in C#, Encryptor returned:
"AgHfT2VvVOorlux0Ms47K46fG5lQOP2YhYWq2KeIKh+MisCDqZfrLF+KsJyBR2EBNC3wQpaKev0X4+9uuC5vliVoHkLsEi6ZI7ZIZ8qVUEkYGQ=="
When I decrypt it in C#, it returned "ABC".
But when I pass this Base64Encoded string to my Swift Decryptor function,it returned:
RNCryptorError error 2.
For Example: qrCodeString = "ABC". public static string EncryptQRCode returns =
"AgF6P5Ya0SifSymd3LqKdH+kGMCFobiziUhwwB6/lfZgAA9N+F5h350MyigoKo9qgUpMXX3x9FxZXwUOJODL4is3R62EGvZWdJBzjSNCef7Ouw=="
The "msg" is returned data from EncryptQRCode(The Base64 Encoded String).
pwd = "password"
encoded data = <02017a3f 961ad128 9f4b299d dcba8a74 7fa418c0 85a1b8b3 894870c0 1ebf95f6 60000f4d f85e61df 9d0cca28 282a8f6a 814a4c5d 7df1f45c 595f050e 24e0cbe2 2b3747ad 841af656 7490738d 234279fe cebb>
decryptedString and decryptedData do not have values due to the error occurred.
In C# when you want to encrypt the text,you have to use Schema.V3 for encryption. Decryptor in Swift cannot identify the Schema Version of Base 64 encoded string.
string encrypted = encryptor.Encrypt (YOUR_PLAIN_TEXT, YOUR_PASSWORD,Schema.V3);