代码之家  ›  专栏  ›  技术社区  ›  Sandipan

用RSA算法加密python3中的图像文件

  •  1
  • Sandipan  · 技术社区  · 6 年前

    我正在用RSA算法加密python3中的图像,但在运行代码时遇到了一些错误;

     File "encrypt_blob.py", line 59, in <module>
     encrypted_blob = encrypt_blob(unencrypted_blob, public_key)
     File "encrypt_blob.py", line 37, in encrypt_blob
     chunk += " " * (chunk_size - len(chunk))
     TypeError: can't concat str to bytes
    

    我已经在前面生成了密钥,并在这个脚本中使用这些密钥来加密图像文件。但是我得到了这个错误。正如我在博客上发现的,我认为代码是用python2编写的,但我使用的是python3,我不知道如何解决这个问题

    代码是:

    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_OAEP
    import zlib
    import base64
    
    def encrypt_blob(blob, public_key):
      #Import the Public Key and use for encryption using PKCS1_OAEP
      rsa_key = RSA.importKey(public_key)
      rsa_key = PKCS1_OAEP.new(rsa_key)
    
      #compress the data first
      blob = zlib.compress(blob)
    
      #In determining the chunk size, determine the private key length used in bytes
    #and subtract 42 bytes (when using PKCS1_OAEP). The data will be in encrypted
    #in chunks
    chunk_size = 470
    print(type(chunk_size))
    offset = 0
    end_loop = False
    encrypted =  ""
    print(type(encrypted))
    
    while not end_loop:
        #The chunk
        chunk = (blob[offset:offset + chunk_size])
    
        #If the data chunk is less then the chunk size, then we need to add
        #padding with " ". This indicates the we reached the end of the file
        #so we end loop here
        if len(chunk) % chunk_size != 0:
            end_loop = True
            chunk += " " * (chunk_size - len(chunk))
    
        #Append the encrypted chunk to the overall encrypted file
        encrypted += (rsa_key.encrypt(chunk))
    
        #Increase the offset by chunk size
        offset += chunk_size
    
    #Base 64 encode the encrypted file
    return base64.b64encode(encrypted)
    
    #Use the public key for encryption
    fd = open("public_key.pem", "rb")
    public_key = fd.read()
    fd.close()
    
    #Our candidate file to be encrypted
    fd = open("img.jpg", "rb")
    unencrypted_blob = fd.read()
    fd.close()
    
    encrypted_blob = encrypt_blob(unencrypted_blob, public_key)
    
    #Write the encrypted contents to a file
    fd = open("encrypted_img.jpg", "wb")
    fd.write(encrypted_blob)
    fd.close()
    

    期待建议。非常感谢。

    0 回复  |  直到 6 年前