In the previous two posts we have seen:
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
- Must be have an imported recipient's public key.
crypto = GPGME::Crypto.new
GPGME::Key.import(File.open('recipient_public_key.pgp'))
- 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
- 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
- Create and save encrypted file in gpg extension:
f = File.open('encrypted_file.gpg', 'wb')
bytes_written = f.write(data)
f.close
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
- Must be have an imported recipient's private key.
crypto = GPGME::Crypto.new
GPGME::Key.import(File.open('recipient_private_key.pgp'))
- Read and create Data instance of encrypted file
cipthertext = GPGME::Data.new(File.open('encrypted_file.gpg'))
- Decrypt data and print
data = crypto.decrypt cipthertext, {}
puts data
#last_name, name, mobile_phone\nSmith,Chris,3336985726
Top comments (0)