- Tutorial: Encrypt, Decrypt, Sign a file with GPG Public Key in Linux
- What is encryption?
- How GPG encrypt and decrypt works?
- Step 1: Creating a GPG Key Pair
- Step 2: List the key pair and fingerprint
- Step 3: Exporting and Importing Public Keys
- Step 4: Signing a Public Key
- Step 5: Encrypting and Decrypting a File
- Deleting public keys from keyring
- Conclusion
- Related Posts
- Шифрование файлов и папок в Linux
- Утилита GPG
- Шифрование файлов с помощью пароля
- Шифрование с использованием ключей
- Подписи и шифрование
- Выводы
Tutorial: Encrypt, Decrypt, Sign a file with GPG Public Key in Linux
Table of Contents
In my last article I shared the steps to improve Disk IO Performance in Linux. Security is a major part of the foundation of any system that is not totally cut off from other machines and users. In this article I will guide you with the steps to secure your critical data before transferring the file to your client. You can encrypt a file using signed GPG key before you transfer or send the file to the recipient. Once the file is received by the client, they can further decrypt the file before viewing the content. This way you can be assured that you secret file is not targeted by any hacker to steal the data.
What is encryption?
One of the building blocks of security is encryption, which provides a means of scrambling data for secure transmission to other parties. In cryptographic terms, the data or message to be encrypted is referred to as plaintext, and the resulting encrypted block of text as ciphertext. Processes exist for converting plaintext into ciphertext through the use of keys, which are essentially random numbers of a specified length used to lock and unlock data. This conversion is achieved by applying the keys to the plaintext according to a set of mathematical instructions, referred to as the encryption algorithm.
How GPG encrypt and decrypt works?
GPG uses public key encryption wherein you create a key pair: one private or secret key you keep to yourself and one public key you share with your correspondents or the world. The important part of this two-key system is that neither key can be calculated by having the other. They are each an independent and necessary part of the system and are based upon solid mathematical foundations.
This setup allows you to
- Use your private key to sign a document to provide identification and message integrity to a recipient who has your public key.
- Identification means the recipient can be certain the document came from you.
- Message integrity means the recipient knows the message has not been altered.
- You can provide these features because only you have your private key.
- Use the recipient’s public key to encrypt a document and provide secrecy.
- Secrecy means that only the recipient (who has the corresponding private key) can decrypt the document.
- Combine these steps to provide identification, message integrity, and secrecy (i.e., only the recipient can decrypt the document, the recipient knows the document came from you, and the recipient knows the document was not altered).
Step 1: Creating a GPG Key Pair
To start working with GPG you need to create a key pair for yourself.
- Use gpg with the —gen-key option to create a key pair.
- With this option, gpg creates and populates the
/.gnupg directory if it does not exist.
I am creating the key for user Deepak. Here you specify your real name (you can specify a nickname or handle in the comment section), your email address (the one most people associate with you), and an optional comment. After you specify these traits, a prompt allows you to edit them, quit, or continue (Okay).
At the next step in generating a key pair is specifying a passphrase that will keep your secret key secure. The passphrase should have the Deepak characteristics as a password except it should be longer. Protect the passphrase as you would a password.
After you enter a passphrase, gpg generates your keys. Generating truly random keys requires many random bytes, and generating random bytes requires entropy. As the instructions suggest, type on the keyboard, move the mouse, and use the disk (e.g., copy several large files) to gain entropy.
When gpg finishes, you have generated your key pair. The gpg utility stores all information in the
/.gpg directory. Your keys, and public keys you import using gpg, are stored on your keyring. The output shows two items you will use while working with gpg: the key ID (A469D9E3D1AF4A79DA9D437E2234BC88364829B7 in the example) and the key fingerprint.
Step 2: List the key pair and fingerprint
After you have generated your key pair, you can display information about the pair using the gpg —list-keys and —fingerprint options. A fingerprint is a shorthand for the public portion of a key; you can use it for manual identification of the key.
Step 3: Exporting and Importing Public Keys
Next you need to export your public key and then share the public key to your recipient. The following command exports public keys ( —export ) in ASCII format ( —armor ; or -a ) to a file named deepak_pgp.asc ( —output ; or -o followed by the name of the file you want to write to). If you specify a user, the command exports the public key for that user, otherwise it exports the public keys for all users on the public keyring .
Following, Deepak writes his public key to deepak_pgp.asc and then displays that file.
Next Deepak sends the exported public key using scp to user Amit on node2.
After user Amit receives Deepak’s public key, he adds it to his keyring using the following command:
Below is the list of keys on node1 (Deepak) and node2(Amit) after repeating the above procedure on node2 for Amit
Step 4: Signing a Public Key
If you want to keep a file from prying eyes and ensure that it comes from the person it says it comes from and that it has not be altered, you can sign the file using your private key and encrypt it using the recipient’s public key. The recipient can then decrypt it using his public key and verify the signature using the sender’s public key.
Similarly we will sign Deepak’s key on node2.
Step 5: Encrypting and Decrypting a File
When you encrypt a file using a public key, only the corresponding private key can decrypt the file. If you want to send a file to someone such that only that person can read (or run) that file, you can encrypt the file using the recipient’s public key. Then the recipient can decrypt the file using his private key and no one else can read the file.
I have a secret file on node1
Here I want to make sure this file is read by user Amit only. So, we will encrypt the secret file using Amit’s public key, yielding an unreadable file named secret.gpg .
Verify the encrypted file:
As you can see this is an encrypted file:
So now we can safely send this over to node2 where we expect user Amit to be able to read this file only.
When Amit receives the file, he decrypts it using his secret key which is already available in the keyring:
Next an decrypted file is created ‘secret’ , now Amit can view the content of the file
Deleting public keys from keyring
Assuming you don’t need the secret keys any more and wish to delete it, first we should list if there are any secret keys available for the respective user:
Since I wish to delete Deepak’s key pair so first I will delete his secret key:
Make sure the secret key is deleted properly:
Next we will delete Deepak’s public key:
So let’s delete Deepak’s key:
Verify the available keys:
Conclusion
There are some advantages of using GPG:
- It uses strong, hard-to-crack encryption algorithms.
- It uses the private/public key scheme, which eliminates the need to transfer a password to a message or file recipient in a secure manner. Instead, just send along your public key, which is useless to anyone other than the intended recipient.
- You can use GPG to just encrypt your own files for your own use, the same as you’d use any other encryption utility.
But it also has some disadvantages
- Using public keys instead of passwords is great when you work directly only with people who you implicitly trust. But for anything beyond that, such as distributing a public key to the general population so that everyone can verify your signed messages, you’re dependent upon a web-of-trust model that can be very hard to set up.
- For the end-to-end encryption of email, the recipients of your email must also have GPG set up on their systems and know how to use it. That might work in a corporate environment, but lots of luck getting your friends to set that up. (I’ve never once succeeded in getting someone else to set up email encryption.)Lastly I hope the steps from the article to encrypt, decrypt, sign a file with GPG public key on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your 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:
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 используется людьми для хранения важных данных, а механизм подписей популярен среди разработчиков дистрибутивов. Если у вас остались вопросы, спрашивайте в комментариях!
На завершение отличное видео о том, как работает асимметричный алгоритм шифрования:
Источник