Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
deepesh-vasthimal-cko opened this issue Jun 10, 2020 · 0 comments

Comments

@deepesh-vasthimal-cko
Copy link

deepesh-vasthimal-cko commented Jun 10, 2020

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
   }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant