Encrypt/Decrypt string in iOS using CryptoSwift - ios

I'm trying to encrypt a string and then decrypt it back using CryptoSwift. Here's the code:
let key: [UInt8] = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c]
let iv: [UInt8] = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
let message = "Hello there!".dataUsingEncoding(NSUTF8StringEncoding)!.arrayOfBytes()
do {
let encryptedBytes = try ChaCha20(key: key, iv: iv)!.encrypt(message)
let decryptedBytes = try ChaCha20(key: key, iv: iv)!.decrypt(encryptedBytes)
let data = NSData.withBytes(decryptedBytes)
let decrypted = String(data: data, encoding: NSUTF8StringEncoding)
print(decrypted) // this should print "Hello there!", but it doesn't
}
catch { ... }
I think this should print out "Hello there!", the original string. But instead I get this: (<48656c6c 6f207468 65726521>, 4)
Any ideas what am I doing wrong?

I figured this out. Changed this line:
let decrypted = String(data: data, encoding: NSUTF8StringEncoding)
to:
let decrypted = String(bytes: decryptedBytes, encoding: NSUTF8StringEncoding)
and it's working now.

Related

Issue in converting Base64string into string

I am trying to convert base64 string in to string format but I always get nil. My base64 string is "NWQwMDU2ZjhiZjRjYmI2M2MxZTI0NzQzNjAxMjMxMzAyMDh8NjAxMjMxMzAyMDh8NWQwMDU2Zjhi\nZjRjYmI2M2MxZTI0NzQzfDYwMTIzMTMwMjA4fG5hdmlnYXRpb25UZXN0MDA1fDIwMTktMDYtMjEg\nMDk6MzQ6MDB8MA==\n"
After decoding, Is suppose to look like this "5d0056f8bf4cbb63c1e2474360123130208|60123130208|5d0056f8bэ͌Ŕ٥ѥQشĂs3C�".
Here is my code event I tried to remove the "=\n" from string but not succeed.
func qrScanningSucceededWithCode(_ str: String?) {
scanTicketView.qrData = QRData(codeString: str)
let charsToRemove: Set<Character> = Set("=\n")
let newNumberCharacters = String(str!.filter { !charsToRemove.contains($0) })
let decodedString = String(data: Data(base64Encoded: newNumberCharacters)!, encoding: .utf8)!
print(decodedString)
}
This works:
let string = "NWQwMDU2ZjhiZjRjYmI2M2MxZTI0NzQzNjAxMjMxMzAyMDh8NjAxMjMxMzAyMDh8NWQwMDU2Zjhi\nZjRjYmI2M2MxZTI0NzQzfDYwMTIzMTMwMjA4fG5hdmlnYXRpb25UZXN0MDA1fDIwMTktMDYtMjEg\nMDk6MzQ6MDB8MA==\n"
let joined = string.replacingOccurrences(of: "\n", with: "")
if let data = Data(base64Encoded: joined) {
String(data: data, encoding: .utf8)
}

Swift 2.3 - Decode Emoji String [duplicate]

I'm trying to encode and decode Emojis to send them to my database.
I use this to encode:
var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
comentario = emojiString
}
And it works. But now I don't know how to decode the emoji.
This is the type of encode ---> \ud83d\ude1a
Your encoding code can be simplified to
func encode(_ s: String) -> String {
let data = s.data(using: .nonLossyASCII, allowLossyConversion: true)!
return String(data: data, encoding: .utf8)!
}
Note that it encodes all non-ASCII characters as \uNNNN, not only
Emojis. Decoding is done by reversing the transformations:
func decode(_ s: String) -> String? {
let data = s.data(using: .utf8)!
return String(data: data, encoding: .nonLossyASCII)
}
This returns an optional because it can fail for invalid input.
Example:
let s = "Hello 😃."
let e = encode(s)
print(e) // Hello \ud83d\ude03.
if let d = decode(e) {
print(d) // Hello 😃.
}
Of course you can also define the code as extension methods of the
String type, and you might want to choose better function names.
I fixed this. If you have a server with encode utf8mb4, then for encoding emojis use this code:
var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
comentario = emojiString
}// comentario contains the emoji encoded
DECODING:
let data = comentarios.data(using: String.Encoding.utf8, allowLossyConversion: false)
if data != nil{
let valueunicode = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue) as? String
if valueunicode != nil{
comentarios = valueunicode!
}
}//comentarios contantes the deecode string(emoji)

Decode base64 + decrypt - Swift

let originalMsg:String = "THIS IS A TEST"
let sessionData = originalMsg.dataUsingEncoding(NSUTF8StringEncoding)
var encryptedPublic:NSData = RNCryptor.encryptData(sessionData!, password: ProjectConstants.MessageEncrypt.PUBLIC_KEY)
var base64EncodedPublic:NSData = encryptedPublic.base64EncodedDataWithOptions([])
var encryptedPrivate = RNCryptor.encryptData(base64EncodedPublic, password: privateKey)
var base64EncodedString:String = encryptedPrivate.base64EncodedStringWithOptions([])
How would you decode + decrypt base64EncodedString to get the original input? I think I am struggling with the base64 decoding.
This is how you get a UTF-8 encoded NSString from a base64 string in Swift 2:
let decodedData = NSData(base64EncodedString: base64EncodedString,
options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
But if you want to decrypt, you'll just want the data:
do {
let decodedData = NSData(base64EncodedString: base64EncodedString,
options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decryptedPrivate = RNDecryptor.decryptData(decodedData, password: privateKey)
let decodedPrivate = NSData(base64EncodedData: decryptedPrivate,
options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decryptedPublic = RNDecryptor.decryptData(decodedPrivate, password: ProjectConstants.MessageEncrypt.PUBLIC_KEY)
let decryptedMessage = NSString(data: decryptedPublic, encoding: NSUTF8StringEncoding) as String
} catch {
// handle decryption errors...
}

iOS - Decrypt values encrypted by AES

I need decrypt value encrypted very similar to first example in PHP mcrypt-encrypt
This is what I know:
iv is base64 encoded
values are base64 encoded as well
After decoding both values from base64 then I should use decrypt method similar to PHP mcrypt-decrypt
I am using CryptoSwift library and I created this helper method (it needs to use parameters and not values in code, it's just until I get it working):
class func aesDecrypt(value: String, key: String) {
let vector = "8Z2IwsEwZ5lh27kFUmhiww=="
let vectorData = Data(base64Encoded: vector)
let vectorDecodedString = String(data: vectorData!, encoding: .unicode)
print("Vector decoded: \(vectorDecodedString)") // foo
let key = "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3"
let manufacture = "t0gEQWTxKgrGCOqXYOIuf6syF7nm1oCrwJVsxUJvw6e2sRQ25TgmML6vzfA3YFFe"
let keyBytes: [UInt8] = Array(key.utf8) //16
let ivBytes: [UInt8] = [UInt8](vectorData!)//Array(vectorDecodedString!.utf8)
let manufactureData = Data(base64Encoded: manufacture)
let valueInBytes = [UInt8](manufactureData!)
do {
let aes = try AES(key: keyBytes, iv: ivBytes, blockMode: .CBC)
let decryptedBytes = try aes.decrypt(valueInBytes)
let decryptedData = Data(bytes: decryptedBytes)
let decryptedString = String(bytes: decryptedBytes, encoding: .utf8)
let decryptedString2 = String(data: decryptedData, encoding: .utf8)
print("decryptedString: \(decryptedString)")
} catch let error {
print(error.localizedDescription)
// some error
}
}
Values in code I get from server. I tried AES with bytes or with strings but without luck. What's wrong with my code? How could I fix it? Thanks for help

Convert NSData to NSString using NSUTF8StringEncoding is not working for special character

I want to parse a CSV file to create a String.
I fetch the data with the Dropbox API. Let's say my CSV file contains a simple word: "école". When I try to create a String I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value.
My code:
client.files.download(path: "/\(selectedFile)", destination: destination).response { response, error in
if let (_, url) = response {
let data = NSData(contentsOfURL: url)
print("data: \(data!)")
let myString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
let csv = CSwiftV(String: myString)
} else {
print(error!)
}
}
The print("data: \(data!)") works well, it prints a bunch of hexadecimal. So I understand my data are not nil (right?).
If my CSV file contains the word "ecole" instead of "école" it works perfectly. But as far as I know, UTF-8 encoding should support special character no?
It means that your data is encoded in other code rather NSUTF8StringEncoding decode it with the same encoding
For Example
let string = "école"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
let myString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String //This is OK
let string = "école"
let data = string.dataUsingEncoding(NSUnicodeStringEncoding)
let myString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String // This will not work and myString will be nil
And please try to avoid force Unwrap (!) even if you are sure that you have data there, because you can have a crash next time you use !
I would do it like this instead:
guard let data = NSData(contentsOfURL: url),
let myString = NSString(data: data, encoding: NSUTF8StringEncoding) else {
print("something terrible happened treat error")
}
let csv = CSwiftV(String: String(myString))

Resources