Ruby Functions for Cryptography and Security

The recipient can decrypt the hash using the sender’s public key (which is available publicly) and compare it to their own calculation of the hash for the received data. If they match, this verifies that the data has not been tampered with during transmission and was indeed sent by the intended party.

Here’s an example implementation in Ruby:

# Import necessary libraries
require 'digest/sha256'
require 'openssl'

# Generate a private key (replace this with your own)
private_key = OpenSSL::PKey::RSA.new(File.read('my-private-key'))

# Define the data to be signed and hash it using SHA-256
data = "This is some sample data"
hash = Digest::SHA256.hexdigest(data)

# Encrypt the hash with the private key (using PKCS1 padding for RSA encryption)
encrypted_hash = private_key.private_encrypt(hash, OpenSSL::PKey::RSA::PKCS1_PADDING).pack('m04') # Corrected method call and added padding parameter for RSA encryption

# Send both the original data and encrypted hash to the recipient
puts "Original Data: #{data}"
puts "Encrypted Hash: #{encrypted_hash}" # Corrected variable name to match previous line

In this example, we first require the ‘digest/sha256’ and ‘openssl’ gems. We then generate a private key (which should be replaced with your own) using OpenSSL::PKey::RSA.new(File.read(‘my-private-key’)).

Next, we define some sample data to sign and hash it using Digest::SHA256.hexdigest(). We then encrypt the resulting hash using PKCS1 padding for RSA encryption (using OpenSSL::PKey::RSA.private_encrypt(hash, private_key).pack(‘m04’)). Finally, we print out both the original data and encrypted hash to be sent to the recipient.

On the receiving end, the recipient can decrypt the hash using PKCS1 padding for RSA decryption (using OpenSSL::PKey::RSA.public_decrypt(encrypted_hash, public_key).unpack(‘m04’)[0].hex) and compare it to their own calculation of the hash for the received data. If they match, this verifies that the data has not been tampered with during transmission and was indeed sent by the intended party.

The significance of digital signatures is that they provide a secure way to ensure data integrity and authenticity in various applications such as email encryption, software updates, and online transactions. By using cryptographic algorithms like RSA and SHA-256, we can create unique hash values for each piece of data being transmitted or stored, which cannot be reversed or duplicated by anyone without the private key used to generate them. This ensures that any tampering with the original data will result in a different hash value, making it easy to detect and prevent fraudulent activity.

SICORPS