Shared Secret is Nil when using CC.EC.computeSharedSecret from SwCrypt pod library iOS

不想你离开。 提交于 2020-06-17 09:55:10

问题


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 within the SwCrypt pod.

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

code

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
   }

来源:https://stackoverflow.com/questions/62310061/shared-secret-is-nil-when-using-cc-ec-computesharedsecret-from-swcrypt-pod-libra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!