Private keys are for decryption, and public keys are for encryption.
So, if System 1 intends to send the encrypted text to System 2.
System 1 should receive the System 2 public key and encrypt the text using the System 2 public key. System 2 can receive the text and use its private key for decryption. When sending Side you can use such a code.
#!/usr/bin/env ruby require 'openssl' require 'base64' public_key_file = 'server2_public.pem'; string = 'Secret!'; public_key = OpenSSL::PKey::RSA.new(File.read(public_key_file)) encrypted_string = Base64.encode64(public_key.public_encrypt(string)) print encrypted_string, "\n"
Base 64 encoding is just an optional step, depending on whether you want to send binary data over the wire, etc.
On the receiving side
#!/usr/bin/env ruby require 'openssl' require 'base64' key = 'my_private_key.pem'; private_key = OpenSSL::PKey::RSA.new(File.read(key),'password') data = private_key.private_decrypt(Base64.decode64(encrypted_data_received)) puts data
If you have n number of systems, you should use conventions to search for public key names. For example, the name of the public key may be the same name as the name of the target device for the message, and it can be found from the key server. private keys should be present only in the corresponding system.
The goal of asymmetric encryption is double.
1) If you encrypt using the public key. Only a person with the corresponding secret key can decrypt. This ensures message security. 2) If you sign using a private key, the public key can be used for authentication. Everyone who has access to the public key can verify the authenticity of the message. This proves that only you could encrypt it. This is called a signature.
source share