reza_khalafi
reza_khalafi

Reputation: 6554

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]

Upvotes: 3

Views: 3489

Answers (2)

Martin R
Martin R

Reputation: 539995

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) { ... }

Upvotes: 8

adamfowlerphoto
adamfowlerphoto

Reputation: 2751

The function below will give you a 32 byte block of data generated from your key string. As you are using the AES keys length from the Common Crypto library I assume you have access to the rest of the library and CC_SHA256() will be available to you

static func sha256Hash(_ string: String) -> Data? {
    let len = Int(CC_SHA256_DIGEST_LENGTH)
    let data = string.data(using:.utf8)!
    var hash = Data(count:len)

    let _ = hash.withUnsafeMutableBytes {hashBytes in
        data.withUnsafeBytes {dataBytes in
            CC_SHA256(dataBytes, CC_LONG(data.count), hashBytes)
        }
    }
    return hash
}

Upvotes: 0

Related Questions