[英]How to add a custom RSA key pair to a .pem file
I created a custom RSA key pair just for test purposes in python.我在 python 中创建了一个自定义 RSA 密钥对,仅用于测试目的。 I want to add the private key and public key to a.pem file but I didnt find anything in my research.
我想将私钥和公钥添加到 a.pem 文件中,但我在研究中没有找到任何东西。 All i found is people generating a RSA key pair from a library.
我发现的只是人们从库中生成 RSA 密钥对。 I have the e, d and n variables for the public key[e, n] and private key[d, n].
我有公钥[e,n]和私钥[d,n]的e,d和n变量。
Most major crypto libraries support this, eg PyCryptodome (via construct()
and exportKey()
) or Cryptography (as described in the Numbers and Key Serialization sections), eg大多数主要的加密库都支持这一点,例如 PyCryptodome(通过
construct()
和exportKey()
)或密码学(如数字和密钥序列化部分所述),例如
PyCryptodome: PyCryptodome:
from Crypto.PublicKey import RSA
n = int("b83b...529b", 16);
d = int("4eea...a721", 16);
e = int("010001", 16);
privateKey = RSA.construct((n, e, d))
privateKeyPem = privateKey.exportKey(pkcs=8) # export in PKCS#8 format
publicKey = RSA.construct((n, e))
publicKeyPem = publicKey.exportKey() # export in X.509/SPKI format
print(privateKeyPem.decode('utf8'))
print(publicKeyPem.decode('utf8'))
or Cryptography:或密码学:
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
n = int("b83b...529b", 16);
d = int("4eea...a721", 16);
e = int("010001", 16);
(q, p) = rsa.rsa_recover_prime_factors(n, e, d)
dmq1 = rsa.rsa_crt_dmq1(d, q)
dmp1 = rsa.rsa_crt_dmp1(d, p)
iqmp = rsa.rsa_crt_iqmp(p, q)
publicNumbers = rsa.RSAPublicNumbers(e, n)
privateNumbers = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, publicNumbers)
privateKey = privateNumbers.private_key();
publicKey = publicNumbers.public_key();
privateKeyPem = privateKey.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
publicKeyPem = publicKey.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
print(privateKeyPem.decode('utf8'))
print(publicKeyPem.decode('utf8'))
Note that the raw key is symmetric in p and q, so swapping p and q changes the PEM or DER encoded key, but not the raw key (n, e, d).请注意,原始密钥在 p 和 q 中是对称的,因此交换 p 和 q 会更改 PEM 或 DER 编码的密钥,但不会更改原始密钥 (n, e, d)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.