All in peace ?
A little about coding
In this post I will demonstrate a little more about the SQL Server HASHBYTES function, which allows working with HASH-based cryptographic functions, where once encoded, it is not possible to get the original string again. If you want to learn more about encryption using the Base64 algorithm, which lets you encode and decode a string, go here.
The encoded string is validated by comparison, re-encoding the string to be tested and comparing the newly generated HASH with the original HASH. If the HASHs match, the tested string is confirmed as true.
This form of validation is considered safer than cryptography, as the complexity of encoding is much greater and makes hacking attacks difficult to break the encoded string. Although it is a very safe method, it has been proven that there are collisions, which are two or more strings that generate the same HASH, causing its safety to be broken by a string that is different from the original. As we increase the number of bits in our encryption, the more secure it gets and the more processing it takes to crack it (and more space to store HASH's)
Algorithm encryption level:
- 128 bits (16 bytes): MD2, MD4, and MD5
- 160 bits (20 bytes): SHA and SHA1
- 256 bits (32 bytes): SHA2_256 (SQL Server 2012 onwards)
- 512 bits (64 bytes): SHA2_512 (SQL Server 2012 onwards)
The HASHBYTES Function
Let's put into practice all that has been said above. Get to work! The HASHBYTES system function returns the hash of MD2, MD4, MD5, SHA1, or SHA2 (SQL Server 2012 onwards) from your SQL Server entry.
Example 1 - SHA1:
-- Retorno: 0x18CAA0AA39B10AE2AB9CFF8DAEC38619F64CF38D
SELECT HASHBYTES('SHA1', 'Dirceu Resende')
Example 2 - MD5:
-- Retorno: 0x48699133C5F20DB0CAB52CC203CFFED1
SELECT HASHBYTES('MD5', 'Dirceu Resende')
Example 3 - SHA1 with data from a table:
IF(OBJECT_ID('tempdb..#Teste') IS NOT NULL) DROP TABLE #Teste
CREATE TABLE #Teste (Ds_Texto nvarchar(50))
INSERT #Teste VALUES ('Dirceu Resende'), ('SQL Server');
SELECT HASHBYTES('SHA1', Ds_Texto) FROM #Teste
To the next!