Skip to content
This repository was archived by the owner on Feb 4, 2019. It is now read-only.

Asymmetric encryption

Itay Grudev edited this page Oct 2, 2016 · 5 revisions

Asymmetric encryption currently supports only the RSA algorithm.

Here is a list of the classes used for asymmetric encryption:

Encryption::Keypair - Used to generate public/private key pairs
Encryption::PublicKey - Handles public key encryption and decryption
Encryption::PrivateKey - Used for private key encryption and decryption

Example usage

Generating a keypair

keypair = Ecryption::Keypair.new
keypair.public_key # Returns an instance of Encryption::PublicKey
keypair.private_key # Returns an instance of Encryption::PrivateKey

Importing a key from string

Both Encryption::PublicKey and Encryption::PrivateKey are derived from Encryption::PKey which's constructor takes 2 arguments. The first one is the key as a string, and the second optional argument is a password for that key.

Here is how it works, assuming that key_data is a valid string representation of a public key:

public_key = Encryption::PublicKey.new(key_data)
public_key = Encryption::PublicKey.new(key_data, password) # Or with the optional password parameter

The same goes for Encryption::PrivateKey, since as was said above, both classes are derived from Encryption::PKey.

Encrypting messages

After we have an instance of either Encryption::PublicKey or Encryption::PrivateKey, we can use their encrypt or decrypt methods, by passing a single parameter - a string with the data to be encrypted.

Here is an example:

message = 'secret message'
public_key = Encryption::PublicKey.new( key_data )
enc_message = public_key.encrypt( message )

Decrypting messages

enc_message = 'encrypted message'
private_key = Encryption::PrivateKey.new( key_data )
private_key.decrypt( enc_message )