0

I cannot seem to find help on the net with regards to this.

I have a JSON endpoint that the SQL developer has created and I'm required to POST the following JSON to receive my data.

{
    "Command": "abc",
    "Data": "base64(xData)",
    "Signature" : "xyz"
}

Where xData is a JSON formatted data or RSA Encrypted JSON formatted data if a public key has been distributed. Signature is HashAlgorithm "SHA-256" in hex of the Base64(xdata)

I have learnt to encode base 64.

let combinedString = "sebastien"
let data = combinedString.data(using: .utf8)//Here combinedString is your string
let encodingString = data?.base64EncodedString()
print(encodingString!)

My questions are: - How do I add a SHA-256 signature on the base 64 xData? - How do I reverse the process and use the signature to confirm the xData is well received? - How do I de-encode base 64 xData?

  • 1
    SHA-256 in Swift https://stackoverflow.com/questions/25388747/sha256-in-swift, Decoding Base64 https://stackoverflow.com/questions/31859185/how-to-convert-a-base64string-to-string-in-swift Note that I am giving you two different answers for two different questions. That suggests that you question is too broad. – Sulthan Nov 13 '19 at 14:27

1 Answers1

0

Final code looks like this:

let str = "John"
if let base64Str = str.base64Encoded() {
  print("Base64 encoded string: \"\(base64Str)\"")
  let data = base64Str.sha256Signature()
  print("SHA256 Signature on the encoded base64 data: \"\(data)\"")
  if let trs = base64Str.base64Decoded() {
    print("Base64 decoded string: \"\(trs)\"")
  }
}
extension String {

    func sha256Signature() -> String{
        if let stringData = self.data(using: String.Encoding.utf8) {
            return hexStringFromData(input: digest(input: stringData as NSData))
        }
        return ""
    }

    private func digest(input : NSData) -> NSData {
        let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
        var hash = [UInt8](repeating: 0, count: digestLength)
        CC_SHA256(input.bytes, UInt32(input.length), &hash)
        return NSData(bytes: hash, length: digestLength)
    }

    private  func hexStringFromData(input: NSData) -> String {
        var bytes = [UInt8](repeating: 0, count: input.length)
        input.getBytes(&bytes, length: input.length)

        var hexString = ""
        for byte in bytes {
            hexString += String(format:"%02x", UInt8(byte))
        }

        return hexString
    }

}