rsa [公钥加密算法]

    http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.RSA.RSA-class.html

    pip install M2Crypto

    from M2Crypto import RSA,BIO                         # help(RSA)
    rsa = RSA.gen_key(2048, 'sha1')                      # 设置生成密钥为2048位,1024较不安全,默认算法sha1
    rsa.save_key('rsa.priv.pem', None )                  # 生成私钥pem文件
    rsa.save_pub_key('rsa.pub.pem')                      # 生成公钥pem文件
    rsa.save_key_bio()                                   # 私钥保存到pem格式的M2Crypto.BIO.BIO对象
    rsa.save_pub_key_bio()                               # 公钥保存到pem格式的M2Crypto.BIO.BIO对象
    priv=RSA.load_key('rsa.priv.pem')                    # 加载私钥文件
    pub=RSA.load_pub_key('rsa.pub.pem')                  # 加载公钥文件
    rsa.check_key()                                      # 检查key是否初始化
    pub_key.public_encrypt('data',RSA.pkcs1_padding)     # 公钥加密
    priv_key.private_decrypt('密文',RSA.pkcs1_padding)   # 私钥解密

    from M2Crypto import RSA,BIO

    rsa = RSA.gen_key(2048, 3, lambda *agr:None)
    pub_bio = BIO.MemoryBuffer()
    priv_bio = BIO.MemoryBuffer()

    rsa.save_pub_key_bio(pub_bio)
    rsa.save_key_bio(priv_bio, None)

    # print pub_bio.read_all()
    pub_key = RSA.load_pub_key_bio(pub_bio)
    priv_key = RSA.load_key_bio(priv_bio)

    message = 'i am luchanghong'

    encrypted = pub_key.public_encrypt(message, RSA.pkcs1_padding)        # 加密
    decrypted = priv_key.private_decrypt(encrypted, RSA.pkcs1_padding)    # 解密

    print decrypted
文档更新时间: 2018-11-21 17:32   作者:RuM