OpenSSL: Simple public key encryption. Encrypt files using OpenSSL How to: Decrypt a file

As you understand from these articles, not every program that promises to encrypt files ensures the security of information. As Bruce Schneier says, “There are two types of cryptography: cryptography that will prevent your little sister from reading your files, and cryptography that will prevent your uncles in the government from reading your files.” OpenSSL is a very popular library that is used by many for cryptography - both paid and free programs. OpenSSL implements a large number of algorithms and encryption modes, which allows you to make the choice yourself, and not the program developer.
In addition to the library itself, the OpenSSL package includes a set console utilities. This article will focus on encrypting files with symmetric algorithms.
To encrypt a file using OpenSSL, you need to use the openssl enc command. Available for this wide choose encryption algorithms that OpenSSL supports - Blowfish, Camellia, DES, RC2, RC4, RC5, IDEA, AES and others. In addition to various algorithms, different encryption modes are also available - ECB, CBC, CFB, OFB. Some encryption modes can be used with different bit depths.
To view the list of options for the openssl enc command, just type:

$ openssl enc --help
options are
-in input file
-out output file
-pass pass phrase source
-e encrypt
-d decrypt
-a/-base64 base64 encode/decode, depending on encryption flag
-k passphrase is the next argument
-kfile passphrase is the first line of the file argument
-md the next argument is the md to use to create a key
from a passphrase. One of md2, md5, sha or sha1
-S salt in hex is the next argument
-K/-iv key/iv in hex is the next argument
- print the iv/key (then exit if -P)
-bufsize buffer size
-nopad disable standard block padding
-engine e use engine e, possibly a hardware device.
Cipher Types
-aes-128-cbc -aes-128-cfb -aes-128-cfb1
-aes-128-cfb8 -aes-128-ecb -aes-128-ofb
-aes-192-cbc -aes-192-cfb -aes-192-cfb1
-aes-192-cfb8 -aes-192-ecb -aes-192-ofb
-aes-256-cbc -aes-256-cfb -aes-256-cfb1
-aes-256-cfb8 -aes-256-ecb -aes-256-ofb
-aes128 -aes192 -aes256
-bf -bf-cbc -bf-cfb
-bf-ecb -bf-ofb -blowfish
-camellia-128-cbc -camellia-128-cfb -camellia-128-cfb1
-camellia-128-cfb8 -camellia-128-ecb -camellia-128-ofb
-camellia-192-cbc -camellia-192-cfb -camellia-192-cfb1
-camellia-192-cfb8 -camellia-192-ecb -camellia-192-ofb
-camellia-256-cbc -camellia-256-cfb -camellia-256-cfb1
-camellia-256-cfb8 -camellia-256-ecb -camellia-256-ofb
-camellia128 -camellia192 -camellia256
-cast -cast-cbc -cast5-cbc
-cast5-cfb -cast5-ecb -cast5-ofb
-des -des-cbc -des-cfb
-des-cfb1 -des-cfb8 -des-ecb
-des-ede -des-ede-cbc -des-ede-cfb
-des-ede-ofb -des-ede3 -des-ede3-cbc
-des-ede3-cfb -des-ede3-cfb1 -des-ede3-cfb8
-des-ede3-ofb -des-ofb -des3
-desx -desx-cbc -idea
-idea-cbc -idea-cfb -idea-ecb
-idea-ofb -rc2 -rc2-40-cbc
-rc2-64-cbc -rc2-cbc -rc2-cfb
-rc2-ecb -rc2-ofb -rc4
-rc4-40 -rc5 -rc5-cbc
-rc5-cfb -rc5-ecb -rc5-ofb
-seed -seed-cbc -seed-cfb
-seed-ecb -seed-ofb

After the Cipher Types block, the available algorithms are listed along with the modes. The DES encryption algorithm is available in several options. In addition to standard DES, there is also triple 3DES (which also comes in several versions) and DESX. Now let's try to encrypt something.

$ openssl enc -e -in infile.txt -out outfile.bf_cbc -bf-cbc

This command will encrypt the infile.txt file using the blowfish algorithm in CBC mode and write the result to the outfile.bf_cbc file. Before encrypting, you will be asked for an encryption key. To decrypt this file you need to use the following command:

$ openssl enc -d -in outfile.bf_cbc -out dec_file.txt -bf-cbc

When asked to enter a key, you must enter the key that was entered during encryption.
If you want to compress data, then this must be done, for obvious reasons, before encryption.
Now let's look at the options command line. The -e option specifies that the file should be encrypted (this option is enabled by default), and the -d option should be decrypted. The encryption key can be entered when calling openssl enc using the -k option, or in a file using the -kfile option.
Using the -nosalt option, you can disable the use of salt during encryption (not recommended as it reduces the security of the cipher).
Using this utility you can also convert to base64 and back, but this conversion is not encryption. Read more on the project website - http://www.openssl.org/docs/apps/enc.html. If you have any questions please ask.

P.S. After the information has been encrypted, it is necessary to properly delete the original file so that no residual information remains. To do this, you can use some program that implements the Gutman method. Also, if you enter a password on the command line, make sure that it is not saved in history, and if it is read from a file, then that it has been completely deleted.

There are a lot of situations when you need to encrypt a specific file or folder. For example, if data is transmitted over open channels or stored on external media. Many people (including me) use truecrypt, but the main purpose of this program is to work with encrypted partitions, so it is not very good in this case.

OpenSSL is quite suitable for such tasks - a reliable cross-platform solution. OpenSSL supports a variety of encryption algorithms, plus it is installed by default in many operating systems, and installation on the rest is not difficult.

Below is the basics of using symmetric and asymmetric encryption in OpenSSL, as well as a couple of scripts that simplify asymmetric encryption with a one-time key.

The simplest way to protect data using OpenSSL is symmetric encryption. The following commands encrypt and decrypt the documents.zip file using the AES algorithm with a 256-bit key length:

Openssl enc -aes-256-cbc -salt -in documents.zip -out documents.enc
openssl enc -d -aes-256-cbc -in documents.enc -out documents.zip

The problem with these commands may be that they require a password. There are situations when this is undesirable. For example, automatic backup/encryption of data on a schedule, or if data is encrypted by one person and decrypted by another.

It is for such cases that public key encryption was invented. In general, you will need to create an open and private key And. The first command will generate the private key private.pem, the second will create public key public.pem:

Openssl genrsa -out private.pem -aes256 2048
openssl rsa -in private.pem -pubout -out public.pem

As a result, you get a pair of RSA keys 2048 bits long. Unfortunately, in the RSA system, the size of the encrypted data is limited by the key size, so it will not be possible to encrypt more than 2Kb of data. There is a way around this - the information is first encrypted with a symmetric algorithm (similar to the one used above) using a one-time key. This one-time key is then encrypted with the public key. During decryption, the one-time key is decrypted with the private key. More details about this have already been written very well in.

The following script will help automate encryption, as the output of which you will receive a one-time key and data (encrypt.sh) in encrypted form:

FILENAME="$1"
PUBLICKEY="$2"
SESSIONKEY="$3"
RESULT="$4"

# Generate the random symmetric-key
PASSIZE=30
if [ -c /dev/urandom ] ; then
KEY=`head -c 30 /dev/urandom | openssl enc -base64`
else
KEY=`openssl rand -base64 30`
fi
export KEY

# Encrypt the symmetric key using the public key
openssl rsautl -encrypt -inkey "$PUBLICKEY" -out "$SESSIONKEY" -pubin<$KEY
EOF

# Encrypt the file
openssl enc -aes-256-cbc -pass env:KEY -in "$FILENAME" -out "$RESULT"

The following command uses the public key public.pem to encrypt the documents.zip file. It will generate an encrypted one-time key session.key and encrypted data documents.enc:

./encrypt.sh documents.zip public.pem session.key documents.enc

Decryption script (decrypt.sh):

PRIVATEKEY="$1"
SESSIONKEY="$2"
ENCRYPTED="$3"
DECRYPTED="$4"

# Decrypt the symmetric key using the private key
KEY=` openssl rsautl -decrypt -inkey "$PRIVATEKEY" -in "$SESSIONKEY" `
export KEY

# Decrypt the file
openssl enc -aes-256-cbc -d -pass env:KEY -in "$ENCRYPTED" -out "$DECRYPTED"

The decryption command uses the private key private.pem and the one-time key session.key to decrypt the documents.enc file. It will generate a documents.zip file:

./decrypt.sh private.pem session.key documents.enc documents.zip

As you can see, public key encryption can be almost as simple as symmetric encryption. But there is an even simpler way. I was prompted to write this post by the SbF₅ blog. Its author (undoubtedly more experienced in bash than me) wrote a script that archives a folder, encrypts it with a public key and generates another script containing everything necessary: ​​a one-time key, data and the actual commands for decryption. Additionally, the script can generate an RSA key pair for you:

./encrypt-file.sh -keys public.pem private.pem
./encrypt-file.sh folder public.pem > decrypt-folder.sh
chmod +x decrypt-folder.sh
./decrypt-folder.sh private.pem > folder.tar

In this example, we first generated a key pair. After this, the folder folder was encrypted into the decrypt-folder.sh script and then decrypted into the folder.tar archive. A possible disadvantage of this method is that the data in decrypt-folder.sh is stored in BASE64 format, and therefore its size increases.

UPD Moved to the Information Security blog.

There are a lot of situations when you need to encrypt a specific file or folder. For example, if data is transmitted over open channels or stored on external media. Many people (including me) use truecrypt, but the main purpose of this program is to work with encrypted partitions, so it is not very good in this case.

OpenSSL is quite suitable for such tasks - a reliable cross-platform solution. OpenSSL supports various encryption algorithms, plus it is installed by default on many operating systems, and installation on others is easy.

Below is the basics of using symmetric and asymmetric encryption in OpenSSL, as well as a couple of scripts that simplify asymmetric encryption with a one-time key.

The simplest way to protect data using OpenSSL is symmetric encryption. The following commands encrypt and decrypt the documents.zip file using the AES algorithm with a 256-bit key length:

Openssl enc -aes-256-cbc -salt -in documents.zip -out documents.enc
openssl enc -d -aes-256-cbc -in documents.enc -out documents.zip

The problem with these commands may be that they require a password. There are situations when this is undesirable. For example, automatic backup/encryption of data on a schedule, or if data is encrypted by one person and decrypted by another.

It is for such cases that public key encryption was invented. In general, you will need to create a public and private key. The first command will generate the private key private.pem, the second will generate the public key public.pem:

Openssl genrsa -out private.pem -aes256 2048
openssl rsa -in private.pem -pubout -out public.pem

As a result, you get a pair of RSA keys 2048 bits long. Unfortunately, in the RSA system, the size of the encrypted data is limited by the key size, so it will not be possible to encrypt more than 2Kb of data. There is a way around this - the information is first encrypted with a symmetric algorithm (similar to the one used above) using a one-time key. This one-time key is then encrypted with the public key. During decryption, the one-time key is decrypted with the private key. More details about this have already been written very well in an article on Habré.

The following script will help automate encryption, as the output of which you will receive a one-time key and data (encrypt.sh) in encrypted form:

FILENAME="$1"
PUBLICKEY="$2"
SESSIONKEY="$3"
RESULT="$4"

# Generate the random symmetric-key
PASSIZE=30
if [ -c /dev/urandom ] ; then
KEY=`head -c 30 /dev/urandom | openssl enc -base64`
else
KEY=`openssl rand -base64 30`
fi
export KEY

# Encrypt the symmetric key using the public key
openssl rsautl -encrypt -inkey "$PUBLICKEY" -out "$SESSIONKEY" -pubin<$KEY
EOF

# Encrypt the file
openssl enc -aes-256-cbc -pass env:KEY -in "$FILENAME" -out "$RESULT"

The following command uses the public key public.pem to encrypt the documents.zip file. It will generate an encrypted one-time key session.key and encrypted data documents.enc:

./encrypt.sh documents.zip public.pem session.key documents.enc

Decryption script (decrypt.sh):

PRIVATEKEY="$1"
SESSIONKEY="$2"
ENCRYPTED="$3"
DECRYPTED="$4"

# Decrypt the symmetric key using the private key
KEY=` openssl rsautl -decrypt -inkey "$PRIVATEKEY" -in "$SESSIONKEY" `
export KEY

# Decrypt the file
openssl enc -aes-256-cbc -d -pass env:KEY -in "$ENCRYPTED" -out "$DECRYPTED"

The decryption command uses the private key private.pem and the one-time key session.key to decrypt the documents.enc file. It will generate a documents.zip file:

./decrypt.sh private.pem session.key documents.enc documents.zip

As you can see, public key encryption can be almost as simple as symmetric encryption. But there is an even simpler way. I was prompted to write this post by the SbF₅ blog. Its author (undoubtedly more experienced in bash than me) wrote a script that archives a folder, encrypts it with a public key and generates another script containing everything necessary: ​​a one-time key, data and the actual commands for decryption. Additionally, the script can generate an RSA key pair for you:

./encrypt-file.sh -keys public.pem private.pem
./encrypt-file.sh folder public.pem > decrypt-folder.sh
chmod +x decrypt-folder.sh
./decrypt-folder.sh private.pem > folder.tar

In this example, we first generated a key pair. After this, the folder folder was encrypted into the decrypt-folder.sh script and then decrypted into the folder.tar archive. A possible disadvantage of this method is that the data in decrypt-folder.sh is stored in BASE64 format, and therefore its size increases.

UPD Moved to the Information Security blog.

OpenSSL is a powerful set of tools that can be used to encryption of files and messages.

If you want to use the same password for both plaintext encryption, and for its subsequent decryption, then you need to use symmetric encryption algorithm.

From this article you will learn how encrypt and decrypt files and messages using a password from the command line on Linux using OpenSSL.

How to: Encrypt a file

$ openssl enc -aes-256-cbc -salt -in file.txt-out file.txt.enc

256bit AES is a cryptographic algorithm used by the United States government to encrypt information at the most sensitive level.

Option -salt(salt) must be used ALWAYS, if the secret key is generated based on the password.

Without using the option -salt, it is possible to conduct a highly effective dictionary attack that will lead to the disclosure of encrypted data. The reason for this is that without adding a 'salt', the same password will always generate the same secret key.

When a salt is used, the first 8 bytes are reserved for it. It is generated randomly when a file is encrypted and read from the encrypted file during decryption.

How to: Decrypt a file

$ openssl enc -aes-256-cbc -d-in file.txt.enc-out file.txt

Base64 Encoding and Decoding

Base64 encoding is standard method to convert 8-bit binary information into a limited subset of ASCII characters for secure transport through email and other systems that do not support the 8-bit format.

By default, the encrypted file is created in binary format. If you are going to send it by e-mail, IRC, etc., you must save it in Base64 encoding. To encrypt a file in Base64 encoding, you need to add the option -a:

$ openssl enc -aes-256-cbc -salt -a-in file.txt-out file.txt.enc

Options Description
-a Tells OpenSSL that the encrypted data is Base64 encoded.

Also, option -a, must be indicated during decryption:

$ openssl enc -aes-256-cbc -d -a-in file.txt.enc-out file.txt

Encryption/Decryption without password prompt

Since the password is made visible, this method should only be used where security is not important.

By default, the user is prompted to enter the password interactively.

When writing BASH script You may want to arrange for the password to be entered non-interactively using the option -k.

It is for such cases that public key encryption was invented.

Encrypt the file using the provided password:

$ openssl enc -aes-256-cbc -salt -in file.txt -out file.txt.enc -k PASS

Decrypt the file using the provided password:

$ openssl enc -aes-256-cbc -d -in file.txt.enc -out file.txt -k PASS

Tools like OpenSSH and OpenSSL need no introduction. These are the eternal friends of any system administrator and many advanced users. However, not everyone knows about their true power and capabilities accumulated over years of development. Today you will discover a lot of interesting ways to use these programs.

OpenSSH

OpenSSH, which replaced the leaky Telnet, still ranks first among systems remote control thanks to its safety and ease of use. Everyone can understand it, even the most chrome-plated teapots, but the vast majority of users use a minimum of its capabilities. Let's skip the stories about keys, port forwarding, proxying and other useful but well-known techniques and look at actually interesting and not very common ways to use this tool.

INFO

WITH full list OpenSSL commands can be found using following parameters: list-standart-commands, list-message-digest-commands, list-cipher-commands.

So, trick number one is multiple connections. OpenSSH is capable of serving many simultaneous connections to the same machine. Typically, users simply run a command and wait for it to complete before running the next one. Fortunately, this problem can be easily circumvented by splitting a single connection into multiple sessions. Just add the following lines to your ssh config (~/.ssh/config):

ControlMaster auto ControlPath ~/.ssh/mux_%h_%p_%r

You can create as many connections to the same server as you deem necessary, and you won’t need to waste time on re-authentication.


Trick number two is proxying connections. Let's say you cannot create a connection to the SSH server directly, but you can use another host for this, to which you also have SSH access. Add the following lines to your config:

ForwardAgent yes Host host HostName host.com ProxyCommand ssh proxy-host.com \ netcat -q 600 %h %p

The ssh host command will create a connection to the host.com server through the proxy-host.com server.

Trick number three is going beyond HTTP isolation. Many organizations not only cut off unwanted traffic, but also force users to access the Internet only using the HTTP protocol. This injustice can be easily circumvented using corkscrew (www.agroman.net/corkscrew/), which can tunnel SSH traffic over HTTP. Just install it on your machine and add the following lines to the config (where proxy.com and 80 are the address of the external HTTP proxy and its port):

Host * ProxyCommand corkscrew proxy.com 80 %h %p

Now all connections will go through the specified HTTP proxy.

Trick number four - test bandwidth networks. To test the connection speed, it is not necessary to install specialized software; the pv utility and good old SSH are enough:

$ sudo apt-get install pv $ yes | pv | ssh host.com "cat > /dev/null"

Trick number five - remote analysis network traffic. Almost every UNIX system has the tcpdump network sniffer, but reading its logs is quite tedious. OpenSSH capabilities will help simplify traffic analysis:

$ssh [email protected] tcpdump -w – "port !22" \ | wireshark -k -i -

Now all traffic passing through host.com will be visible in the wireshark graphical window on your machine.

Trick number six - transfer files at low speed. Sometimes it is necessary to transfer a large number of files to a remote machine, but do this in such a way that the process does not interfere with the network. In this case, you can use the cstream tool:

$ sudo apt-get install cstream $ tar -cj /backup | cstream -t 512k | \ssh host "tar -xj -C /backup"

Trick number seven is to always have an open SSH session. Laptop users, whose connection to the network may not be constant, have to restart the SSH client each time the network appears, and kill it when the connection is lost. You can avoid this by using the autossh tool, which will maintain the illusion permanent connection with the server, restoring communication when the network is available:

$ sudo apt-get install autossh $ autossh -M50000 -t server.example.com\"screen -raAd mysession"

Trick number eight is to run the command on several servers at the same time. No comments needed:

$ echo "uptime" | pee "ssh host1" "ssh host2" \ "ssh host3"

Trick number nine - remote file comparison. It is often necessary to compare the local and remote versions of a config, but copying files back and forth is inconvenient and time consuming. In this case, you can use the following command:

$ ssh user@host cat /path/to/remote/file | \diff /path/to/local/file -

The same can be done for two files located on different servers:

$diff<(ssh host1 cat /etc/apt/sources.list) \ <(ssh host2 cat /etc/apt/sources.list)

cpu0: RNG AES

Benchmark results of cryptographic tools built into the CPU of the VIA Eden platform (processor instructions for working with the AES block symmetric encryption algorithm):

% openssl speed -elapsed -evp aes-256-cbc type 16 bytes 64 bytes256 bytes 1024 bytes 8192 bytes aes-256-cbc 21780.33k79591.78k 198578.08k 317102.05k 383371.05k

Trick number 10 - simultaneous viewing of logs from several machines. Using multitail and SSH, you can easily view logs from two servers simultaneously:

$ sudo apt-get install multitail $ multitail -l "ssh host1 "tail -f \ /var/log/apache2/error.log"" -l "ssh host2 \ "tail -f /var/log/apache2/error. log""

Trick number 11 - copying files from one remote machine to another via a local one. If two remote machines cannot communicate with each other, files can be transferred between them using your computer as an intermediate link:

$ ssh root@host1 "cd /directory && tar -cf – ." |\ ssh root@host2 "cd /dir && tar -xf -"

Trick number 12 - copying the output of the remote command to the clipboard. Often you need to copy the output of a remote command to the clipboard in order to paste it into an email, forum post, etc. The easiest way to do this is using the xclip utility:

$ ssh user@host cat /file.txt | xclip

Trick number 13 - time synchronization using SSH. If the machine does not have access to the NTP server or does not have an NTP client installed on it, you can synchronize the time between machines as follows:

# date --set="$(ssh user@server date)"

Trick number 14 - installing packages from a remote machine onto the local one. It is often necessary to synchronize two machines so that they have the same set of packages installed. This is difficult to do using standard methods, but using SSH it’s as easy as shelling pears:

# ssh remotehost "dpkg --get-selections" | \dpkg --set-selections && dselect install

Trick number 15 - remote screenshot. You can very easily obtain an image of an X server from a remote machine using the standard ImageMagick graphics package:

# ssh user@host "DISPLAY=:0.0 import -window \ root -format png -" | display -format png -

Trick number 16 - speed up data transfer. If the machines with which the connection is established are located inside a known secure network (for example, an office or home), data transfer using SSH can be somewhat faster if you use a less strong encryption algorithm. To do this, add the following lines to the configuration file:

Host host.com Ciphers arcfour256 MACs [email protected]

Trick number 17 - outputting audio from a remote machine to a local one. Sometimes you want to get sound along with the desktop picture of the remote machine. This is done using the banal dd:

$ dd if=/dev/dsp | ssh -c arcfour -C \ user@host dd of=/dev/dsp

Trick number 18 - running a local script on a remote machine. Often you need to run a script on a remote machine, but there is no need to copy it there; just run the following simple command:

$ ssh -T user@host< script.sh

OpenSSL

OpenSSL is a data security and certification system that was developed in response to the creation of the Secure Sockets Layer (SSL) protocol by Netscape. Contrary to popular belief, OpenSSL is not a tool for implementing the SSL protocol at all and can perform many different functions, including managing keys and certificates, calculating hashes, etc. Here is just a partial list of the capabilities of this cryptographic combine:

  • creating and managing RSA and DSA keys (rsa, dsa, dsaparam commands);
  • creating x509 format certificates, generating certification requests, recovery (commands x509, req, verify, ca, crl, pks12, pks7);
  • symmetric and asymmetric data encryption (enc, rsautl commands);
  • calculation of hashes (dgst command);
  • working with S/MIME (s/mime command).

OpenSSL can also be used to test SSL servers and clients using special commands s client/s server and for testing the speed of various algorithms (speed command).

We have written more than once about working with the OpenSSL package, so we will not consider standard examples of its use, such as creating hashes and certificates, but will immediately move on to more serious tricks.


Time is money

One of the interesting features of OpenSSL is that it can benchmark the algorithms used and the speed of establishing an SSL connection. The standard s_time command is intended for this. To evaluate the speed of establishing an SSL connection, you need to apply it to the openssl command:

$ openssl s_time -connect gmail.com:443 \ -www /test.html -new 103 connections in 0.75s; 137.33 connections/user sec, bytes read 42436 103 connections in 31 real seconds, 412 bytes read per connection

The same can be done using the most robust algorithms:

$ openssl s_time -ssl3 -cipher HIGH \ -connect gmail.com:443 -www / -new 99 connections in 0.73s; 135.62 connections/user sec, bytes read 40788 99 connections in 31 real seconds, 412 bytes read per connection

These two commands allow you to determine the maximum throughput of the SSL server. But an even more interesting way is to test all supported algorithms. To do this we will have to resort to scripting:

IFS=":" for c in $(openssl ciphers -ssl3 RSA); do echo $c openssl s_time -connect host:443 -www / -new \ -time 10 -cipher $c 2>&1 | grep bytes echo done

This command allows you to measure the speed of establishing an SSL connection using various encryption algorithms, which can be used, for example, to tune an SSL server. If there is no SSL server as such yet, it can be easily emulated using OpenSSL itself. On the server machine we launch the OpenSSL server: