DEV Community

Cover image for PGP - Encrypt/Decrypt file with Ruby on Rails (Part 3)
Humberto Arroyo
Humberto Arroyo

Posted on

PGP - Encrypt/Decrypt file with Ruby on Rails (Part 3)

In the previous two posts we have seen:

  1. Introduction Encryption and Decryption
  2. Create a Public/Private Key Pair

In this tutorial we are going to explain how to encrypt and decrypt in Ruby on Rails with the GPGME gem.

Summary

  • GPGME provides an encryption, decryption, signing, signature verification and key management
  • Encrypt data with GPGME gem
  • Decrypt data with GPGME gem

Ruby gem GPGME (GnuPG Made Easy) is a library designed to make access to GnuPG easier for applications. GPGME provides a High-Level Crypto API for encryption, decryption, signing, signature verification and key management.

Encrypt data with GPGME gem

  1. Must be have an imported recipient's public key.
crypto = GPGME::Crypto.new
GPGME::Key.import(File.open('recipient_public_key.pgp'))
Enter fullscreen mode Exit fullscreen mode
  1. Read file or data to encrypt
plaintext = GPGME::Data.new(File.open('file.csv'))

#Our file contains following data:
#last_name, name, mobile_phone\nSmith,Chris,3336985726
Enter fullscreen mode Exit fullscreen mode
  1. Encrypt data with following options
    • Recipients: For which recipient do you want to encrypt this file.
    • Sign: Must be true, performs a combined sign and encrypt operation.
    • Signers: Sender of encrypt file.
options = { sign: true, signers: 'sender@foo.com', recipients: 'recipient@foo.com' }
data = crypto.encrypt plaintext, options
Enter fullscreen mode Exit fullscreen mode
  1. Create and save encrypted file in gpg extension:
f = File.open('encrypted_file.gpg', 'wb')
bytes_written = f.write(data)
f.close
Enter fullscreen mode Exit fullscreen mode

Now we have a file with this name encrypted_file.gpg and we can send to the recipient into S3, SFTP, etc.

Decrypt data with GPGME gem

  1. Must be have an imported recipient's private key.
crypto = GPGME::Crypto.new
GPGME::Key.import(File.open('recipient_private_key.pgp'))
Enter fullscreen mode Exit fullscreen mode
  1. Read and create Data instance of encrypted file
cipthertext = GPGME::Data.new(File.open('encrypted_file.gpg'))
Enter fullscreen mode Exit fullscreen mode
  1. Decrypt data and print
data = crypto.decrypt cipthertext, {}
puts data
#last_name, name, mobile_phone\nSmith,Chris,3336985726
Enter fullscreen mode Exit fullscreen mode

Top comments (0)