如何在Swift中计算ECDH共享密钥以匹配NodeJs中生成的密钥

klh5stk1  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(400)

我在NodeJS中生成ECDH共享密钥,我想在Swift(iOS)中生成相同的共享密钥。我需要它的工作与secp256k1secp224r1曲线生成的关键字。
在NodeJS中,我的代码看起来像这样:

import crypto from 'node:crypto'

const keyPair2 = {
    privateKey: Buffer.from(
      'iUfaS6XxDCOS65sGqeunCQJR4045pTA3H4cCcYqfLpg',
      'base64'
    ),
    publicKey: Buffer.from(
      'BJPPEL/HhVR4Yv8qyKT/1A8rcRhmP8aXBKCikXeShNhjWWWKjDuKt9zco7Flt9l14uJW1lt2kCIjb8e64wDW5Sg=',
      'base64'
    ),
  }

  const ecdh1 = crypto.createECDH('secp256k1')
  ecdh1.setPrivateKey(keyPair1.privateKey)
  const sharedSecret1 = ecdh1.computeSecret(keyPair2.publicKey)

  const ecdh2 = crypto.createECDH('secp256k1')
  ecdh2.setPrivateKey(keyPair2.privateKey)
  const sharedSecret2 = ecdh2.computeSecret(keyPair1.publicKey)

  // sharedSecret1 and sharedSecret2 are the same: "/SW/mVsgNNqXq42c6n6RsxPHdX1nJn3srPJ61IN1fPE="

现在,在Swift中,我查看了SwiftEEC库。到目前为止,我得出了以下结论:

import SwiftECC

func base64ToPrivateKey(x: String) throws -> ECPrivateKey? {
    if let data = Data(base64Encoded: x) {
        let bytes = [UInt8](data)
        let bInt = BInt(magnitude: bytes)
        return try ECPrivateKey(domain: domain, s: bInt)
    }
    
    return nil
}

func base64ToPublicKey(x: String) throws -> ECPublicKey? {
    if let data = Data(base64Encoded: x) {
        let bytes = [UInt8](data)
        let withoutPrefix = bytes.dropFirst()
        let half = withoutPrefix.count / 2
        let x = [UInt8](withoutPrefix.prefix(half))
        let y = [UInt8](withoutPrefix.suffix(half))
        return try ECPublicKey(domain: domain, w: Point(BInt(magnitude: x), BInt(magnitude: y)))
    }
    return nil
}

let myPrivateKey = try base64ToPrivateKey(x: "DmuxAqe2H4Ntyuc9Vex/Zbl4+w5/sdPWBBlmJqU+pjs=")!
let otherSidePublickey = try base64ToPublicKey(x: "BJPPEL/HhVR4Yv8qyKT/1A8rcRhmP8aXBKCikXeShNhjWWWKjDuKt9zco7Flt9l14uJW1lt2kCIjb8e64wDW5Sg=")!

let sharedSecret = try myPrivateKey.keyAgreement(
    pubKey: otherSidePublickey,
    length: 32,
    // The problem is the next line. In node there is no option to specify message digest. 
    // Shared secret does not match with the one generated in node no matter what I 
    // put here.
    md: .SHA2_224,
    sharedInfo: []
)

// outputs: "myXnNz+5YDdMHJ4N1AMwsXqpxf/SJy2h0Kzo1Qw9yk8="
print(Data(sharedKey).base64EncodedString())

有没有一种方法可以在Swift中使用Node完成相同的操作?看起来keyAgreement函数正在计算一些其他值,然后是共享密钥,但SwiftECC中没有其他函数可以计算密钥之间的某种共享值。

wswtfjt7

wswtfjt71#

最后,我为SwiftECC创建了一个pull request,以添加一个函数,该函数允许您生成共享密钥,而无需对它进行散列

相关问题