Encrypting files in linux

7 Tools to Encrypt/Decrypt and Password Protect Files in Linux

Encryption is the process of encoding files in such a way that only those who are authorized can access it. Mankind is using encryption from ages even when computers were not in existence. During war they would pass some kind of message that only their tribe or those who are concerned were able to understand.

Linux distribution provides a few standard encryption/decryption tools that can prove to be handy at times. Here in this article we have covered 7 such tools with proper standard examples, which will help you to encrypt, decrypt and password protect your files.

If you are interested in knowing how to generate Random password in Linux as well as creating random password you may like to visit the below link:

1. GnuPG

GnuPG stands for GNU Privacy Guard and is often called as GPG which is a collection of cryptographic software. Written by GNU Project in C programming Language. Latest stable release is 2.0.27.

In most of the today’s Linux distributions, the gnupg package comes by default, if in-case it’s not installed you may apt or yum it from repository.

We have a text file (tecmint.txt) located at

/Desktop/Tecmint/, which will be used in the examples that follows this article.

Before moving further, check the content of the text file.

Now encrypt tecmint.txt file using gpg. As soon as you run the gpc command with option -c (encryption only with symmetric cipher) it will create a file texmint.txt.gpg. You may list the content of the directory to verify.

Note: Enter Paraphrase twice to encrypt the given file. The above encryption was done with CAST5 encryption algorithm automatically. You may specify a different algorithm optionally.

To see all the encryption algorithm present you may fire.

Now, if you want to decrypt the above encrypted file, you may use the following command, but before we start decrypting we will first remove the original file i.e., tecmint.txt and leave the encrypted file tecmint.txt.gpg untouched.

Note: You need to provide the same password you gave at encryption to decrypt when prompted.

2. bcrypt

bcrypt is a key derivation function which is based upon Blowfish cipher. Blowfish cipher is not recommended since the time it was figured that the cipher algorithm can be attacked.

If you have not installed bcrypt, you may apt or yum the required package.

Encrypt the file using bcrypt.

As soon as you fire the above command, a new file name texmint.txt.bfe is created and original file tecmint.txt gets replaced.

Decrypt the file using bcrypt.

Читайте также:  Remove pop up windows что это

Note: bcrypt do not has a secure form of encryption and hence it’s support has been disabled at least on Debian Jessie.

3. ccrypt

Designed as a replacement of UNIX crypt, ccrypt is an utility for files and streams encryption and decryption. It uses Rijndael cypher.

If you have not installed ccrypt you may apt or yum it.

Encrypt a file using ccrypt. It uses ccencrypt to encrypt and ccdecrypt to decrypt. It is important to notice that at encryption, the original file (tecmint.txt) is replaced by (tecmint.txt.cpt) and at decryption the encrypted file (tecmint.txt.cpt) is replaced by original file (tecmint.txt). You may like to use ls command to check this.

Provide the same password you gave during encryption to decrypt.

4. Zip

It is one of the most famous archive format and it is so much famous that we generally call archive files as zip files in day-to-day communication. It uses pkzip stream cipher algorithm.

If you have not installed zip you may like to apt or yum it.

Create a encrypted zip file (several files grouped together) using zip.

Here mypassword is the password used to encrypt it. A archive is created with the name tecmint.zip with zipped files tecmint.txt, tecmint1.txt and tecmint2.txt.

Decrypt the password protected zipped file using unzip.

You need to provide the same password you provided at encryption.

5. Openssl

Openssl is a command line cryptographic toolkit which can be used to encrypt message as well as files.

You may like to install openssl, if it is not already installed.

Encrypt a file using openssl encryption.

Explanation of each option used in the above command.

  1. enc : encryption
  2. -aes-256-cbc : the algorithm to be used.
  3. -in : full path of file to be encrypted.
  4. -out : full path where it will be decrypted.

Decrypt a file using openssl.

6. 7-zip

The very famous open source 7-zip archiver written in C++ and able to compress and uncompress most of the known archive file format.

If you have not installed 7-zip you may like to apt or yum it.

Compress files into zip using 7-zip and encrypt it.

Decompress encrypted zip file using 7-zip.

Note: Provide same password throughout in encryption and decryption process when prompted.

All the tools we have used till now are command based. There is a GUI based encryption tool provided by nautilus, which will help you to encrypt/decrypt files using Graphical interface.

7. Nautilus Encryption Utility

Steps to encrypt files in GUI using Nautilus encryption utility.

Encryption of file in GUI

1. Right click the file you want to encrypt.

2. Select format to zip and provide location to save. Provide password to encrypt as well.

Encrypt File Using Nautilus

3. Notice the message – encrypted zip created successfully.

Encrypted Zip File Confirmation

Decryption of file in GUI

1. Try opening the zip in GUI. Notice the LOCK-ICON next to file. It will prompt for password, Enter it.

Читайте также:  Загрузка профиля windows по умолчанию

Decryption of File

2. When successful, it will open the file for you.

Decryption Confirmation

That’s all for now. I’ll be here again with another interesting topic. Till then stay tuned and connected to Tecmint. Don’t forget to provide us with your valuable feedback in the comments below. Like and share us and help us get spread.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Шифрование файлов и папок в Linux

В современном мире каждый аспект нашей личной жизни записывается на компьютеры. Один из способов защиты наиболее важной информации — шифрование файлов и каталогов. Во время шифрования содержимое файлов перемешивается с избыточными данными в соответствии с установленным алгоритмом, таким образом, что расшифровать его можно только имея специальный пароль или ключ.

В операционной системе Linux есть замечательный инструмент с открытым исходным кодом для шифрования файлов — GNU Privacy Guard или просто GPG, который может быть использован для шифрования любого файла из командной строки или в графическом режиме. О нем и пойдет речь в сегодняшней статье.

Утилита GPG

Перед тем как перейти к использованию утилиты, давайте рассмотрим ее синтаксис:

$ gpg опции файл параметры

Опции указывает что необходимо сделать с файлом, как это сделать и какие возможности использовать. Давайте рассмотрим самые основные опции, которые мы будем использовать в этой статье:

  • -h — вывести справку по утилите;
  • -s, —sign — создать цифровую подпись, эта опция используется вместе с другими опциями для шифрования;
  • —clearsign — подписать незашифрованный текст;
  • -e, —encrypt — зашифровать данные, с помощью ключа;
  • -с, —symmetric — зашифровать данные, с помощью пароля;
  • -d, —decrypt — расшифровать данные, зашифрованные с помощью ключа или пароля;
  • —verify — проверить подпись;
  • -k, —list-keys — вывести доступные ключи;
  • —list-sigs — вывести доступные подписи;
  • —fingerprint — вывести все ключи вместе с их отпечатками;
  • —delete-key — удалить ключ;
  • —delete-secret-key — удалить секретный ключ;
  • —export — экспортировать все ключи;
  • —export-secret-keys — экспортировать все секретные ключи;
  • —import — импортировать ключи;
  • —send-keys — отправить ключи на сервер, должен быть указан сервер ключей;
  • —recv-keys — получить ключи от сервера ключей;
  • —keyserver — указать сервер ключей;
  • —fetch-keys — скачать ключи;
  • —gen-key — создать ключ;
  • —sign-key — подписать ключ;
  • —passwd — изменить пароль для ключа.

А теперь рассмотрим по порядку, что нам нужно для того, чтобы выполнять шифрование файлов Linux.

Шифрование файлов с помощью пароля

Симметричный шифр — самый простой и в то же время надежный способ шифрования файлов linux. Расшифровать файл сможет любой у кого есть пароль. Для использования просто запустите терминал и выполните команду gpg с параметром -c:

Читайте также:  Установка языковых пакетов для windows

gpg -c имя файла

Утилита создаст файл с расширением gpg. Для расшифровки используйте:

Шифрование с использованием ключей

Асимметричный шифр более надежный так как для шифрования используется два ключа — публичный, собственно для шифрования, которым может воспользоваться любой, и приватный — для расшифровки. Причем файл можно расшифровать только с помощью приватного ключа, даже если вы зашифровали файл, без приватного ключа вы его не расшифруете.

Сначала необходимо настроить gpg, создать пару ключей, для этого наберите:

Программа задаст ряд вопросов для настройки ключа:

Выберите требуемый тип ключа.

Выберите нужный размер для ключа, обычно 2048 будет достаточно.

Выберите строк действия для ключа.

Проверьте все ли правильно.

Введите имя нового ключа, фактически, это имя пользователя, но вы будете использовать его чтобы зашифровать файл linux, поэтому выбирайте обдумано.

Введите ваш email адрес.

Описание ключа, если нужно.

Финальная проверка, затем нажмите O для завершения.

Процесс генерации может занять некоторое время. Когда все будет готово в каталоге

./gnupg появятся два файла. В файле pubring.gpg публичный ключ, а в secring.gpg приватный.

Также вы можете посмотреть список доступных ключей:

Если вы собираетесь шифровать файлы на другом компьютере необходимо экспортировать публичный ключ, для этого есть опция -а:

gpg -a -o gpgkey.asc —export имя_ключа

Затем передаем файл на целевое устройство и импортируем ключ:

gpg —import gpgkey.asc

После импорта ключа уровень доверия к нему по умолчанию будет неизвестным поэтому при каждом шифровании gpg будет спрашивать действительно ли вы доверяете этому ключу. Чтобы этого избежать нужно указать уровень доверия. Для этого воспользуйтесь редактором ключей:

gpg —edit-key Username

Для выбора уровня доверия введите команду trust:

Для своих ключей можно использовать пункт абсолютно доверяю с номером 5, вы же знаете что это именно ваш ключ.

Теперь можно переходить к шифрованию. Для того чтобы зашифровать файл linux используйте команду:

gpg -e -r ид_пользователя имя_файла

Ид пользователя нужно указывать тот что вы использовали при создании ключа. Для расшифровки используйте:

gpg -d имя_файла.gpg

Для каталогов действия аналогичны только сначала нужно создать архив с помощью tar:

tar -cf — каталог | gpg -e -r ид_пользователя

А для расшифровки:

gpg -d каталог.gpg | tar -xvf

Подписи и шифрование

Для проверки подлинности файлов может использоваться не шифрование, а подпись. Тогда на основе файла и ключа создается отпечаток, который записывается в файл. Если файл будет изменен, то отпечаток уже не совпадет.

Вы можете подписать файл с помощью опции —sign:

gpg —sign имя_файла

Если вы не хотите изменить исходный файл, то можно создать подпись в отдельном файле:

gpg -b имя_файла

Тогда в каталоге, рядом с файлом появиться файл .sig с подписью. Дальше, чтобы проверить достаточно использовать команду verify:

gpg —verify textfile.sig textfile

Если файл был изменен, то вы увидите, что подпись не сходиться.

Выводы

В этой статье мы рассмотрели как выполняется шифрование файла linux, а также настройка утилиты gpg. Шифрование gpg linux используется людьми для хранения важных данных, а механизм подписей популярен среди разработчиков дистрибутивов. Если у вас остались вопросы, спрашивайте в комментариях!

На завершение отличное видео о том, как работает асимметричный алгоритм шифрования:

Источник

Оцените статью