title: How to read RSA private key in Java from string created in Python?
body: <p>I have generated RSA public and private keys in my python app. I want to encrypt some string in python, send it to java app and decrypt it. How to do that? I've tried few methods described in here but I can't make it work:</p>
  
  <ul>
  <li><p><a href="https://stackoverflow.com/a/19387517/3626048">https://stackoverflow.com/a/19387517/3626048</a></p></li>
  <li><p><a href="https://stackoverflow.com/questions/7216969/getting-rsa-private-key-from-pem-base64-encoded-private-key-file">Getting RSA private key from PEM BASE64 Encoded private key file</a></p></li>
  <li><p><a href="https://stackoverflow.com/questions/22900570/key-from-string-in-java-rsa">Key from String in Java RSA</a></p></li>
  </ul>
  
  <p>This is my python code:</p>
  
  <pre><code>from Crypto.PublicKey import RSA
  
  new_key = RSA.generate(2048, e=65537)
  public_key = new_key.publickey().exportKey("PEM")
  private_key = new_key.exportKey("PEM")
  
  def encrypt(string, public_key):
    encrypted = public_key.encrypt(bytes(string, "latin1"), 255)
    date = encrypted[0]
    date = base64.b64encode(date)
    return date
  </code></pre>
  
  <p>Decryption in python works:</p>
  
  <pre><code>def decrypt(string, private_key):
    raw_cipher_data = base64.b64decode(string)
    string  = private_key.decrypt(raw_cipher_data)
    string = string.decode("latin1")
    return string
  </code></pre>
  
  <p>where I create private_key object like this:</p>
  
  <pre><code>private_key_str = "-----BEGIN RSA PRIVATE KEY-----\nMIIE+IB [.....] bcy/VVp63YA==\n-----END RSA PRIVATE KEY-----"
  private_key = RSA.importKey(private_key_str)
  </code></pre>