Linux password hash generator

Как: Сгенерировать Хэш Пароля в Linux и как узнать тип хэша

Сгенерировать Хэш Пароля в Linux

Linux хранить зашифрованные пароли пользователей, также как и другую информацию связанную с безопасностью, например сроки действия аккаунтов или паролей, в файле /etc/shadow .

Однажды у вас может возникнуть необходимость вручную отредактировать файл /etc/shadow для того, чтобы задать или изменить чей-то пароль.

В отличие от файла /etc/passwd , который могут читать все, файл /etc/shadow должен быть доступен для чтения ИСКЛЮЧИТЕЛЬНО пользователю ROOT.

Для этого вам придется сгенерировать хэш пароля в формате, который будет совмести с /etc/shadow .

Нет необходимости устанавливать дополнительные утилиты, так как это может быть легко сделано из командной строки в Linux с помощью Python.

Создать Хэш Пароля для /etc/shadow

Зашифрованные пароли в /etc/shadow хранятся в следующем формате:

$ID обозначает тип шифрования, $SALT — это случайная (до 16 символов) строка и $ENCRYPTED — хэш пароля.

Тип Хэша ID Длина Хэша
MD5 $1 22 символов
SHA-256 $5 43 символов
SHA-512 $6 86 символов

Используйте следующие команды из терминала в Linux для создания хэшированых паролей со случайной солью для /etc/shadow .

Создать MD5 Хэш пароля:

Создать SHA-256 Хэш пароля:

Создать SHA-512 Хэш пароля:

Надеюсь эти команды будут вам полезны.

Только не забудьте поменять MySecretPassword на ваш YourSecretPassword.

Как вы видите, это действительно очень легко генерировать хэши для /etc/shadow из командной строки в Linux с помощью Python.

В частности потому, что Python, по умолчанию, установлен в большинстве Linux дистрибутивах.

Узнать тип хэша

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

  • Длина ХЭШа (каждая хэш-функция имеет определенную выходную длину);
  • Используемый алфавит (есть ли английские буквы? числа 0-9 и A-F … возможно это hex? используются ли специальные символы?).

Step 1: Скачиваем последнюю версию (v1.1 на текущий момент)

Step 2: Запускаем скрипт и копируем интересующие нас ХЭШи

Добавить комментарий Отменить ответ

Для отправки комментария вам необходимо авторизоваться.

Источник

/etc/shadow – HowTo: Generate Password Hash in Linux

Linux stores users’ encrypted passwords, as well as other security information, such as account or password expiration values, in the /etc/shadow file.

Someday you may need to edit the /etc/shadow file manually to set or change ones password.

Unlike the /etc/passwd that is readable for everyone, the /etc/shadow file MUST be readable by the ROOT user only.

For this you would have to generate password hash in the format compatible with /etc/shadow .

Cool Tip: Want to create a USER with ROOT privileges? This can be very dangerous! But if you insist… Read more →

There is no need to install any additional tools as it can be easily done from the Linux command line using Python.

Generate Password Hash for /etc/shadow

The $ID indicates the type of encryption, the $SALT is a random (up to 16 characters) string and $ENCRYPTED is a password’s hash.

Hash Type ID Hash Length
MD5 $1 22 characters
SHA-256 $5 43 characters
SHA-512 $6 86 characters

Cool Tip: Got a hash but don’t know what type is it? Find out how to easily identify different hash types! Read more →

Use the below commands from the Linux shell to generate hashed password for /etc/shadow with the random salt.

Generate MD5 password hash:

Generate SHA-256 password hash:

Generate SHA-512 password hash:

Hope these commands will be helpful.

Just don’t forget to replace MySecretPassword with YourSecretPassword.

As you can see, it is really very easy to generate hashes for the /etc/shadow from the Linux command line using Python.

Particularly for the reason that the Python is installed by default on the most Linux distributions.

Источник

Генераторы паролей в Linux

Придумать одновременно красивый, сложный для взлома и легко запоминающийся пароль очень сложно. Например когда мне нужно ввести пароль для новой учетной записи, на ум приходят только элементарные или уже использованные варианты.

Читайте также:  Asrock m3a770de нет звука windows 10

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

Генераторы паролей для Linux

1. pwgen

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

Утилита pwgen довольно популярная, поэтому есть в официальных репозиториях большинства дистрибутивов. Для установки в Ubuntu наберите:

sudo apt install pwgen

При запуске pwgen без параметров будет сгенерирован целый список паролей. Просто выберите понравившийся вариант, и очистите терминал чтобы никто не подсмотрел что вы выбрали. Для запуска наберите:

Как только выберете пароль используйте команду clear чтобы очистить вывод. Если вы уверены что никто не смотрит можно заставить программу генерировать только один пароль:

Для создания полностью случайного пароля используйте опцию -s:

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

Если вас не устраивает стандартная длина пароля, ее можно изменить опцией -n, генерация паролей linux длиной в десять символов:

Опция -0 — позволяет не использовать цифры, а опция -B — не использовать символы которые можно спутать при печати, например: L и 1, 0 и O.

2. makepasswd

Утилита makepasswd работает аналогично pwgen, однако она не пытается создать пароли которые легко запомнить. Все пароли генерируются случайным образом с акцентом на безопасность.

Для установки в Ubuntu откройте терминал и выполните:

sudo apt install makepasswd

Для создания одного пароля введите:

Для генерации пяти паролей, с минимальным количеством символов 10, наберите:

makepasswd —count 5 —minchars 10

Вы также можете указать символы для генерации пароля. Это может быть полезно при создании пин-кодов. Например для получения четырехзначного пин-кода используйте:

makepasswd —string 1234567890 —chars 4

3. PasswordMaker

Программа Passwordmaker немного отличается от двух предыдущих. Она позволяет сгенерировать пароль linux на основе URL. Первоначально это было расширение для популярных браузеров Internet Explorer и Firefox и т д. Пакет passwordmaker-cli устанавливает консольную версию программы:

sudo apt install passwordmaker-cli

Для генерации пароля нужно указать url и мастер пароль. Утилита на основе этих данных создает уникальный пароль. Например:

passwordmaker —url losst.ru

В результате мы видим очень даже безопасный но не просто запоминаемый пароль. Если вы снова запустите программу с тем же url и мастер-паролем будет сгенерирован тот же пароль. Это означает что вы можете создать пароль для определенного сайта, который нет необходимости помнить, и не нужно нигде хранить. Перед тем, как сгенерировать этот пароль утилита попросит ввести мастер-пароль, который будет использоваться для генерации, поэтому это безопасно.

Всегда держите ваши пароли в надежном месте и не используйте очевидные варианты такие как password или qwerty.

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

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

7 комментариев

Себе почти всегда делаю пароли в консоли. Преимущество в том, что для этого мне не нужны никакие пакеты:
echo «mypassword» | md5sum
Чем длиннее (8 символов и более) наш «mypassword», тем безысходнее становится время его вскрытия:)
Если же возникнет опасение, что некий суперхакер возьмется за очень дОООООлгий многопоточный брутфорс моей длинной сигнатуры, то можно повторно вставить (уже ее) вместо исходного «mypassword». Приблизительное время взлома уже такой сигнатуры увеличится тогда в_несколько_порядков. При этом, у нас в запасе всегда будет изначальный пред-пароль «mypassword», по которому в консоли элементарно восстановить свой окончательный пароль в случаях его потери или «забытия»:)
p.s.
При попытках хака MD5-сигнатур никогда не будет никакой гарантии получения взломщиком нашего исходного пароля. Дело в том, что алгоритм вычисления сигнатур MD5 односторонний, поэтому хакер сможет получить лишь некоторые_возможные_варианты_пароля и то, затратив на взлом месяцы/годы/века/тысячелетия, как ему повезет:)

Мысль хорошая, пожалуй, возьму на вооружение, т.к. буковки проще запоминать, а пароль из них можно и на смарте сгенерить 😉 вот только изменю чутка, чтоб пароли можно было в открытом виде хранить:
echo «mypassword» | sha512sum | md5sum
или echo «mypassword» | sha512sum | head -c 33 && echo » или .
Взломщику останется только украсть файл с открытой частью паролей и перебрать пару сотен/тысяч комбинаций за пару-тройку часов для каждого пароля 😀

Читайте также:  Образ системы для восстановления linux

Источник

5 Useful Password Generators For Linux

Last updated November 20, 2019 By Shirish 3 Comments

I am not going to discuss why you need strong passwords. It is an open secret that strong passwords keep you relatively safer.

Generating strong passwords is something you can do on your own but putting all the combination of lower and upper cases, numbers, symbols can be a tiresome work.

But you need not worry. Linux has got you covered. You can either use a password manager in Linux for managing your passwords or simply user password generating tools.

Let me share some of the best password generators for Linux that will ease the task for you.

Generate secure password in Linux with these tools

Most of the password generation tool discussed here are command line tools. Don’t worry, I have not forgotten readers who prefer GUI. This list of password generators for Linux covers both kinds of tools.

1. Pwgen

Now while making truly random passwords is easy if you have the right tools, remembering them is hard. For e.g. my goto tool to generate a random password is pwgen. Let’s first install it –

generating random passwords with pwgen is easy, just run pwgen and it will generate a list of passwords for you.

While the above may same excessive, in today’s world, it’s probably a tool which is needed. The default though I find to be too simplistic for my usage and use-cases.

pwgen provides a number of options that you can view in the help menu.

But if you want to take my advice, use the command to generate passwords in the following manner.

Just try it and you will see the results. The only way you can learn the tool, any tool for that matter is to play with it.

Related Post: Learn how to change user password in Ubuntu and other Linux distributions.

2. xkcdpass

I am hopeful and sure that most technology users might have heard and used xkcd by now. As it states right on the top it is”A webcomic of romance, sarcasm, math, and language.”- xkcd.com .

Now somewhere in end 2010, early 2011, xkcd.com published a webcomic strip –

That webcomic became an inspiration for the tool called xkcdpass. It entered Debian somewhere in 2015 so anybody running Debian squeeze and later are surely to have it. It tells about itself in its package description only – ” A flexible and scriptable password generator which generates strong passphrases, inspired by XKCD 936:” – giving homage to the webcomic which inspired its creation.

To use it, after installation one has to simply do –

Now what xkcdpass does is it has 12 dictionaries based on aspell work. You can read about the 12 dictionaries slightly long readme here.

xkcdpass by default uses dict2 and dict6 of the wordlist for their unique characteristics. Now while I’m not in a position to share whether it’s good choice of words or not, it’s an option that could and should be used, it can be combined with output of pwgen to have unique passwords as well. You can also use the first letter of each word of the passphrase to get a password which is easily memorable as well.

Whether it will be successful or not solely relies on the attacker’s skill and determination. For the casual brute-force attacks as shared above, the combination might be somewhat of a better choice.

3. Diceware

Another contendor for good memorable password generation is diceware. It also can be installed as –

Now by default Diceware strings two or more words together to produce a string, something like this –

diceware comes with its own worldlist, it has two worldlists, one is plain english words and the other one comes from EFF. Those who don’t know EFF, it is an organization which works for individual privacy rights in digital domain among other things. So you can use it in two ways –

Читайте также:  Linux или windows платформа

and the one from eff:

There is an outstanding bug to have some more eff lists which would make the package even more relevant in this heightened security scenario. Hopefully, it will be fixed soon so we have a better package.

4. Revelation

On the GUI side, the first tool I would share is Revelation. First install the package.

Revelation is an oldish tool as it entered Debian since 2004 but has kept up with changes. Revelation describes itself as a GNOME 2 password manager but it is more than that. First either run it from either the command-line interface (CLI) or take the icon from the menu. You would usually find it in Menu > Accessories > Revelation . Just drag the icon from the menu to either the desktop or the top/bottom or side panel whichever is good for you, double-click to see the interface. For terminal users, do it as

Once you do it in either of the above ways, you need to go to View > Password Generator to see the Password Generator in action –

Once you click on that it will give you random passwords depending upon the length of the letters needed in the password and whether you need punctuation or not as can be seen in the picture below.

Now this is good or bad enough depending on what your needs are.

5. KeepassX

The tool has been in Debian for over a decade as well, was introduced in 2006. You can install it in Debian and other downstream or/and derivative distributions by doing:

Keepassx describes itself as a Cross Platform Password Manager but its much more than that. It puts your password in a database (like Mozilla Firefox does with sqlite3) and also encrypts it either using AES or Twofish algorithims (similar to Mozilla Firefox as well.)

Now in Keepassx, there is no easy way to get to the password generator. The way is first make a database, then make a group and then make an entry, when making the entry you will see a small button say Gen. If you see the third line Repeat, you see blank space, the button next to the blnak space

Once you click on Gen, another window appears

The Generate button generates passwords for you depending on what options you choose. Just copy the password on your favorite text-editor to know what password was generated.

The biggest difference between the command-line tools (CLI) and the Graphical User Interface (GUI) tools is the CLI tools can be used in scripts. So they can be used for both users and web hosters who might want to offer password generation as a service along with other services.

Best practices and tips for having strong passwords and security

  • No one tool or no one strategy is the answer to all kinds of attacks and there are many different types of attacks.
  • If possible try to find services which don’t put a cookie or a password. Such services are rare but they are there. A good example would perhaps be duckduckgo.com
  • One of the most important rule, don’t use the same password to all the sites. That is like having all locks in real life using the same key. You can very well understand the consequences of that.
  • One of the most common ways that an attacker can attack you is by owning your ADSL modem/router. At the very least don’t leave it at ‘admin/admin’ for both user and password. Ideally, you should change both but if you don’t want to change user:admin at least change the password there.
  • Lastly, read and research on your own – Being a web user, it is imperative that you read and research on your own. There are all kinds of tools and techniques being born every day, While it is next to impossible to learn and keep watch on all that is being claimed and shared, at least some barest knowledge is needed to survive in this web world.

Hope these password generation Linux tools and the tips helps you to be more secure. Have a safe time on the web.

Like what you read? Please share it with others.

Источник

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