2

I have encrypted a string that is output in UInt8

[107, 200, 119, 211, 247, 171, 132, 179, 181, 133, 54, 146, 206, 234, 69, 197]

How do I go about converting this into a datatype that can be concatenated into a URL that can then be decrypted with PHP? I have tried to convert it to base64 or a hexadecimal, however I could not find any information on how to do so.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
iamnickpitoniak
  • 227
  • 1
  • 4
  • 11

2 Answers2

0
let bytes: [UInt8] = [107, 200, 119, 211, 247, 171, 132, 179, 181, 133, 54, 146, 206, 234, 69, 197]
let base64String = bytes.withUnsafeBufferPointer { buffer -> String in
    let data = NSData(bytes: buffer.baseAddress, length: buffer.count)
    return data.base64EncodedStringWithOptions([])
}
print(base64String)

Output:

a8h30/erhLO1hTaSzupFxQ==
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
0

The data can not be converted directly to a string because many data bytes are not representable as string characters. The obvious choices are encoding to Base64 or hexadecimal. Apple does not supply and conversions to hexadecimal so the best choice seems to be be Base64.

let bytes: [UInt8] = [107, 200, 119, 211, 247, 171, 132, 179, 181, 133, 54, 146, 206, 234, 69, 197]

// Convert to NSData
let data = NSData(bytes: bytes, length: bytes.count)

// Convert to Base64
let base64String = data.base64EncodedStringWithOptions([])

print("base64String: \(base64String)")

Output:

base64String: a8h30/erhLO1hTaSzupFxQ==

The Base64 in most cases needs to be URL encoded due to possibly containing '/' and/or '=' character depending on the portion of the URL string. See this SO answer for URL encoding information.

Community
  • 1
  • 1
zaph
  • 111,848
  • 21
  • 189
  • 228