I'm trying to take a Swift string as a [UInt8] byte array, and then return the same byte array from C code and convert it back to the original Swift string. I'm trying to preserve unicode (so no lossiness in conversions/manipulations). I'm getting an error "Cannot convert value of type 'String.Encoding' to expected argument type 'UInt' on the conversion line in the decrypt function. Thanks in advance for any help!
// function to encrypt a string with custom "C" code and encode the result into a hex string
func EncryptString( password: String, stringToEncrypt: String) ->String {
var hexStr = ""
// convert the String password into utf8 bytes
let pw = password.data(using: String.Encoding.utf8, allowLossyConversion:false)
var passwordBytes : [UInt8] = Array(pw!)
// convert the string to encrypt into utf8 bytes
let bytes = stringToEncrypt.data(using: String.Encoding.utf8, allowLossyConversion:false)
var buf : [UInt8] = Array(bytes!)
// encrypt the string to encrypt with the Unicode password (both are Unicode in Swift)
encryptData(&passwordBytes, Int32(password.count), &buf, Int32(stringToEncrypt.count))
// turn the now encrypted "stringToEncrypt" into two character hex values in a string
for byte in buf {
hexStr.append(String(format:"%2X", byte))
}
// return the encrypted hex encoded string to the caller...
return hexStr
}
func DecryptString( password: String, hexStringToDecrypt: String) ->String {
var decryptedStr = ""
// convert the String password into utf8 bytes
let pw = password.data(using: String.Encoding.utf8, allowLossyConversion:false)
var passwordBytes : [UInt8] = Array(pw!)
// convert the string to encrypt into utf8 bytes
let bytes = hexStringToDecrypt.data(using: String.Encoding.utf8, allowLossyConversion:false)
var buf : [UInt8] = Array(bytes!)
// encrypt the string to encrypt with the Unicode password (both are Unicode in Swift)
let bytecount = password.count
decryptData(&passwordBytes, Int32(password.count), &buf, Int32(hexStringToDecrypt.count))
// turn the now encrypted "hexStringToDecrypt" into int values here is where I get error: Cannot convert value of type 'String.Encoding' to expected argument type 'UInt'
var unicode_str = NSString(bytes: buf, length: bytecount, encoding: NSUTF32LittleEndianStringEncoding)
// return the encrypted hex encoded string to the caller...
return unicode_str
}
}
utf8. And confirm that you are using Swift 3 or later.Datatype in place ofUInt8. FurtherNSUTF32LittleEndianStringEncodingis not the correct way to convert data to the String type, you need to specify the encoding type of the bytes and that isutf8because that is how the data was created.