gpt4 book ai didi

python - M2Crypto - 从非标准文件导入 key ?

转载 作者:行者123 更新时间:2023-12-01 06:01:12 25 4
gpt4 key购买 nike

我有一个包含公共(public)指数和模数的文件。它们不是 pem 或 xml 或 der 格式,它们只是在其偏移处写入的值。

我如何使用 M2Crypto 从中创建公钥?我也有相同格式的私钥。我已经设法使用某人在 Stackoverflow 上发布的代码来使用 php 生成 PEM 文件,但这似乎是一种极其荒谬的方法。

这也不是一次性的事情,我需要能够从这种格式的文件中读取公共(public)指数和模数来检查签名。

最佳答案

非常感谢拉尔斯:http://blog.oddbit.com/2011/05/09/signing-data-with-ssh-agent/

e 是公共(public)指数的 Python longn 是公共(public)模数的 Python long

他发布的代码是:

import M2Crypto
key = M2Crypto.RSA.new_pub_key((
M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(hex(e)[2:])),
M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(hex(n)[2:])),
))

hex 将生成 0xA45E 类型的十六进制字符串,因此他只是获取 0x 之后的所有内容。

我正在从文件中读取 key ,所以我没有那么长的 key 。我最终使用:

import M2Crypto
from binascii import hexlify
e = f.read(4)
n = f.read(0x80)
key = M2Crypto.RSA.new_pub_key((
M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(hexlify(e))),
M2Crypto.m2.bn_to_mpi(M2Crypto.m2.hex_to_bn(hexlify(n))),
))

效果非常好!

根据文档,new_pub_key 的接受格式必须是

OpenSSL's MPINT format - 4-byte big-endian bit-count followed by the appropriate number of bits

我不确定这是否是一个拼写错误,但对于我的指数(十六进制)00010001 最终是000003010001。我认为这是字节数,而不是位数。他们还剥离了第一个 0x00。我不知道这是否是标准的,还是因为它是一个空字节。

编辑:我想我对这种格式有了更好的理解。

如果第一个字节为负,则在开头添加一个零字节。如果有任何前导(在开头)零字节,它们将被删除,除非第一个字节变为负数,在这种情况下,只留下一个零字节。

一些例子:

Unformatted:\x23\x24\x25\x26Formatted:\x00\x00\x00\x04\x23\x24\x25\x26Explanation:String left as is and count of bytes packed inUnformatted:\x00\x23\x55\x35Formatted:\x00\x00\x00\x03\x23\x55\x35Explanation:leading zero byte removed, byte count now 3Unformatted:\x80\x43\x55\x27Formatted:\x00\x00\x00\x05\x00\x80\x43\x55\x27Explanation:leading zero byte added because \x80 is negativeUnformatted:\x00\xff\x43\x23Formatted:\x00\x00\x00\x04\x00\xff\x43\x23Explanation:Leading zero byte left because \xff is negativeUnformatted:\x23\x53\66\x00Formatted:\x00\x00\x00\x04\x23\x53\66\x00Explanation:Trailing zero byte left in string

关于python - M2Crypto - 从非标准文件导入 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10367072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com