Converting a hex string into base64 in Swift

542 Views Asked by At

Signed up for Triplebyte and they suggested the Matasano Crypto Challenges for getting used to the libraries of the particular language you'll take their tests in. I chose Swift, but I'm having trouble with the first challenge in the first set. The assignment is to convert a hex string into base 64. Tried doing it the other way around (base 64 to hex) and was able to get that, but I'm not able to get hex to base 64. Here's my code:

//: Playground - noun: a place where people can play

import Foundation

func convertToHex(base64 base64String: String) -> String {
    let data = NSData(base64Encoded: base64String)!
    return data.description
}

func convertToBase64(hex hexString: String) -> String {
    let data = NSData(data: hexString.data(using: .utf8)!)
    return data.base64EncodedString()
}

print(convertToHex(base64: "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"))
// <49276d20 6b696c6c 696e6720 796f7572 20627261 696e206c 696b6520 6120706f 69736f6e 6f757320 6d757368 726f6f6d> (Correct - this is the argument in the assigned function below)

print(convertToBase64(hex: "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"))
// NDkyNzZkMjA2YjY5NmM2YzY5NmU2NzIwNzk2Zjc1NzIyMDYyNzI2MTY5NmUyMDZjNjk2YjY1MjA2MTIwNzA2ZjY5NzM2ZjZlNmY3NTczMjA2ZDc1NzM2ODcyNmY2ZjZk (Incorrect - supposed to match the argument in the function above)

Was wondering if anyone has thoughts about what I'm exactly doing wrong. I'm just getting into Swift, as well as what the Swift Standard Library, other frameworks like Foundation and platform-specific frameworks like UIKit have to offer. I graduated from Dev Bootcamp a couple of months ago.

0

There are 0 best solutions below