轉發:已知rsa的模數和指數 生成pem公鑰文件

1.安裝cryptography
sudo pip3 install cryptography

2.代碼

#coding:utf8
# pupulate-pub-key-v3.py
#
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
pub_key="EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D245A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD3993CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443"# ===>新浪微博的公鑰模數,抓包而來

# 從little-endian格式的數據緩衝data中解析公鑰模數並構建公鑰
def populate_public_key(data):
    # convert bytes to integer with int.from_bytes
    # 指定從little格式將bytes轉換爲int,一句話就獲得了公鑰模數,省了多少事
    n = int(data,16)
    e = 65537

    # 使用(e, n)初始化RSAPublicNumbers,並經過public_key方法獲得公鑰
    # construct key with parameter (e, n)
    key = rsa.RSAPublicNumbers(e, n).public_key(default_backend())

    return key


# 將公鑰以PEM格式保存到文件中
def save_pub_key(pub_key, pem_name):
    # 將公鑰編碼爲PEM格式的數據
    pem = pub_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )

    # print(pem)

    # 將PEM個數的數據寫入文本文件中
    with open(pem_name, 'w+') as f:
        f.writelines(pem.decode())

    return

if __name__ == '__main__':
        pub_key = populate_public_key(data=pub_key)
        pem_file = r'pub_key.pem'
        save_pub_key(pub_key, pem_file)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42

結果:
新浪微博的公鑰:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDrKjhWhmGIf6GAvdtcq9XyHHv9
WcCQyy0kWoesJTBiiCcpKT5VBjUFCOf5qju3f0MzIxSQ+RX21jxV/i8IpJs1P0RK
05k8rMAtt4Sru45CqbG7//s4vhjXjoeg5Bubj3OpKO4MzuH2c5iEuXd+T+noihu+
SVknrEp5mzGB1kQkQwIDAQAB
-----END PUBLIC KEY-----

來源:CSDN
原文:https://blog.csdn.net/jmh1996/article/details/78815005 編碼

相關文章
相關標籤/搜索