Skip to content
Sign upLog in
This post is read-only. Explore Repls and connect with other creators on Community.View Community
The info in this post might be out of date, check out our docs instead. View docs
9

How to hashes

CodeLongAndPros
CodeLongAndPros

How to use hashes in Python

Today we're going to talk about how use use the MD5 (Message Direct 5) and SHA-256
But first we need to address a problem.

What are hashes anyway?

A hash is a function that produces a fixed length number (Usually Hex) based on a input.

Some examples (MD5):

"cat" --> md5sum --> d077f244def8a70e5ea758bd8352fcd8

"dog" --> md5sum --> 06d80eb0c50b49a509b49f2424e8c805

"cats" --> md5sum --> 0832c1202da8d382318e329a7c133ea0

"dogs" --> md5sum --> d28d2d3560fa76f0dbb1a452f8c38169

As you can see, cat and cats have totally different sums

Try it out

If you have a Linux system, to calculate the MD5 sum of a string, run this:

echo -n STRING | MD5sum

Using MD5 hashes in Python

Python comes with built-in support for SHA and MD5.

To access it, import it:

import hashlib

You can then create a hash object like this:

import hashlib checksum = hashlib.md5("Hello World".encode())

You have to use the .encode(), because MD5 works on a series of bytes.

If you don't you'll get this error:

TypeError: Unicode-objects must be encoded before hashing

To get the actual hash of the string, call .hexdigest() on the object:

import hashlib checksum = hashlib.md5("Hello World!".encode()) print(checksum.hexdigest())

A quicker method:

import hashlib print(hashlib.md5("Hello World!".encode()).hexdigest())

A couple of notes on MD5

MD5 has been cracked.

You should not use it for passwords because of collisions.

What is a collision?

Since MD5 has a fixed hash length (32 bits), there are a finite number of hashes.
A visual is the best option:

good --> md5sum - | | | | ---> 05aa266ba089be6b42738236dc96665d | | evil --> md5sum - |

If you hash your passwords, a cracker could gain access by colliding two hashes.

How to apply MD5 in your programs

I use MD5 for checksums in P2P

This is to verify that the transferred file is identical to the host's file, because MD5 works on bytes too.

Using SHA-256

To use SHA256 in your programs, refer to the example above, just replace md5 with sha256

SHA256 has not been collided, as of 2020, so you can use it to hash your passwords.
I used it in Coyote OS
It is so much more secure than storing passwords in plaintext.

Additional Reading

All I've given is a brief overview.

3 years ago

Voters

Comments

TopNew
2
Codemonkey51
Codemonkey51

Cool I once made a sort of hash password module on github here: https://github.com/Codemonkey51/secure-python-password-engine

3 years ago
1
CodeLongAndPros
CodeLongAndPros

@Codemonkey51
I made a clone of getPass here:

https://repl.it/@CodeLongAndPros/passwd

3 years ago
1
Codemonkey51
Codemonkey51

I'll make sure to credit you

@CodeLongAndPros

3 years ago
Load more