Hi All
I am trying to convert json jwk pulbic ec key to data format and i written below code which does that. But the data returned is 65 bytes in keyData variable below, instead of 32 bytes. Currently I am trying to pass this data of 32 bytes to GMEllipticCurveCrypto ( GMEllipticCurveSecp256r1 ) library which helps me create a shared secret but only takes in 32 bytes and if I pass this 65 bytes of data then I see a crash with error message as : Terminating app due to uncaught exception 'Invalid Key' ( reference : https://stackoverflow.com/questions/62063112/ios-creating-shared-secret-from-gmellipticcurvecrypto-using-a-public-jwk-ec-ke)
So can anyone please possibly help me generate a 32 bytes of data from public EC x and y values of public JWK key ?
var xStr = "XUvZlQ3ZYmB2kg-9fySt6Nk30ZnXAPWFa5tnIUGZuxs"
var yStr = "sHHTw0MHoiWw0lj7eOjgy95la1LOiMFpDqdolTZ1Trw"
//Padding required
xStr = xStr.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
if xStr.count % 4 == 2 {
xStr.append("==")
}
if xStr.count % 4 == 3 {
xStr.append("=")
}
yStr = yStr.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
if yStr.count % 4 == 2 {
yStr.append("==")
}
if yStr.count % 4 == 3 {
yStr.append("=")
}
let xBytes = Data(base64Encoded: xStr)
let yBytes = Data(base64Encoded: yStr)
//Now this bytes we have to append such that [0x04 , /* xBytes */, /* yBytes */, /* dBytes */]
//Initial byte for uncompressed y as Key.
let keyData = NSMutableData.init(bytes: [0x04], length: [0x04].count)
keyData.append(xBytes!)
keyData.append(yBytes!)
//keyData.append(dBytes)
let attributes: [String: Any] = [
kSecAttrKeyType as String: kSecAttrKeyTypeEC,
kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
kSecAttrKeySizeInBits as String: 256,
kSecAttrIsPermanent as String: false
]
var error: Unmanaged?
let keyReference = SecKeyCreateWithData(keyData as CFData, attributes as CFDictionary, &error)
print(keyData)