计算ECDH(secp256k1)共享机密会导致错误结果

时间:2019-04-05 10:43:39

标签: swift encryption diffie-hellman ecdh

我想计算ECDH( secp256k1 )基于私钥 “5785cb919db4984453826032a411248184536c632096c647f72db4e66a8bd091” 和公钥 “0425a4ef791d8d855077c4d5dd6ca87cbda2f3296939a350e4ea57b3f0235fe1ba4d02cb29f6391675e866944065f9905a30a3e472c45c7ad7afa06143d87efa13” 共享机密

我迅速使用secp256k1

    let myPrKeyBytes: [UInt8] = [87, 133, 203, 145, 157, 180, 152, 68,
                                 83, 130, 96, 50, 164, 17, 36, 129, 132,
                                 83, 108, 99, 32, 150, 198, 71, 247, 45,
                                 180, 230, 106, 139 ,208, 145]

    let myPubKeyBytes: [UInt8] = [4, 37, 164, 239, 121, 29, 141, 133,
                                  80, 119, 196, 213, 221, 108, 168, 124,
                                  189, 162, 243, 41, 105, 57, 163, 80,
                                  228, 234, 87, 179, 240, 35, 95, 225,
                                  186, 77, 2, 203, 41, 246, 57, 22, 117,
                                  232, 102, 148, 64, 101, 249, 144, 90,
                                  48, 163, 228, 114, 196, 92, 122, 215,
                                  175, 160, 97, 67, 216, 126, 250, 19]

    let ctx = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN))

    var publicKeyParsed = secp256k1_pubkey()

    let publicKeyParseStatus = secp256k1_ec_pubkey_parse(
        ctx!,
        &publicKeyParsed,
        myPubKeyBytes,
        myPubKeyBytes.count
    )

    guard publicKeyParseStatus == 1 else {

        fatalError("Couldn't parse the public key")
    }


    let sharedSecretLength = 32
    let sharedSecret = UnsafeMutablePointer<UInt8>
        .allocate(capacity: sharedSecretLength)

    let sharedSecretComputeStatus = secp256k1_ecdh(
        ctx!,
        sharedSecret,
        &publicKeyParsed,
        myPrKeyBytes
    )

    guard sharedSecretComputeStatus == 1 else {

        fatalError("Couldn't compute shared secret")
    }

    var sharedSecretBytes: [UInt8] = []
    for i in 0..<sharedSecretLength {

        sharedSecretBytes.append(sharedSecret[i])
    }

    let sharedSecretStr = sharedSecretBytes
        .map { String(format: "%02x", $0) }
        .joined()

    print("Shared secret: \(sharedSecretStr)")
    // Shared secret: 4d6f4351d68351c419408621efddfcfcc0bc10270669af822093fcf22c9ca26c

我有“ 4d6f4351d68351c419408621efddfcfcc0bc10270669af822093fcf22c9ca26c”共享的机密,但正确的机密应为“ ccf231a0ce74e92d9a94265ab27aa4616a3683af5df5aa65f4a011ad83673b49”

0 个答案:

没有答案