title: How to use decrypt with RSA private key and SHA256 on python
body: <p>I am learning for school to encrypt and decrypt a file using public and private keys en encoding.</p>
  
  <p>I used this code to encode the message. (which generates public key ≠ not private key error)</p>
  
  <pre class="lang-py prettyprint-override"><code>from Crypto.Signature import pkcs1_15
  from Crypto.Hash import SHA256
  from Crypto.PublicKey import RSA
  
  
  
  def signing():
      #open file = message als binary
      message = open('C:/Users/Gebruiker/Desktop/message.txt', "rb").read()
      #open public key -&gt; key     
      key = RSA.import_key(open('C:/Users/Gebruiker/Desktop/public.pem').read())
      #message becomes a hash
      h = SHA256.new(message)  
      #f = open file as write binary
      f = open('C:/Users/Gebruiker/Desktop/message.signature', 'wb')
      # sign hash message with private key  
      signature = pkcs1_15.new(key).sign(h) 
      #write signed hash to file 
      f.write(signature)
      f.close()
  </code></pre>
  
  <p>But now i am trying to decode this message and I found all these people that do it in different ways and work with different type of encoding and encrypting. And I cant find a clear answer.</p>
  
  <p>what i have right now is this</p>
  
  <p>First i have to read the message so</p>
  
  <pre class="lang-py prettyprint-override"><code>def decrypt():
      f = open('C:/Users/Gebruiker/Desktop/message.signature', 'rb').read()
  </code></pre>
  
  <p>then i open up my private key</p>
  
  <pre class="lang-py prettyprint-override"><code>    key = RSA.import_key(open('C:/Users/Gebruiker/Desktop/private.pem').read())
  </code></pre>
  
  <p>Because I write and read in binary i have to turn it back into a hash</p>
  
  <pre class="lang-py prettyprint-override"><code>    h = SHA256.new(f)
  </code></pre>
  
  <p>And then i have to decrypt the hash using my private key.???</p>
  
  <p>Instead i see a lot of people using something like this.</p>
  
  <pre class="lang-py prettyprint-override"><code>    h = pkcs1_15.new(key).sign(h)  # sign hash message with private key
  </code></pre>
  
  <p>which i don't get. You are supposed to decode it right? not sign it again. this part makes no sense to me.    </p>
  
  <p>Now I have 2 problems.</p>
  
  <ol>
  <li>I get an encoding error saying my public key is not a private key. Which is kinda the point of public keying right. so only private key can decrypt? Why am i getting an error?</li>
  <li>I don't know how to proceed with the decrypting of my message</li>
  </ol>
  
  <p>Can anybody help me with this? </p>
  
  <p>Thanks a lot!</p>