如何在 Rust 中获取 EC 点的 X 和 Y 坐标?

问题描述 投票:0回答:2

我正在尝试从 Rust 中的 EcKeyopenssl::pkey::Private key 中提取 X 和 Y 坐标。 我已设法将其转换为点和字节,但我不知道如何获取坐标。

pub fn exportpubkey(key: &EcKey<openssl::pkey::Private>) -> (){
    let group: EcGroup = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
    let mut ctx: BigNumContext = openssl::bn::BigNumContext::new().unwrap(); 
    let bytes = key.public_key().to_bytes(&group,openssl::ec::PointConversionForm::COMPRESSED, &mut ctx).unwrap();
    println!("{}", display_bytes(&bytes));
}
rust cryptography
2个回答
1
投票

您可能想查看方法 affine_coordinates

use openssl::{bn::*, ec::*, nid::Nid};

pub fn print_pub_key(key: &EcKey<openssl::pkey::Private>) -> () {
    let group: EcGroup = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
    let mut ctx: BigNumContext = BigNumContext::new().unwrap();
    let public_key = key.public_key();
    let mut x = BigNum::new().unwrap();
    let mut y = BigNum::new().unwrap();
    public_key
        .affine_coordinates_gfp(group.as_ref(), &mut x, &mut y, &mut ctx)
        .expect("extract coords");

    println!("{}, {}", x, y);
}

fn main() {
    let group: EcGroup = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
    let key = EcKey::generate(&group).unwrap();
    print_pub_key(&key);
}

请注意,

affine_coordinates_gfp
affine_coordinates_gf2m
似乎会在您选择的组中返回相同的坐标。


0
投票

小心!

对于任何来到这篇文章并寻找从 public key 获取 x,y 坐标的方法的人,@Cyrill 的答案中提供的方法不适合您。如果您想了解G和其他参数,您也可以访问https://neuromacer.sk/std/nist/P-224

对于那些想知道公钥的 xy 并来到此页面的人,我已经与我的同事验证了,x,y 坐标对是 G 生成器的。您可以通过将私钥替换为不同的密钥来进行双重检查,而无需更改任何其他内容,x,y 将始终相同。

fn insecure_keygen() {
    let private_key_b64 = "YOUR BASE64 ENCODED PRIVATE KEY";
    let private_key_bytes = base64::decode(private_key_b64).expect("Failed to decode base64");
    let group = EcGroup::from_curve_name(Nid::SECP224R1).expect("Failed to create EC group");
    let private_key_bn = openssl::bn::BigNum::from_slice(&private_key_bytes).expect("Failed to create BigNum");
    let private_key = EcKey::from_private_components(&group, &private_key_bn, &group.generator()).expect("Failed to create EC key");
    let mut ctx: BigNumContext = BigNumContext::new().unwrap();
    let public_key = private_key.public_key();
    let mut x = BigNum::new().unwrap();
    let mut y = BigNum::new().unwrap();
    public_key
        .affine_coordinates_gfp(group.as_ref(), &mut x, &mut y, &mut ctx)
        .expect("extract coords");

    println!("{}, {}", x, y);
}

© www.soinside.com 2019 - 2024. All rights reserved.