Skip to content
Blog cá nhân của PhongTV

Blog cá nhân của PhongTV

  • Home
  • About
  • Skills
  • Resume
  • Contact
  • Bài viết

How to get the SHA1 hash of a string in SQL Server

pbk14 Tháng 8, 202414 Tháng 8, 2024 No Comments

To get SHA1 hash, SQL Server provides HASHBYTE function:

SELECT HASHBYTES('SHA1', 'abc123') -- Output in HEX format: 0x6367C48DD193D56EA7B0BAAD25B19455E529F5EE

To convert HEX to string, we need to use CONVERT:

SELECT CONVERT(NVARCHAR(40), HASHBYTES('SHA1', 'abc123'), 2) -- Output is 6367C48DD193D56EA7B0BAAD25B19455E529F5EE

We need to use 40 as parametter for NVARCHAR because the length of SHA1 is 40, otherwise the output will be cut.

The last parametter of CONVERT is 2, you can read Microsoft’s documentation here: https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms187928(v=sql.105)?redirectedfrom=MSDN

ValueOutput
0 (default)Translates ASCII characters to binary bytes or binary bytes to ASCII characters. Each character or byte is converted 1:1.If the data_type is a binary type, the characters 0x are added to the left of the result.
1, 2If the data_type is a binary type, the expression must be a character expression. The expression must be composed of an even number of hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, a, b, c, d, e, f). If the style is set to 1 the characters 0x must be the first two characters in the expression. If the expression contains an odd number of characters or if any of the characters are invalid an error is raised.If the length of the converted expression is greater than the length of the data_type the result will be right truncated.Fixed length data_types that are larger then the converted result will have zeros added to the right of the result.If the data_type is a character type, the expression must be a binary expression. Each binary character is converted into two hexadecimal characters. If the length of the converted expression is greater than the data_type length it will be right truncated.If the data_type is a fix sized character type and the length of the converted result is less than its length of the data_type; spaces are added to the right of the converted expression to maintain an even number of hexadecimal digits.The characters 0x will be added to the left of the converted result for style 1.

Điều hướng bài viết

Previous: How to fix error “Uncaught TypeError: ftp_fget(): Argument #1 ($ftp) must be of type FTP\Connection, null given in class-wp-filesystem-ftpext.php” in WordPress

Để lại một bình luận Hủy

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Proudly powered by WordPress | Theme: Smart Portfolio by Code Work Web.
Contact Us

    This form is powered by: Sticky Floating Forms Lite