Hello people,
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 validation of the encoded string occurs through comparison, re-encoding the string to be tested and comparing the newly generated HASH with the original HASH. If the HASH's match, the tested string is confirmed as true.
This form of validation is considered more secure than cryptography, since the complexity of the encoding is much greater and makes it difficult for hackers to break the encoded string. Although it is a very safe method, collisions have already been proven, which are two or more strings that generate the same HASH, causing your security to be broken by a string that is different from the original. As we increase the amount of bits in our encryption, the more secure it becomes and demands more processing to break 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:
1 2 |
-- Retorno: 0x18CAA0AA39B10AE2AB9CFF8DAEC38619F64CF38D SELECT HASHBYTES('SHA1', 'Dirceu Resende') |
Example 2 - MD5:
1 2 |
-- Retorno: 0x48699133C5F20DB0CAB52CC203CFFED1 SELECT HASHBYTES('MD5', 'Dirceu Resende') |
Example 3 - SHA1 with data from a table:
1 2 3 4 5 6 7 8 9 10 11 |
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 /* -- Retorno: 0xA76690CCD5AF74518E9C6218B4CBC6BA313C86E6 0xD983D8A96DAA8A7368438848B6D988FC4AA6659B */ |
To the next!