python rsa加密


rsa 加密,是一个非对称加密,python中有多个 库可以使用,在此使用rsa库存

pip install rsa

假如使用4096 bit的密钥,

加密时每次可加密的字符长度是4096/8-11=501bytes,加上自身带的11bytes数据,

加密后的密文长度是512bytes

密钥长度越长,解密用时越长,要看CPU的性能

2048位的密钥大约是加密用时的22倍或更多,

4096位的密钥大约是加密用时的65倍或更多,

生成密钥对:

  pubkey, privkey = rsa.newkeys(4096)

  #把公钥写入到文件

  pub = pubkey.save_pkcs1()

  with open('pub.pem','wb') as wfs:

    wfs.write(pub)

  #把私钥写入到文件

  priv = privkey.save_pkcs1()

  with open('priv.pem','wb') as fs:

    fs.write(priv)

加密文件:

  加密和解密,都只能使用bytes类型,不能使用字符串等其它类型

  #读取公钥

  with open('pub.pem','rb') as rfs:

    pubdata = rfs.read()

  pubkey = rsa.PublicKey,load_pkcs1(pubdata)

  #循环读取并加密文件

  start = 0

  with open('abc.txt','rb') as rfs:

    with open('abc.encrypt.txt','wb') as wfs:

      while start < os.path.getsize('abc.txt):

        data = rfs.read(501)

        #加密

        encrypt_data = rsa.encrypt(data,pubkey) #data:要加密的数据;pubkey:公钥

        wfs.write(encrypt_data)

        start += 501

解密:

  #读取私钥

  with open('priv.pem','rb') as fs:

    privdata = fs.read()

  privkey = rsa.PrivateKey.load_pkcs1(privdata)

  #循环读取并解密文件

  start = 0

  with open('abc.encrypt.txt','rb') as rfs:

    with open('abc.decrypt.txt','wb') as wfs:

      while start < os.path.getsize('abc.encrypt.txt):

        data = rfs.read(512) #加密后的密文长度增加了11bytes

        #加密

        decrypt_data = rsa.encrypt(data,pubkey) #data:要解密的数据;pubkey:私钥

        wfs.write(decrypt_data)

        start += 501

 

 字符串加解密:

  先获取字符串长度,比较与密钥长度对应的固定长度,判断是否需要截取

  a = 'abcdefg'

  加密:

  a = a.encode('utf-8')

  length = len(a)

  encrypt_data = b''

  if length <= encrypt_length:

    encrypt_data = rsa.encrypt(a,pubkey)

  else:

    start = 0

    while start < length:

      end = start + encrypt_length

      data = a[start:end]

      encrypt_data += rsa.encrypt(data,pubkey)

      start =+ encrypt_length

  return encrypt_data

 

  解密同理:

 

  length = len(a)

 

  decrypt_data = ''

 

  if length <= decrypt_length: # decrypt_length = encrypt_length +11

 

    decrypt_data = rsa.decrypt(a,pubkey)

 

  else:

 

    start = 0

 

    while start < length:

 

      end = start + decrypt_length

 

      data = a[start:end]

 

      decrypt_data += rsa.decrypt(data,pubkey)

 

      start =+ decrypt_length

 

  return decrypt_data

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM