0

I need help for the following scenario. I need to convert bytes to string in Swift language. Here is my code.

let ciphertext = try aes.encrypt(Array("Password123".utf8))
print("ciphertext: \(ciphertext)")
// output ciphertext: [148, 177, 49, 193, 100, 184, 232, 51, 26, 170, 146, 114, 77, 244, 29, 172]

let nsdata = NSData(bytes: ciphertext as [UInt8], length: ciphertext.count)
print("nsdata: \(nsdata)")
// output nsdata: <94b131c1 64b8e833 1aaa9272 4df41dac>

let str = String(data: nsdata as Data, encoding: String.Encoding.utf8)
print("cipherStr: \(str)")
// output cipherStr: nil

I always got "NIL" value when I try to convert bytes to String.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
A1ucard
  • 199
  • 5
  • 16
  • Why do you need to convert Data to String? Your data it is not a String. If you just want to see a string representation of your encrypted data you can use `.ascii` instead of `.utf8` – Leo Dabus Mar 23 '18 at 04:18
  • @LeoDabus `.ascii` will still return `nil` if the data contains any bytes larger than 127. I'd say it's more likely to return `nil` than `.utf8` is (and certainly will be `nil` for this data). If you want to ensure it will succeed, you could use something like `.isoLatin1`, but I'd rather ask what you're really trying to output. Is it a hexadecimal representation of the bytes like what `NSData` logs? Because that seems more likely to me than the gibberish you'll get from interpreting this byte string in any text encoding being useful. – Charles Srstka Mar 23 '18 at 04:50
  • Possible duplicate of https://stackoverflow.com/questions/41650817/cant-convert-encrypted-data-to-string – Martin R Mar 23 '18 at 04:57
  • which library you are using for aes encrypt? – PPL Mar 23 '18 at 05:54
  • CryptoSwift @PPL – A1ucard Mar 23 '18 at 06:15

1 Answers1

0

I found the answer I want.

let ciphertext = try aes.encrypt(Array("Password123".utf8))
let base64EncodeString = ciphertext.toBase64()            
print("ciphertext: \(base64EncodeString!)")
A1ucard
  • 199
  • 5
  • 16