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

如何用cryptography模块提取SECT163R2密钥的原始字节?

生成SECT163R2曲线的原始公私钥字节(无格式元数据)

要获取SECT163R2(B-163)曲线的原始私钥(24字节)和公钥(48字节),无法直接通过private_bytes()/public_bytes()的Raw格式参数实现,需从密钥对象中提取原始数值再转换为字节:

私钥提取(24字节原始字节)

EC私钥的核心是一个163位整数,通过private_numbers()方法获取该数值后,转换为固定24字节的大端字节(补前导零填充):

from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.backends import default_backend

# 生成SECT163R2密钥对
private_key = ec.generate_private_key(ec.SECT163R2(), default_backend())

# 提取私钥数值并转为24字节原始字节
private_num = private_key.private_numbers().private_value
raw_private_key = private_num.to_bytes(24, byteorder='big')

print(len(raw_private_key))  # 输出24

公钥提取(48字节原始字节)

公钥由曲线上点的x、y坐标组成,每个坐标为163位整数,分别转为24字节后拼接即可:

# 提取公钥坐标数值
public_numbers = private_key.public_key().public_numbers()
x = public_numbers.x
y = public_numbers.y

# 转换为24字节并拼接
raw_public_key = x.to_bytes(24, byteorder='big') + y.to_bytes(24, byteorder='big')

print(len(raw_public_key))  # 输出48

关键说明

  • private_bytes()的Raw格式仅对部分对称密钥或特定非对称密钥类型支持,EC密钥的Raw格式未被cryptography直接实现,因此需要手动提取数值转换。
  • 固定24字节的原因是163位需向上取整到最近的字节数(24字节=192位),补前导零保证字节长度一致,符合原始密钥的字节要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 18:04:55