title: Encrypt JSON with SHA256 hash, got 512 characters back instead of 64
body: <p>Based on <a href="https://cloud.google.com/kms/docs/encrypt-decrypt-rsa#kms-howto-encrypt-rsa-python" rel="nofollow noreferrer">Google document</a> and <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/?highlight=decryption#decryption" rel="nofollow noreferrer">cryptography.io</a>. </p>
  
  <p>I attempt to encrypt a queried result which is in a JSON format which look like this {"data":"abc"}. As I know, when encrypting with SHA256, the encrypted data will be in a form of 64 characters but after I looked on and tried it with the code in the link and some modification, I got a result of 512 characters instead of 64 characters.</p>
  
  <p>This is my code:</p>
  
  <pre><code>def encrypt_rsa(_rsa_pub, plaintext):
      key_txt = _rsa_pub.encode()
      public_key = serialization.load_pem_public_key(key_txt, default_backend())
  
      # encrypt plaintext
      pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                         algorithm=hashes.SHA256(),
                         label=None)
      return public_key.encrypt(plaintext, pad)
  
  pk = ....#public key
  message = .... #query result (JSON)
  x = json.dumps(message).encode('utf-8')
  enc = encrypt_rsa(pk , x)
  enc = base64.b64encode(enc).decode()
  dec = decrypt_rsa(enc)
  </code></pre>
  
  <p>There is no error but I got a long encrypted data with 512 characters which is really weird. I have tried decrypting it with the code from <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/?highlight=decryption#decryption" rel="nofollow noreferrer">cryptography.io</a> and got an error:</p>
  
  <pre><code>AttributeError: 'str' object has no attribute 'decrypt'
  </code></pre>
  
  <p>which I think this error might occured because of the wrong encrypted data that should be 64 characters but the input is 512 characters. So, based on my case, what did I forgot or what should be add to this code to make it become an encrypted data with 64 characters that can be decrypted?</p>
  
  <p>Edit: decrypt function</p>
  
  <pre><code>def decrypt_rsa(ciphertext):
      private_key = .....
      pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None)
      return private_key.decrypt(ciphertext, pad)
  </code></pre>
  
  <p>The error occured at <code>decrypt</code> at the line that return the result. I actually passed the encrypted data into this function. And I think it not because of the key since it should not provide error result like this </p>