Generate hash from string python

Create SHA-512 Hash of a string in Python

As a Python enthusiast, I’m always on the lookout for ways to enhance my coding skills and explore new techniques. One such technique that’s often used in data security and cryptographygraphy is creating a SHA-512 hash of a string. In this blog post, I’ll guide you through the process of generating a SHA-512 hash in Python. We’ll explore the fundamentals, understand the significance of this cryptographygraphic hash function, and learn how to implement it in our Python code. So, let’s dive into the world of SHA-512 hashes and strengthen our Python skills together!

Encryption and hashing have served as the foundation for new security modules, among other network security developments. One of the most used hash algorithms is the Secure Hash Algorithm(SHA) with a digest size of 512 bits, or SHA 512.

The SHA-512 hashing algorithm is currently one of the best and secured hashing algorithms after hashes like MD5 and SHA-1 has been broken down. Due to their complicated nature it is not well accepted and SHA-256 is a general standard, but the industry is slowing moving towards this hashing algorithm.

SHA 256 is a part of the SHA 2 family of algorithms, where SHA stands for Secure Hash Algorithm. It was a joint effort between the NSA and NIST to introduce a successor to the weaker SHA 1 family. SHA2 was published in 2001 and has been effective ever since.

The hash function generates the same output hash for the same input string. This means that, you can use this string to validate files or text or anything when you pass it across the network or even otherwise. SHA-512 can act as a stamp or for checking if the data is valid or not.

SHA-512 hasn’t gained the popularity that SHA-256 is experiencing or even other types of newer hashing algorithms when it comes to real-world use in blockchain. That being said it does have a few non-blockchain applications that are noteworthy.

The 512 in the name SHA-512 refers to the final hash digest value, meaning that regardless of the amount of plaintext or cleartext, the hash value will always be 512 bits.

Input String Output Hash
hi 150a14ed5bea6cc731cf86c41566ac427a8db48ef1b9fd626664b3bfbb99071fa4c922f33dde38719b8c8354e2b7ab9d77e0e67fc12843920a712e73d558e197
debugpointer 7e2dd654680000d5e27bf67e5a2c440d122da180a7ee4f1dd792a28d17c8a2d34fafa7f9f6e5f837607d41521de42f628e8fa48c0be8a86953d9bc20006ca1fc
computer science is amazing! I love it. d46bc2b8b0e30ee6f2bfe42826a01d550451223e36d8ea73e46f283eeed3514480b16681ebb9ad8d72c7f9247b5711e5f0797578200afe8229abf86b6ade79cd

SHA-512 hash of a String in Python

SHA-512 hash can be created using the python’s default module hashlib . There are many more hash functions defined in the hashlib library.

Читайте также:  Image source with css

The process of creating an SHA-512 hash in python is very simple. First import hashlib, then encode your string that you want to hash i.e., converts the string into the byte equivalent using encode(), then pass it through the hashlib.sha512() function. We print the hexdigest value of the hash m , which is the hexadecimal equivalent encoded string.

import hashlib text = 'Hello!'  m = hashlib.sha512(text.encode('UTF-8')) print(m.hexdigest()) 
3a928aa2cc3bf291a4657d1b51e0e087dfb1dea060c89d20776b8943d24e712ea65778fe608ddaee0a191bc6680483ad12be1f357389a2380f660db246be5844 

The value you see here 3a928aa2cc3bf291a4657d1b51e0e087dfb1dea060c89d20776b8943d24e712ea65778fe608ddaee0a191bc6680483ad12be1f357389a2380f660db246be5844 is the SHA-512 hash of the string Hello! .

The functions used in the above code-

  • encode() : Converts the string into bytes to be acceptable by hash function.
  • hexdigest() : Returns the encoded data in hexadecimal format.

You can also update the value of the string and check it as well if needed. This can be used to strengthen the hash logic in your workflow where you can append strings in certain order and see if your hash matched the source hash.

import hashlib text = 'Hello!'  m = hashlib.sha512() print(m.hexdigest()) m.update(b"Have Fun!") print(m.hexdigest()) m.update(text.encode('UTF-8')) print(m.hexdigest()) 
58858becf3fbc2d744c3c34f8c66ffcf21a894cf8641bb14c4bb362ef85a1df4f769ebf6c0ff3b53e37731244ff2c3f6ef88e6d8a6de515e621088d095fa5f7c 

As you see, the SHA-512 hash of a string using Python is as simple as this code.

The above code just produced SHA512 hash of the string alone, but, to strengthen the security you can also generate SHA512 hash with salt as well.

I’m glad that you found the content useful. And there you have it! We’ve successfully explored the process of creating a SHA-512 hash of a string using Python. I hope you found this journey insightful and empowering. As Python developers, it’s essential to grasp concepts like cryptographygraphic hashing to ensure data integrity and security in our applications. Now armed with the knowledge and understanding of SHA-512 hashes, you can incorporate this powerful technique into your own projects. Keep exploring, keep coding, and keep harnessing the full potential of Python! Happy Coding.

Источник

Hashing Strings with Python

A hash function is a function that takes input of a variable length sequence of bytes and converts it to a fixed length sequence. It is a one way function. This means if f is the hashing function, calculating f(x) is pretty fast and simple, but trying to obtain x again will take years. The value returned by a hash function is often called a hash, message digest, hash value, or checksum. Most of the time a hash function will produce unique output for a given input. However depending on the algorithm, there is a possibility to find a collision due to the mathematical theory behind these functions.

Читайте также:  What is hash function in php

Now suppose you want to hash the string «Hello Word» with the SHA1 Function, the result is 0a4d55a8d778e5022fab701977c5d840bbc486d0 .

hash2

Hash functions are used inside some cryptographic algorithms, in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more. As a Python programmer you may need these functions to check for duplicate data or files, to check data integrity when you transmit information over a network, to securely store passwords in databases, or maybe some work related to cryptography.

I want to make clear that hash functions are not a cryptographic protocol, they do not encrypt or decrypt information, but they are a fundamental part of many cryptographic protocols and tools.

Some of the most used hash functions are:

  • MD5: Message digest algorithm producing a 128 bit hash value. This is widely used to check data integrity. It is not suitable for use in other fields due to the security vulnerabilities of MD5.
  • SHA: Group of algorithms designed by the U.S’s NSA that are part of the U.S Federal Information processing standard. These algorithms are used widely in several cryptographic applications. The message length ranges from 160 bits to 512 bits.

The hashlib module, included in The Python Standard library is a module containing an interface to the most popular hashing algorithms. hashlib implements some of the algorithms, however if you have OpenSSL installed, hashlib is able to use this algorithms as well.

This code is made to work in Python 3.2 and above. If you want to run this examples in Python 2.x, just remove the algorithms_available and algorithms_guaranteed calls.

First, import the hashlib module:

[python]
import hashlib
[/python]

Now we use algorithms_available or algorithms_guaranteed to list the algorithms available.

[python]
print(hashlib.algorithms_available)
print(hashlib.algorithms_guaranteed)
[/python]

The algorithms_available method lists all the algorithms available in the system, including the ones available trough OpenSSl. In this case you may see duplicate names in the list. algorithms_guaranteed only lists the algorithms present in the module. md5, sha1, sha224, sha256, sha384, sha512 are always present.

MD5

[python]
import hashlib
hash_object = hashlib.md5(b’Hello World’)
print(hash_object.hexdigest())
[/python]

The code above takes the «Hello World» string and prints the HEX digest of that string. hexdigest returns a HEX string representing the hash, in case you need the sequence of bytes you should use digest instead.

It is important to note the «b» preceding the string literal, this converts the string to bytes, because the hashing function only takes a sequence of bytes as a parameter. In previous versions of the library, it used to take a string literal. So, if you need to take some input from the console, and hash this input, do not forget to encode the string in a sequence of bytes:

Читайте также:  Блокировка поля
[python]
import hashlib
mystring = input(‘Enter String to hash: ‘)
# Assumes the default UTF-8
hash_object = hashlib.md5(mystring.encode())
print(hash_object.hexdigest())
[/python]

SHA1

[python]
import hashlib
hash_object = hashlib.sha1(b’Hello World’)
hex_dig = hash_object.hexdigest()
print(hex_dig)
[/python]

SHA224

[python]
import hashlib
hash_object = hashlib.sha224(b’Hello World’)
hex_dig = hash_object.hexdigest()
print(hex_dig)
[/python]

SHA256

[python]
import hashlib
hash_object = hashlib.sha256(b’Hello World’)
hex_dig = hash_object.hexdigest()
print(hex_dig)
[/python]

SHA384

[python]
import hashlib
hash_object = hashlib.sha384(b’Hello World’)
hex_dig = hash_object.hexdigest()
print(hex_dig)
[/python]

SHA512

[python]
import hashlib
hash_object = hashlib.sha512(b’Hello World’)
hex_dig = hash_object.hexdigest()
print(hex_dig)
[/python]

Using OpenSSL Algorithms

Now suppose you need an algorithm provided by OpenSSL. Using algorithms_available , we can find the name of the algorithm you want to use. In this case, «DSA» is available on my computer. You can then use the new and update methods:

[python]
import hashlib
hash_object = hashlib.new(‘DSA’)
hash_object.update(b’Hello World’)
print(hash_object.hexdigest())
[/python]

Practical example: hashing passwords

In the following example we are hashing a password in order to store it in a database. In this example we are using a salt. A salt is a random sequence added to the password string before using the hash function. The salt is used in order to prevent dictionary attacks and rainbow tables attacks. However, if you are making real world applications and working with users’ passwords, make sure to be updated about the latest vulnerabilities in this field. I you want to find out more about secure passwords please refer to this article

def hash_password(password):
# uuid is used to generate a random number
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ‘:’ + salt

def check_password(hashed_password, user_password):
password, salt = hashed_password.split(‘:’)
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

new_pass = input(‘Please enter a password: ‘)
hashed_password = hash_password(new_pass)
print(‘The string to store in the db is: ‘ + hashed_password)
old_pass = input(‘Now please enter the password again to check: ‘)
if check_password(hashed_password, old_pass):
print(‘You entered the right password’)
else:
print(‘I am sorry but the password does not match’)
[/python]

def hash_password(password):
# uuid is used to generate a random number
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ‘:’ + salt

def check_password(hashed_password, user_password):
password, salt = hashed_password.split(‘:’)
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

new_pass = raw_input(‘Please enter a password: ‘)
hashed_password = hash_password(new_pass)
print(‘The string to store in the db is: ‘ + hashed_password)
old_pass = raw_input(‘Now please enter the password again to check: ‘)
if check_password(hashed_password, old_pass):
print(‘You entered the right password’)
else:
print(‘I am sorry but the password does not match’)
[/python]

Источник

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