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

1 Answer 1

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
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.