This question already has an answer here:
I want to encrypt a string such that the end user can verify it was encrypted by me, but such that they can't encrypt it themselves.
For example, I have a private key 'private', a public key 'public', a message 'hello world' and want to do something like:
private_key = 'private'
public_key = 'public'
message = 'hello world'
encrypted_value = Crypto.encrypt(message, private_key)
# encrypted_value is now 'd92a01df241a3'
is_verified = Crypto.verify(message, public_key)
# given just the public key and the message, is_verified will
# be able to tell whether it's accurate
# note that the encrypted_value cannot be generated by just the public_key
# but it can be verified by the public_key
You are looking for built-in Ruby OpenSSL wrapper. The documentation provides examples of how to do it.
NOTE: Using
.sign
method below to sign your data with a private key only generates a digital signature, it does not encrypt your data. From your question, it is not clear if you want to encrypt your data or just validate the message. If you want to encrypt the data, you will also have to useCipher
class. You need only a digital signature to verify that your data has not been tempered with and been signed by you!Sign your message
Now, send your data & signature to the receiving end. Also, you may consider using PKCS#7 as a standard way to pack your data and signature.
Verify your message & signature