On Fri, Aug 03, 2007 at 01:46:56PM +0100, Brian Candler wrote:
>  I know how to use public key to encrypt data if I create public/private
> > key pair by myself through OpenSSL::PKey::RSA. However, if I only know
> > other guy's public key, how could I encrypt data with his/her public
> > key? Is there any method in the module OpenSSL::PKey::RSA to support it?
> 
> What's your current code? You should just be able to read in the public key
> (e.g. from a PEM file), and use that to encrypt.

Try this:

$ openssl genrsa -out key.priv -des3 -passout pass:abcd 2048
Generating RSA private key, 2048 bit long modulus
.....................................................................+++
...................+++
unable to write 'random state'
e is 65537 (0x10001)

$ openssl rsa -in key.priv -passin pass:abcd -out key.pub -pubout
writing RSA key

$ cat enc.rb
require 'openssl'
key = OpenSSL::PKey::RSA.new(File.read('key.pub'))
raise "Not public key" unless key.public?
$stdout.write key.public_encrypt($stdin.read)

$ echo "Hello, world" | ruby enc.rb >data.bin

$ ls -l data.bin
-rw-r--r-- 1 candlerb candlerb 256 2007-08-03 14:00 data.bin

$ openssl rsautl -decrypt -in data.bin -inkey key.priv -passin pass:abcd
Hello, world