SQL Server HashBytes - sql-server

Can you unhash a value that you have stored in the DB?
So if I generate and store a value like this
SELECT HashBytes('MD5', 'HelloWorld')
Can I use a function to unhash it so that I can get the original value backout?
Thanks,
S

Unfortunately not. If you are trying to check if a password or pass phrase is correct, you would only be able to encrypt what you've received, and then compare the two results. If they differ, then obviously the wrong information has been passed in.

No. Cryptographic hashes are by definition one way.

Related

Why does ISNUMERIC() state a Zip Code, which is a varchar data type, as numeric in SQL server?

From my understanding, and I am probably wrong here, but doesn't the ISNUMERIC() return a 1 if whatever we are looking at is a numeric data type? And since most zip codes are saved as varchar data types, shouldn't it then return a 0? I looked up the documentation and that's what it says there to me, what am I missing here? I get zip codes are numbers, but because they are saved as a string shouldn't that make a difference? Thanks in advance.
ISNUMERIC() is specifically to look at strings, not at things already stored as numbers.
However, I don't recommend using it. For instance, '3.1e5' is considered numeric.
Instead, use try_convert():
try_convert(int, zip)
This returns NULL if the column cannot be converted.

HASHBYTES 'SHA1' return value that differ to standard SHA1 implementation

I am computing HASH value of each row in a table (for diffing purpose), after implementing the algorithm I am testing the results.
Results are consistent and algorithm somewhat seems to work, but testing it step by step I found a strange result.
The script:
SELECT HASHBYTES('SHA1', (SELECT INNERTBL.VALUT FOR XML RAW)) as KHASH
FROM ACLING AS INNERTBL
Should perform the SHA1 calculation on the table key, but when I perform the same calculation with external tool I get different results:
In fact when I perform SHA1('<row VALUT="A"/>') with external tool (tool here: https://emn178.github.io/online-tools/sha1.html) I get a different result:
So my question is, there is something wrong with my logic or simply SQL Server use some non standard SHA1 "parametrization"? (I have suspect about the use of a, may be standard but particular, padding scheme)
Example in fiddler: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=efa4e0ba11c112f54e36afb5d54d2cce
SELECT HASHBYTES('SHA1','<row VALUT="A"/>'), --- you are testing this
HASHBYTES('SHA1',N'<row VALUT="A"/>') -- ..but for xml returns Nvarchar
It is important to remember that you get the same result only if the string are binary the same. For example if the two strings uses different characterset they will have different HASH value. For more details please check thsi out https://security.stackexchange.com/questions/18290/is-sha-1-hash-always-the-same

Snowflake builtin masking function

I want to mask certain data either by obfuscation or addition of a masking character.
Using traditional rpad and lpad plus replacing leading digits all have undesired outputs. SQL Server 2016 has a built in data masking function.
See mockup code:
Select mask(ssn,7,4, 'X') from dual;
input 111-11-1234
output: 111-11-XXXX
None.
Not sure what the "undesired outputs" are using rpad and lpad functions, but you could always create a UDF that gives you the correct reformatting of your string. I believe that this works for what you are looking for:
SELECT RPAD(LEFT($1,7),LENGTH($1),'X') FROM (VALUES ('123-44-5678'));
AFAIK Currently there is no such function in Snowflake to mask data.
But this article explains how to use roles and a mapping table to obfuscate PII data.

how to Hash an already existing password?

After testing and ensuring my Send_email function authenticates successfully using the hardcoded user and password in the SQL Table, I am now trying to Hash the password.
the way my columns are set up is something like this:
variable | value
password | someP#ssword
the columns are varchar both, with the value column being 1000 length (is that too much? i set it to that much cause i read that sha 512 requires a lot of length or something, and seen examples using 1000 at least so went with that)
I am using this query to hash,
INSERT INTO [dbo].[Table] (value)
VALUES(HASHBYTES('SHA2_512', 'someP#ssword'))
but it generates a nonbinary hash, which i am suspecting is why i am receiving this error of email authentication failed because it probably cant decipher the nonbinary password characters. but the problem is i have other values in the value column, so i can't convert the whole column to varbinary.
so is there a way to hash the password that is hardcoded or i have to insert it as hash? or is there a way i can convert just that particular field/cell without having to alter the rest of the design of the value column so it wont affect other values in there as well? or am i supposed to create a completely separate column for password and set it to binary?
EDIT: I have to pass the password in this email function call for authentication:
Send-EMail -EmailFrom $From_Email -SendTo $To_Email -Body $Email_Body -Subject $Job_Success_Email_Subject -Username $SmtpUser -Password $SmtpPassword
but Von in the comment said i can't pass the hashed password in there as credential. then that means i have to keep it nonhashed in the table? i thought hashing would work perfectly in this situation...
It looks like you have been confused by the irrelevant discussion in the comments above.
First of all: hashed password would not work in your Send-EMail function as the function has no way of "unhashing" said password. Read this introduction to Hashing vs Encryption.
If you want to secure your password and be able to retrieve original value you will need to encrypt it. The topic of encryption is quite large and way outside the scope of what can be written in SO. I will provide a few links for you to read:
http://www.manjuke.com/2018/03/data-encryption-in-sql-server-using-t.html
https://learn.microsoft.com/en-us/sql/relational-databases/security/encryption/encrypt-a-column-of-data?view=sql-server-2017
https://learn.microsoft.com/en-us/sql/relational-databases/security/encryption/sql-server-and-database-encryption-keys-database-engine?view=sql-server-2017
Encryption by pass phrase would be the simplest to implement but also weakest as anyone reading the code of an SP will find out the pass phrase and therefore can decrypt data. Note that pass phrase itself can be passed into ENCRYPTBYPASSPHRASE as a parameter, allowing you to store it (securely) elsewhere outside the database i.e. you don't have to hard code in your SP code. You will need to implement pass phrase storage method yourself if you decide to go this way.
Encryption using keys and certificates offers a very secure method but requires some time to set-up in addition to very carefully backing up your keys. If you loose your keys your data is gone i.e. you can never decrypt it.
As far as storing binary data in varchar column goes - easy, here is an example:
DECLARE #BinValue VARBINARY( 500 ) = HASHBYTES('SHA2_512', 'someP#ssword')
DECLARE #StringBinValue VARCHAR( 500 ) = CONVERT( VARCHAR( 500 ), #BinValue, 1 )
SELECT #BinValue, #StringBinValue, CONVERT( VARBINARY( 500 ), #StringBinValue, 1 ) AS BackToString
I have used your original HASHBYTES function as an example but you will need to change it to an encryption function.
Hope this clarifies things for you.

How do I store a signature block, including formatting, in a Sql server table?

I've been assigned the task of creating a table that stores an email signature for each username. The question is, how should I store the signature block? I could use a regular varchar type, but then how do I store the formatting metadata?
Any ideas or suggestions would be welcome.
Thanks!
Another idea I had was that you could design a specific email signature template, and then let people specify fields, such as Username, quote, avatar, alignment etc, and then have them modify their signature in a "signature editor". This way you could just store the "data" and not the rendering. so you could store something like follows:
<signature>
<username>chama</username>
<avatar href="http://url to my image"/>
<quote>A bird in the hand is not in the nest</quote>
</signature>
and it could look something like:
Chama
A bird in the hand is not in the nest
use varchar(max), or whatever length limit is appropriate.
otherwise, the only real concern is that you might want to make sure the html is html-encoded before you stick it in the database. (i.e., replace < with <, etc.) Not sure what you're using, but some tools have a setting so you don't have to do it manually.
other things you can do besides / in addition to html-encoding
1) restrict the formatting tags to some pre-defined set (i.e., search/replace tags you don't want before doing the insert. You can manage this in your db stored procedure, or better yet, in your front-end (if you have control over that).
2) disqualify attempts to insert data if they include certain tags (like '<script>', etc.)
HTML, RTF, XML. The stanard choices are multiple.
Note: "email signature" is NOT "digital signature". The term digital signature has a specific meaning and means a SIGNATURE to make sure - for email - it comes from th real sender and has not been tampered with.
I'd suggest going with your initial thought -- varchar(max). This will allow you to store signatures that are ASCII based. This includes plaintext, RTF or HTML signatures.
If users want to embed images (i.e. not a link to an image), then you'd have to determine a way for the caller to convert those images to Base64 or other before storing and after reading from your table.
Based on what I'm finding, you have basically two options:
1) Convert your formatted signature data to Binary and store it as a BLOB.
2) Instead of saving the signature itself in the DB, save them as files somewhere and store a reference to that file location in the DB.

Resources