You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中如何打印pqcrypto-dilithium库生成的公私钥字节变量

问题说明

开发基于pqcrypto-dilithium库的密码学项目时,需要打印Dilithium5算法生成的公钥、私钥内容,直接使用println!("{:#?}", public_key)方式打印时触发E0277报错,提示PublicKey/SecretKey类型未实现Debug trait。
涉及的代码、配置、报错信息如下:

  • 初始Rust代码
pub use pqcrypto_dilithium::dilithium5::{
    public_key_bytes as public_key_bytes,
    secret_key_bytes as secret_key_bytes, 
    signature_bytes as signature_bytes,
    verify_detached_signature as verify_detached_signature,
    detached_sign as detached_sign,
    keypair as keypair,
    open as open,
    sign as sign,
};

fn main () {
    let (public_key, private_key) = keypair();
    // 在此处打印变量...
}
  • Cargo.toml配置
[package]
name = "project"
version = "0.1.0"
edition = "2021"

[dependencies]
pqcrypto-dilithium = "0.4.5"
  • 触发的报错信息
error[E0277]: `pqcrypto_dilithium::dilithium5::PublicKey` doesn't implement `Debug`
  --> src\main.rs:14:23
   |
14 |     println!("{:#?}", public_key)
   |                       ^^^^^^^^^^ `pqcrypto_dilithium::dilithium5::PublicKey` cannot be formatted using `{:?}` because it doesn't implement `Debug`
   |
   = help: the trait `Debug` is not implemented for `pqcrypto_dilithium::dilithium5::PublicKey`
   = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0277`.
报错原因

pqcrypto-dilithium封装的PublicKey、SecretKey新类型没有实现std::fmt::Debug trait,无法直接被调试格式占位符解析打印。这两个类型本质是固定长度字节数组的封装,都实现了AsRef<[u8]> trait,通过该特征可以取出底层的字节切片完成打印。

实现方案

方式1:直接打印原始字节

无需新增依赖,直接调用as_ref()拿到密钥对应的字节切片,即可用Debug格式打印:

fn main () {
    let (public_key, private_key) = keypair();

    // 打印原始字节内容
    println!("公钥字节: {:?}", public_key.as_ref());
    println!("私钥字节: {:?}", private_key.as_ref());

    // 可选校验:密钥长度与库提供的标准长度一致
    assert_eq!(public_key.as_ref().len(), public_key_bytes());
    assert_eq!(private_key.as_ref().len(), secret_key_bytes());
}

方式2:打印为十六进制字符串(密码学场景通用格式)

原始字节数组可读性差,密码学场景通常将密钥编码为十六进制字符串展示。首先在Cargo.toml的依赖项中新增hex编码库:

[dependencies]
pqcrypto-dilithium = "0.4.5"
hex = "0.4.3"

修改代码调用hex编码接口输出即可:

fn main () {
    let (public_key, private_key) = keypair();

    println!("公钥(十六进制): {}", hex::encode(public_key.as_ref()));
    println!("私钥(十六进制): {}", hex::encode(private_key.as_ref()));
}

修改完成后执行cargo run即可正常输出公私钥内容。

内容的提问来源于stack exchange,提问作者user19316228

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 07:45:35