orangleliu 笔记本

lzz的编程之旅,技术,思考,分享,happy

[python]使用pycrypto 或者 cryptography 生成rsa 公钥私钥对

简单的例子分别使用了 pycrypto 和 cryptography 库,可以根据自己的需求调整 key的长度或者是格式,默认是 PEM的。

  • python 2.7.x
  • cryptography (2.2.2)
  • pycrypto (2.6.1)

代码

# coding:utf-8
from Crypto.PublicKey import RSA
from Crypto import Random

def generate_rsa_keys():
    """crpyto install need gcc and python-devel
    pip install pycrypto
    """
    random_generator = Random.new().read
    key = RSA.generate(1024, random_generator)
    pub_key = key.publickey()

    public_key = pub_key.exportKey("PEM")
    private_key = key.exportKey("PEM")
    return public_key, private_key


from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import NoEncryption,\
    Encoding, PrivateFormat, PublicFormat

def generate_keys():
    """
    pip install cryptography
    """
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=1024,
        backend=default_backend(),
    )

    serialized_private_key = private_key.private_bytes(
        Encoding.PEM,
        PrivateFormat.PKCS8,
        NoEncryption()
    )

    public_key = private_key.public_key()

    serialized_public_key = public_key.public_bytes(
        Encoding.PEM,
        PublicFormat.SubjectPublicKeyInfo,
    )

    return serialized_public_key, serialized_private_key

if __name__ == "__main__":
    print "------------pycrypto------------"
    pub_key, pri_key = generate_rsa_keys()
    print pub_key
    print pri_key

    print "\n------------cryptography------------"
    pub_key, pri_key = generate_keys() 
    print pub_key
    print pri_key

因为我们的jwt用的是rsa,所以就有了这么个需求。

阅读更多
版权声明:本文为orangleliu (http://blog.csdn.net/orangleliu/)原创文章,自由传播,文章转载请声明, 多谢。 https://blog.csdn.net/lzz957748332/article/details/80274662
文章标签: rsa python key 公钥
个人分类: 如今Python 安全
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭