我有一个 C 代码,可以生成 DH 密钥对作为原始字节。然后我使用 TCP/IP 套接字将公钥发送到 python 服务器。我的 DH 公钥如下所示:
derive_key_dh_public_value = {
0x46, 0x3b, 0x61, 0x4, 0x74, 0x26, 0x81, 0x71, 0xee, 0xba, 0x8b, 0xe, 0xe, 0x34, 0xd, 0x39,
0x8f, 0xb3, 0xa1, 0x44, 0x63, 0x19, 0x8f, 0x66, 0x6b, 0x80, 0x48, 0x55, 0x8b, 0x96, 0x65, 0x3c,
0x4a, 0x69, 0x48, 0xbd, 0x65, 0xa5, 0xa5, 0x5c, 0x9, 0x12, 0x30, 0x86, 0xcd, 0x68, 0x11, 0x24,
0x6, 0x68, 0xb1, 0x36, 0x47, 0x1a, 0x19, 0xb2, 0x5c, 0xb, 0x92, 0x29, 0x2d, 0xa6, 0x1f, 0x22,
0xc0, 0x36, 0x4e, 0xcd, 0x1, 0x68, 0xcb, 0xd9, 0xd4, 0x1b, 0xae, 0xf9, 0x4b, 0x70, 0x61, 0x7c,
0x7c, 0xb8, 0x42, 0xf0, 0xaa, 0xd9, 0x5b, 0xd2, 0x37, 0x84, 0x70, 0x1d, 0x18, 0x4a, 0xd4, 0xf3,
0xac, 0x95, 0x6e, 0xd7, 0xea, 0x70, 0x66, 0xd6, 0x20, 0x27, 0x27, 0xbe, 0x40, 0x62, 0x96, 0xdb,
0x6e, 0xa7, 0xc4, 0x7, 0xaa, 0x75, 0x86, 0xb5, 0xc9, 0x44, 0xa1, 0xa8, 0x9f, 0xe0, 0xc6, 0x4d,
0x71, 0x15, 0x80, 0x83, 0x5, 0x5, 0x15, 0xfc, 0xba, 0x56, 0x52, 0xd4, 0x25, 0xcd, 0x75, 0x88,
0xcc, 0xce, 0x9d, 0x5e, 0xdf, 0xef, 0xc1, 0x58, 0xfc, 0xc6, 0x91, 0xc3, 0xcd, 0x72, 0xfe, 0xa5,
0x36, 0xdd, 0x68, 0x90, 0x66, 0xea, 0x38, 0x2a, 0x1a, 0x6, 0xb, 0x38, 0xb5, 0xaf, 0x58, 0x7e,
0x39, 0x9c, 0x6c, 0xab, 0x1f, 0xd5, 0x0, 0xb4, 0x69, 0x63, 0xa4, 0x8b, 0xa3, 0xf1, 0x1e, 0xef,
0x97, 0x28, 0x32, 0x7a, 0xd0, 0x1c, 0xa3, 0x5d, 0xf, 0x93, 0xa, 0x6b, 0x90, 0x78, 0x6b, 0xf0,
0x1d, 0xed, 0xeb, 0x85, 0x46, 0x54, 0x76, 0x32, 0x15, 0xbe, 0x96, 0x8e, 0xe2, 0x70, 0x60, 0x16,
0xae, 0xf7, 0xe5, 0x29, 0xc3, 0x70, 0xf0, 0x6b, 0x4c, 0xb7, 0xf0, 0x7c, 0x7a, 0xc8, 0xee, 0x38,
0x7f, 0x5d, 0xf4, 0x28, 0x64, 0x94, 0x59, 0x43, 0xcd, 0x57, 0x87, 0x33, 0x7b, 0xae, 0xee, 0xfe
};
它是一个 2048 位 Diffie-Hellman 公钥。我以这种格式接收此密钥的另一部分是一个 Python 程序,它已经生成了自己的 DH 密钥对。我的问题是如何加载这个原始字节作为 DH 公钥来导出共享秘密?任何图书馆都可以。
我尝试了这个,但给了我错误:
`
dh_public_key_base64 = base64.b64encode(received_public_key).decode('utf-8')
print(dh_public_key_base64)
received_public_key = serialization.load_der_public_key(dh_public_key_base64, backend=default_backend())
尝试使用以下代码:
from cryptography.hazmat.primitives.asymmetric import dh
# Your raw public key bytes
raw_public_key = b'...' # replace with 256-byte raw public key
# Convert raw public key to an integer
public_key_int = int.from_bytes(raw_public_key, byteorder='big')
# Standard DH parameters for 2048-bit MODP Group from RFC 3526 (Group 14)
parameters = dh.generate_parameters(generator=2, key_size=2048)
public_numbers = dh.DHPublicNumbers(public_key_int, parameters.parameter_numbers())
public_key = public_numbers.public_key()
当然,这假定了一组特定的域参数,但这些是最常见的。