Search code examples
iosswiftaesnsdataencode

How to convert string to data with 32 bytes count in iOS Swift 3.1


How to convert string to data or NSData with 32 bytes count in iOS Swift 3.
I have a key like this:

let keyString = "hpXa6pTJOWDAClC/J6POVTjvJpMIiPAMQiTMjBrcOGw=" 

and test this code for convert to Data:

let keyData: Data = keyString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!  
let keyLength = keyData.count //44

key length is 44.
I need convert with 32 because valid key bytes count should be equals: 16 or 24 or 32 base on this cases:

let validKeyLengths = [kCCKeySizeAES128, kCCKeySizeAES192, kCCKeySizeAES256]

Solution

  • That is a Base64 encoded string, and Data(base64Encoded:) can be used to decode it, that gives exactly 32 bytes:

    let keyString = "hpXa6pTJOWDAClC/J6POVTjvJpMIiPAMQiTMjBrcOGw="
    
    if let keyData = Data(base64Encoded: keyString) {
        print(keyData.count) // 32
        print(keyData as NSData) // <8695daea 94c93960 c00a50bf 27a3ce55 38ef2693 0888f00c 4224cc8c 1adc386c>
    }
    

    Depending on where the string comes from, you might want to add the .ignoreUnknownCharacters option in order to ignore unknown characters (including line ending characters), as suggested by @l'L'l:

    if let keyData = Data(base64Encoded: keyString, options: .ignoreUnknownCharacters) { ... }