using public key cryptography to send a message (old version)

Created: — modified: — tags: security

New version, using certificates (and, more importantly, secrets of arbitrary length without extra commands), see here.

Note that this version can't encrypt messages longer than few words:

  1. The person receiving the message generates public and private keys, like this:

    openssl genpkey -out key.priv -outpubkey key.pub -algorithm RSA
    

    Then they send the public key (key.pub) to the person sending the message, and keep the private key (key.priv) to themselves for step 3.

  2. The person sending the message encrypts it like this:

    openssl pkeyutl -encrypt -inkey key.pub -pubin -in file.txt -out file.rsa
    

    Where file.txt contains the message you want to encrypt. If you omit the -in file.txt part, you can simply type the message in console. This command will create file.rsa file with encrypted message. Send it to the person receiving the message.

  3. The person receiving the message can decrypt it using the private key generated on step 1, like this:

    openssl pkeyutl -decrypt -inkey key.priv -in file.rsa # -out file.txt
    

    Note that if you add -out file.txt part, then the secret message will be saved in file.txt, otherwise you'll see it on screen.

Source which uses older openssl commands


To encrypt longer versions, you can combine symmetric and asymmetric crypto! Reuse step 1, and then:

  1. The person sending the message encrypts it like this:

    openssl rand -base64 32 > pass.txt
    openssl enc -aes128 -pbkdf2  -in file.txt -out file.aes -pass file:pass.txt
    openssl pkeyutl -encrypt -inkey key.pub -pubin -in pass.txt -out pass.rsa
    
  2. The person receiving the message can decrypt it using the private key generated on step 1, like this:

    openssl pkeyutl -decrypt -inkey key.priv -in pass.rsa -out pass.txt
    openssl enc -aes128 -pbkdf2  -d -in file.aes -out file.txt -pass file:pass.txt