How to encrypt a string using RSA public key only? I have been given the following public RSA key:

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl2uzoWA2iEGfeqDYO4XA0mQV8odb6qgdLT0T/k1PsbviMMt+SlAnZpwDkPlFySxNejOv8zAUHwDTWV7NGpYA0y+TrrBLkGGl9uUrzOjQLryJmFWsXxBGFd4emYXYBzROaH+r7pzhK7mIWLw1e2Cj5RL9Ac6wKA56axqCr2UZRNDBcS5A+nKTQTWy5eTrq6EQSBA6Hr81UWtYwlNSo1YbZ9JSNdD75Go7Du/zv1iPI+wWr7tMp0AJVBmieeB0kryXl+8zhli80wa72hDtyTkmfkBJAid5Il1biTrOXtMDaqXdfi9s4xzFp/ilP17KnA+VeAH2eLcqaC6LkEp/A1LApwIDAQAB


Now, I need to encrypt a string with this public RSA key.

What I have tried so far:

Put the key in a file, and name it public. Ran the following command to get the .pem version of the key:

openssl rsa -in public  -pubout &gt; file.pem


But doing so says the following:


  unable to load Private Key


So how can I successfully encrypt a string using a public RSA key only?
This is not a question about cryptography itself, but rather use of a program or library related to crypto (OpenSSL). It would fit better on security.SX or superuser, or stackoverflow if you want to do it in your own code.

Your key is base64-of-SPKI which is nearly OpenSSL's PEM format; just break it into lines of length 76 (can omit this step if using OpenSSL 1.1.0 given your key is not too long), add a line -----BEGIN PUBLIC KEY----- before and a line -----END PUBLIC KEY----- after. (Note 'line' must have a terminating LF or CRLF depending on OS.) Alternatively just convert it from base64 to binary and that's OpenSSL's DER format.

Much as Squeamish said you can then use this key to encrypt small data (such as a symmetric key) from commandline using 

 openssl rsautl -encrypt -inkey file -pubin [-keyform der]


or (in 1.0.0 up) 

 openssl pkeyutl -encrypt -inkey file -pubin [-keyform der]


as described in their respective man pages which should be present on your system or on the web; or from code in ways depending on the API(s) available or preferred which you didn't identify. 

Both of these by default use the traditional padding of RSAES-PKCS1-v1_5 (commonly abbreviated pkcs) and optionally can do OAEP from PKCS1 v2 (see the man pages) or raw/none (which is usually a very bad idea). You need the recipient to tell you what padding (or possibly choice of paddings) they accept; if you have a choice OAEP is better (and the reasons why are ontopic here but already answered). If they require something other than the two PKCS1 schemes you'll almost certainly need to code it yourself.