Skip to content

How to compute shared secret using EC public key x and y values and private key d value #62

@deepesh-vasthimal-cko

Description

@deepesh-vasthimal-cko

Hi

How to compute shared secret using EC public key x and y values and private key d value using the below function and i am getting back nil. I tried to decode and i can see the privateD which i am passing returns back nil from importKey method where the value of status is -4302.

Can you please help what format Data should i be passing into the computeSharedSecret for it to work in this case ?

var publicX = "2_v-MuNZccqwM7PXlakW9oHLP5XyrjMG1UVS8OxYrgA"
 var publicY = "rm1ktLmFIsP2R0YyJGXtsCbaTUesUK31Xc04tHJRolc"
 let privateD = "iyn--IbkBeNoPu8cN245L6pOQWt2lTH8V0Ds92jQmWA"
       
       let binaryPrivateData = privateDData(base64String: privateD)
       let publicKeyData = dataFromPublicXandY(x: publicX, y: publicY)
       
       let shared = try? CC.EC.computeSharedSecret(binaryPrivateData, publicKey: publicKeyData)
       print(shared) // is nil


func privateDData(base64String: String) -> Data {
       
       let base64Co = base64urlToBase64(base64url: base64String)
       //print(base64Q) // hJQWHABDBjoPHorYF5xghQ==
       let decodedDataCo = Data(base64Encoded: base64Co)
       return decodedDataCo!
   }

func dataFromPublicXandY(x: String, y:String) -> Data {
       
       var xStr = x
       var yStr = y
       
       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)
       /*Same with y and d*/
       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!)
       return keyData as Data
   }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions