Линукс создать архив с паролем

How to Create an Encrypted (Password Protected) Tar or Zip Archive in Linux

There is often a need to encrypt and/or password protect archive files. Whether you are using them to backup data or share it across the internet, you should take the necessary steps to protect your data. In this quick tip we will examine three ways to create an encrypted and password protected archive in Linux. We will also briefly discuss some pros and cons of each method.

After entering the passphrase you will be asked to repeat it. Then the archive will be created as an encrypted archive, using a secure algorithm and protected by your custom passphrase.

gpg -d myarchive.tar.gz.gpg | tar xzvf -

You will be prompted for the passphrase before the archive is extracted.

I like to always name these types of archives .tar.gz.gpg so I know how they were created. For this example we used tar, gzip and gpg. Also, it is important that you DO NOT forget the passphrase. If you do, there is no way to recover the data.

Use 7zip to create zip format archives with secure algorithms

This is just as secure as the first option since it supports the same AES-256 encryption algorithm, although it does require you put the passphrase or “secret” on the command line, which I am not a fan of. It is also not as convenient because most systems do not come with the P7zip package installed.

To install P7zip on Red Hat, or RH variants like CentOS or Fedora:

On Debian based systems such as Ubuntu:

sudo apt-get install p7zip-full

To create the archive, use the command below, replace “PASSPHRASE” with your own secret passphrase.

7za a -tzip -pPASSPHRASE -mem=AES256 secure.zip file1.txt file2.pdf file3.jpg
$ 7za a -tzip -pPASSPHRASE -mem=AES256 myarchive.zip file1.txt file2.pdf file3.jpg
7-Zip (A) [64] 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
p7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,8 CPUs)
Scanning

Creating archive myarchive.zip
Compressing file1.txt
Compressing file2.pdf
Compressing file3.jpg

Everything is Ok

To extract the zip archive use the following:

Use the zip command to create an encrypted archive

The zip command provides options to allow you to encrypt archives. It uses a known insecure PKZIP algorithm and also requires you to add your passphrase on the command line. The benefit of this method is both Linux and Windows folks can extract the archive without any additional software.

Читайте также:  Intercepter ng for linux

Simply add the —password option to the zip command like so:

zip --password PASSPHRASE myarchive.zip file1.txt file2.pdf file3.jpg

Remember to replace PASSPHRASE with your password.

$ zip --password PASSPHRASE myarchive.zip file1.txt file2.pdf file3.jpg 
adding: file1.txt (deflated 75%)
adding: file2.pdf (deflated 7%)
adding: file3.jpg (deflated 4%)

To extract the archive, use the normal unzip utility. The only difference is you will be asked for a password.

$ unzip myarchive.zip
Archive: myarchive.zip
[myarchive.zip] password:
inflating: file1.txt
inflating: file2.pdf
inflating: file3.jpg

Conclusion

So there you have my three favorite ways to created encrypted archives. There are plenty more ways to accomplish this (openssl, gpg-zip, bcrypt) and some are better than others. If you data is really important, I suggest you read up on the different algorithms and signing methods that are out there and decide for yourself which is right.

Whatever method you use it is important to NOT forget your passphrase.

Resources

Источник

How to Create a Password Protected Zip File in Linux

This simple tutorial shows you how to create a password protected zip file in Linux both in command line and graphical way.

  • Create password protected zip file in Linux command line
  • Create password protected zip file using Nautilus file manager [GUI method]

There are several ways you can encrypt zip file in Linux. There are dedicated command line tools for this task, but I am not going to talk about those. I will show you how to password protect a zip file without installing a dedicated tool.

Create password protect zip file in Linux command line

First thing first, make sure that you have zip support enabled in your Linux system. Use your distribution’s package manager and try to install it. If its not installed already, it will be installed.

In Debian/Ubuntu, you can use this command:

sudo apt install zip unzip

Now, let’s see how to password protect a zip file in Linux. The method is almost the same as creating zip folder in Linux. The only difference is the use of option -e for encryption.

zip -re output_file.zip file1 folder1

The -r option is used to recursively look into directories. The -e option is for encryption.

You’ll be asked to enter and verify the password. You won’t see the password being typed on the screen, that’s normal. Just type the password and press enter both times.

Here’s what the process looks like on the screen:

zip -re my_zip_folder.zip agatha.txt cpluplus.cpp test_dir Enter password: Verify password: adding: agatha.txt (deflated 41%) adding: cpluplus.cpp (deflated 4%) adding: test_dir/ (stored 0%) adding: test_dir/myzip1.zip (stored 0%) adding: test_dir/myzip2.zip (stored 0%) adding: test_dir/c.xyz (stored 0%)

Do note that if someone tries to unzip this file, he/she can see the content of the folder such as which files are there in the zipped file. But the files cannot be read.

Читайте также:  Astra linux установка принтера windows

Create a password protected zip file in Linux using GUI

I have created a password-protected zip file in Ubuntu 18.04 here but you can use the same steps on any Linux distribution with GNOME desktop environment.

Search for Archive Manager and open it.

Archive Manager Ubuntu

Drag and drop the file(s) you want to compress into a zip file. Select Create Archive option here.

Create Archive Ubuntu 1

In here, choose the type of compressed file. It will be .zip in my case. You’ll see the “Other Options”, click on it and you’ll see the password field. Enter the password you want and click on the Save button.

Creating Password Protected Zip file in Ubuntu Linux

That’s it. You have successfully created a password protected zip file in Ubuntu Linux graphically. The next time you want to extract it, it will ask for a password.

Password Protected Zip file in Ubuntu

As you can see, no one (in normal ways) can extract this file without the password. Congratulations, you just learned how to encrypt zip files in Ubuntu Linux.

Just for your information, double-clicking on the password-protected directory might give the impression that you may access the encrypted directory without a password, but you cannot actually read those files.

There are other ways to password protect folders in Linux. This tutorial shows how to do that.

I hope this quick tutorial helped you to create password-protected zip files in Linux.

Источник

Создаем zip-архивы в командной строке

Рассмотрим, как создавать и распаковывать zip архивы из командной строки.

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

Создаем простой zip-архив

Для создания zip-архива просто выполняем команду zip, в первом аргументе указываем имя будущего архива, а во втором сам файл, который мы сжимаем:

Если нужно сжать несколько файлов то перечисляем их через пробел:

zip myarchive.zip myfile.txt yourfile.txt theirfile.txt

Создаем zip-архив папки

Чтобы заархивировать папку, используется ключ -r:

zip -r mydir.zip verygooddir

Создаем zip-архив с паролем

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

zip -P мойпароль -r mysecretdir.zip mysecretdir

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

zip -er mysecretdir.zip mysecretdir

После выполнения данной команды, вам будет предложено дважды ввести пароль. Сам пароль виден при этом не будет:

Enter password: Verify password:

Распаковка zip-архива

Для того, чтобы разархивировать zip-архив, используется команда unzip. Ее можно запускать без опций, только указывая имя архива:

По умолчанию распаковка происходит в текущей директории. Чтобы распаковать архив в другую директорию, используется опция -d, после которой нужно указать путь до директории:

Источник

Как создать защищенный паролем ZIP-архив в Linux

Команды LINUX «от A до Z» — настольная книга с примерами

Как создать защищенный паролем ZIP-архив в Linux

Сегодня поговорим про надежный ZIP-архив. ZIP — очень популярная утилита для сжатия и загрузки файлов для Linux/Unix-подобных операционных систем, а также и для Windows.

Читайте также:  How to change keyboard language in kali linux

В этой статье рассмотрим, как создать защищенный паролем zip-архив в терминале Linux. Это поможет вам изучить практический способ шифрования и дешифрования содержимого ZIP-архива.

Сначала установите zip-утилиту в свой дистрибутив Linux, используя менеджер пакетов, как показано ниже:

Как создать защищенный паролем ZIP-архив в Linux

После установки вы можете использовать команду zip с флагом -p для создания защищенного паролем zip-архива ccat-command.zip из каталога файлов ccat-1.1.0 следующим образом.

Однако указанный метод абсолютно небезопасен, поскольку здесь пароль предоставляется в виде текстового аргумента в командной строке. Во-вторых, он также будет сохранен в файле истории (например, ~.bash_history для bash), что означает, что другой пользователь, имеющий доступ к вашей учетной записи (особенно пользователь root), может легко увидеть пароль, что очевидно совершенно не белопасно.

Поэтому старайтесь всегда использовать флаг -e, он показывает подсказку, позволяющую ввести скрытый пароль, как показано ниже:

Курсы Python с нуля до DevOps на практике за 1,5 часа

Как распаковать защищенный паролем ZIP-архив в Linux

Чтобы распаковать и расшифровать содержимое архивного файла ccat-command.zip, используйте программу распаковки и укажите пароль, который вы задали выше.

Вот и все! В этой статье рассмотрено, как создать защищенный паролем zip-файл в терминале Linux.

Спасибо за уделенное время на прочтение статьи!

Если возникли вопросы, задавайте их в комментариях.

Подписывайтесь на обновления нашего блога и оставайтесь в курсе новостей мира инфокоммуникаций!

Курсы Git за час: руководство для начинающих DevOps / DevNet инженеров

Чтобы знать больше и выделяться знаниями среди толпы IT-шников, записывайтесь на курсы Cisco от Академии Cisco, курсы Linux от Linux Professional Institute на платформе SEDICOMM University.

Курсы Cisco, Linux, кибербезопасность, DevOps / DevNet, Python с трудоустройством!

Спешите подать заявку! Группы стартуют 25 января, 26 февраля, 22 марта, 26 апреля, 24 мая, 21 июня, 26 июля, 23 августа, 20 сентября, 25 октября, 22 ноября, 20 декабря.

  • Поможем стать экспертом по сетевой инженерии, кибербезопасности, программируемым сетям и системам и получить международные сертификаты Cisco, Linux LPI, Python Institute.
  • Предлагаем проверенную программу с лучшими учебниками от экспертов из Cisco Networking Academy, Linux Professional Institute и Python Institute, помощь сертифицированных инструкторов и личного куратора.
  • Поможем с трудоустройством и стартом карьеры в сфере IT — 100% наших выпускников трудоустраиваются.
  • Проведем вечерние онлайн-лекции на нашей платформе.
  • Согласуем с вами удобное время для практик.
  • Если хотите индивидуальный график — обсудим и реализуем.
  • Личный куратор будет на связи, чтобы ответить на вопросы, проконсультировать и мотивировать придерживаться сроков сдачи экзаменов.
  • Всем, кто боится потерять мотивацию и не закончить обучение, предложим общение с профессиональным коучем.
  • отредактировать или создать с нуля резюме;
  • подготовиться к техническим интервью;
  • подготовиться к конкурсу на понравившуюся вакансию;
  • устроиться на работу в Cisco по специальной программе. Наши студенты, которые уже работают там: жмите на #НашиВCisco Вконтакте, #НашиВCisco Facebook.

Чтобы учиться на курсах Cisco, Linux LPI, кибербезопасность, DevOps / DevNet, Python, подайте заявку или получите бесплатную консультацию.

Источник

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