What is gpg key in linux

What is GPG / PGP

GnuPG (more commonly known as GPG) is an implementation of a standard known as PGP (Pretty Good Privacy). It uses a system of «public» and «private» keys for the encryption and signing of messages or data.

Understanding public vs. private keys

Private keys are the first half of a GPG key which is used to decrypt messages that are encrypted using the public key, as well as signing messages — a technique used to prove that you own the key. As the name implies, this part of the key should never be shared.

Public keys are the second half of a key which is used to encrypt messages for the owner of the private key. As the name implies, this part of the key is safe to give out to the public, as it can only be used to encrypt messages or data for the private key owner.

You can download GnuPG (including graphical versions for those uncomfortable with command line) for various platforms, including Windows and macOS / OSX from the GnuPG Website.

On most Linux distributions, GnuPG is included by default as the command line utility gpg , or is available in your package manager.

For our usage examples, we only cover the command line version of GPG. If you’re using a GUI version, you should be able to find guides online on how to use them.

Looking to buy a Virtual or Dedicated server? Do you like privacy and low prices? Try Privex!

We have virtual servers starting from just US$0.99/mo, and dedicated servers starting from as low as US$50/mo

Unlike other hosts, we don’t ask for any personal details — only a name (can be an alias / username), and an e-mail address so we can send you your server details and renewal invoices.

We also accept several different cryptocurrencies with our own in-house payment processor — no third parties involved in processing your payments.

At the time of writing, we currently accept: Bitcoin (BTC), Litecoin (LTC), Monero (XMR), Dogecoin (DOGE), HIVE, and HBD

Order a server TODAY! Privacy is affordable™

Generating a key pair and exporting the public key

To use GPG to send and receive messages securely, first you must generate a key pair.

NOTE: If you want to be able to add a comment to the key, change the bit size (e.g. RSA 2048 or 4096) or algo, or other extra key options you might wish to adjust, you should use gpg —full-generate-key instead:

After creating a key pair, you’ll want to export the public key to share with others.

In the above example, the public key was exported to john_doe.asc , you should open the file in a text editor such as Notepad, and make sure the first line shows:

This is to make sure you haven’t accidentally exported your private key.

Importing a public key from a key server

Next, you’ll want to import the public key of the person/organization you want to send and encrypted message to.

The below example imports the Privex Support key (key ID 288D D163 2F6E 8951) from a key server.

DISCLAIMER: The Privex Support key is occasionally rotated. For the latest key fingerprint, you should check the Contact Us page

Читайте также:  Linux telnet не подключается

Change the default key server in your config to prevent issues with —recv-keys

A lot of systems are pre-configured to use unreliable / broken GPG key servers, which can cause problems when using —recv-keys . You can resolve most problems with —recv-keys / —search-keys by adding a reliable key server to your GPG config:

Commands to fix keyserver config

Once you’ve added the keyserver setting to your config, you should now be able to use —recv-keys and —search-keys without issues 🙂

Retrieve a key from a specific key server for just one command

You can use the —keyserver flag to manually specify a key server to use, which will only be used for that one command. This can be useful if you can’t find a key on your default keyserver, and need to temporarily try downloading the key from a different keyserver.

Retrieve 288D D163 2F6E 8951 from keys.openpgp.org

Searching for keys on a key server (e.g. by name or email)

If we search for privex.io on keys.openpgp.org — it’ll come back with nothing. This is because keys.openpgp.org does not allow searching by names / domains / comments.

However, if we search for an exact email, it will return results if they’re found:

If we enter the number 1 and hit enter, then it will import the first key that it found

Other keyservers, such as hkps://keyserver.ubuntu.com support searching by name / domain etc. — if we search for privex.io — we can see 4 different keys are available, which you can select and download.

Searching keyserver.ubuntu.com for privex.io:

If we enter the value 1 2 3 4 — it will import the keys 1, 2, 3, and 4:

Encrypting and sending your message

Now, write your message in a plain text editor such as Notepad (Windows) or Textedit (Mac). You may want to put your public key at the end of the message if you want it to be sent encrypted, otherwise you’ll have to send your public key as an attachment or unencrypted text in the message.

Let’s assume you saved your message as message.txt . Now let’s encrypt it for Privex Support.

The above command should’ve encrypted the file message.txt for the public key with the ID 2E833D27B0E01433 (Privex Support), and outputted the encrypted version as message.txt.asc

Now just open up the .asc file, you should see it starts with

Simply copy and paste the contents of this file (including the BEGIN and END lines) into an email or other form of message, and make sure you’ve included your public key in some form — either in the encrypted message, or sent in plain text with the message (e.g. pasted at the end, or attached to an email). Finally, send the message.

Decrypting an encrypted message sent to you

To decrypt a message sent to you, assuming it’s saved as reply.txt.asc , simply run the following command, gpg will automatically select the correct private key to decrypt the message and output it to the terminal.

Decrypt an encrypted message

You can also pipe the encrypted message into GPG. This is very useful for interacting with the clipboard — e.g. the pbpcopy and pbpaste commands on macOS (you can also setup pbpaste/copy on Linux, by installing some extra packages and adding some aliases)

Piping pbpaste into gpg -d (decrypt)

If you want to save the message / data instead of outputting it to the terminal, use shell redirection.

The below example outputs the message to reply.txt : reply.txt» >

Trust a GPG key to stop getting asked whether you’re sure you want to use a certain key

By default, GPG will assume imported public keys are unsafe, and will nag you to confirm that you’re absolutely certain you want to sign/verify/decrypt/encrypt something for a certain key. For example, if you try to encrypt a message for Privex Support, you’ll likely see something like this:

To fix this issue, you need to sign the public key which GPG is complaining about, which acts as a statement to GPG «I, john@example.com [ABCD1234] — am 100% certain that key DE12FABC belongs to the person I believe it does.»

Sign the Privex Support key to tell GPG you trust it

Читайте также:  Stalker тема для windows

Once you run this command, you’ll be shown information about the key you’re signing, and the default key which GPG will use to sign the key:

Now, if we try to encrypt a message for Privex Support — GPG won’t bother us with an «are you SURE this is the right key?» prompt, and just encrypt the message immediately:

Signing and verifying a file / message to show that you approve a message, or verify the authenticity of a file

Clearsign (GPG signature as part of the file/message)

For signing simple text messages, clearsign is usually used, as they’re often intended for humans to read, thus the visible signature won’t cause much of an issue

First let’s create a file message.txt

Now, we’ll sign it with our John Doe key

Sign the file with the john@example.org private key

If we now read the file message.txt.asc — we can see both the original message, and the signature:

Verify a clear-signed message

Verify the message.txt.asc file’s signature

NOTE A user needs the GPG public key for john@example.com to be able to verify the signature, while you require the private key to be able to make a signature.

Output from the command:

Detached Signature (separate signature file)

Detached signatures are very common for signing files where the signature would prevent the file from being able to be read, or where you don’t have the ability to / don’t want to distribute the original file with your signature.

They’re most common for verifying software, to ensure that nobody has tampered with the application other than the actual developer(s) who’ve signed it.

First we’ll remove the previous clearsign signature

Now we’ll use the -b flag to create a detached signature (alternatively you can use —detach-sign for clarity)

If we cat message.txt.asc — we can see this time that it’s JUST the signature, not the original contents. This means the person verifying the signature, needs both the original file, and the signature file (.asc)

Verifying a detached signature

There are two ways to verify a detached signature.

1) Ensure the signature file has the same filename as the file being verified, but ends in either .asc (ASCII Armoured) or .gpg (raw binary)

If the original file has the same name, minus the .asc / .gpg extension, then you can simply pass the signature’s name to gpg, and it will auto-detect the original filename

This would output:

2) Manually specify both the signature filename and the original filename

If the original file has a different name to the signature, OR the signature and file are in different locations, then you should specify both filenames to GPG, placing the signature’s file name after —verify , and then the original filename after that.

This would output:

Looking to buy a Virtual or Dedicated server? Do you like privacy and low prices? Try Privex!

We have virtual servers starting from just US$0.99/mo, and dedicated servers starting from as low as US$50/mo

Unlike other hosts, we don’t ask for any personal details — only a name (can be an alias / username), and an e-mail address so we can send you your server details and renewal invoices.

We also accept several different cryptocurrencies with our own in-house payment processor — no third parties involved in processing your payments.

At the time of writing, we currently accept: Bitcoin (BTC), Litecoin (LTC), Monero (XMR), Dogecoin (DOGE), HIVE, and HBD

Источник

Шифрование файлов и папок в 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 — изменить пароль для ключа.
Читайте также:  Полное клонирование жесткого диска с системой mac os

А теперь рассмотрим по порядку, что нам нужно для того, чтобы выполнять шифрование файлов 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 используется людьми для хранения важных данных, а механизм подписей популярен среди разработчиков дистрибутивов. Если у вас остались вопросы, спрашивайте в комментариях!

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

Источник

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