【web_逆向10】非对称加密之RSA

发布时间 2023-08-20 17:14:07作者: Tony_xiao

非对称加密

  • 非对称加密. 加密和解密的秘钥不是同一个秘钥. 这里需要两把钥匙. 一个公钥, 一个私钥. 公钥发送给客户端. 发送端用公钥对数据进行加密. 再发送给接收端, 接收端使用私钥来对数据解密. 由于私钥只存放在接受端这边. 所以即使数据被截获了. 也是无法进行解密的.
  • 常见的非对称加密算法: RSA, DSA等等, 下面我们就介绍一个. RSA加密, 也是最常见的一种加密方案

1、创建公钥跟私钥

  • 注意点:公钥、私钥一定要同时生成
from Crypto.PublicKey import RSA  # 处理秘钥对的.

# 生成密钥对
# 65537 是rsa的一个标志.
# 10001 十六进制的数字 => 65537
key = RSA.generate(2048)  # 默认的这个key是私钥
# # print(key.exportKey())  # 默认的输出格式是PEM格式
with open("private.pem", mode="wb") as f:
    f.write(key.exportKey())


with open("public.pem", mode="wb") as f:
    f.write(key.public_key().export_key())

'''
generate参数说明
    """Create a new RSA key pair.

    The algorithm closely follows NIST `FIPS 186-4`_ in its
    sections B.3.1 and B.3.3. The modulus is the product of
    two non-strong probable primes.
    Each prime passes a suitable number of Miller-Rabin tests
    with random bases and a single Lucas test.

    Args:
      bits (integer):
        Key length, or size (in bits) of the RSA modulus.
        It must be at least 1024, but **2048 is recommended.**
        The FIPS standard only defines 1024, 2048 and 3072.
      randfunc (callable):
        Function that returns random bytes.
        The default is :func:`Crypto.Random.get_random_bytes`.
      e (integer):
        Public RSA exponent. It must be an odd positive integer.
        It is typically a small number with very few ones in its
        binary representation.
        The FIPS standard requires the public exponent to be
        at least 65537 (the default).

    Returns: an RSA key object (:class:`RsaKey`, with private key).

    .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
    """
'''

2、加密、解密

# 加密
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
import base64

ming = "请关注我的博客园".encode("utf-8")
# 需要公钥
# 从文件里读出来公钥
f = open("public.pem", mode="rb")
pub_key = RSA.import_key(f.read())

rsa = PKCS1_v1_5.new(key=pub_key)
result = rsa.encrypt(ming)
print(base64.b64encode(result).decode())

#解密
s = "ipFrgSNB+aPDO+wJb0GEdpy6rMRQxCsoiomb75z582KVjFL0l4iqd54BjAvEvmRHrGBVbWWMGvnwauLM/mdAgobxtvpLnY4EbdBCX4mUk1mlpAyjgDI76aNzRYA5Ii/2DrnygctUzgqomWYfNpa6d7GueYHbPfBmYl20sKs1pG41smHp/PP+DMUO3EwQKw4+wmoLQY21v3LB1ZkvjtcLGL3/LaTET8bDZiy67JcQjTc5r+aK/9gAW6YEFVB7L+kvUBU0cCpJ2evMLbUSmIzRXec4e48Dh1Ada0kqyyZxnq70o+b3Rd4bK2qQtuRxhDCRIcFY6mGu741hXtLTgV9VxA=="

mi_bs = base64.b64decode(s)
f = open("private.pem", mode="rb")
pri_key = RSA.import_key(f.read())

rsa = PKCS1_v1_5.new(key=pri_key)
ming_bs = rsa.decrypt(mi_bs, None)  # 第二个参数固定空的
print(ming_bs.decode("utf-8"))