0

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.

srinitude
  • 43
  • 7
  • In order to convert hex to base64, you really want "hex to data," and "data to base64." You already have the "data to base64." What you want is the "hex to data" portion, which is the duplicate question linked. – Rob Napier Dec 30 '16 at 17:37
  • Your misunderstanding is that `hexString.data(using: .utf8)` doesn't convert hex encoding into data. It converts UTF8 encoding into data. It does not convert "01" to 0x01. It converts it to 0x30 0x31 (the UTF8 encoding of the characters "0" and "1"). That's what the `.utf8` is telling you. – Rob Napier Dec 30 '16 at 17:38
  • @RobNapier Thanks for the feedback and linking to the duplicate question! – srinitude Dec 30 '16 at 19:03

0 Answers0