Monday, 16 June 2008

Ruby and RSA Encryption

One of the greatest security schemes in e-commerce is RSA Encryption. It depends on one published key for encryption and secured private key for decryption. Private key can also be used in signing a content.

Ruby contains a standard library for SSL (Secure Socket Layer) that helps you finding all required schemes for implementing your secure communication channel over the Internet.

If you want to use RSA schema for encrypting/decrypting your content, follow the following steps:

  1. First, you need to generate the private key and store it in secure store, let us generate one with length 1024:

    @private_key = OpenSSL::PKey::RSA.new(1024)


  2. Now, you can use this key to generate the public key as following:

    @public_key = @private_key.public_key

    To get the string representation of this key:

    @public_key.to_pem


  3. After you publish your public key, your clients can encrypt content as following:

    @encrypted_msg = @public_key.public_encrypt("text to encrypt")


  4. Now, to decrypt the incoming encrypted content, use your secured private key:

    @decrypted_msg = @private_key.private_decrypt(@encrypted_msg)

    You can also use this pair to sign your content with your signature. That can be done by encrypting your content using your secret private key and your clients can check the content authority by decrypting this content using your published public key.

Note: Don't forget that private key, public key and also the encrypted content may contains unprintable characters. To store or print them, you need to encrypt them first using Base64 encoding.

This library also contains other security protocols, check the full documentation.

No comments: