IF EXISTS (SELECT
						 *
					 FROM
						 sys.objects
					 WHERE
						object_id = OBJECT_ID(N'SENHA_SHA1') AND
						type IN ( N'P', N'PC' ))
	BEGIN
			DROP PROCEDURE SENHA_SHA1
	END

GO

CREATE PROCEDURE [dbo].[SENHA_SHA1] @USU INT = 0
WITH ENCRYPTION
AS
		--IF(OBJECT_ID('tempdb..#Teste') IS NOT NULL) DROP TABLE #Teste
		--CREATE TABLE #Teste (Ds_Texto nvarchar(50))
		DECLARE @CRYPTED AS VARCHAR(50)
		DECLARE @SALASANA AS INT
		DECLARE @TT AS INT
		DECLARE @X1 AS INT
		DECLARE @SANA AS INT
		DECLARE @G AS INT
		DECLARE @CC AS INT
		DECLARE @TEXTI AS VARCHAR(50)

		SET @TEXTI = (SELECT
										SENHA
									FROM
										GLB_USU
									WHERE
									 CD_USU = @USU)
		SET @CRYPTED ='';
		SET @CC = 1;
		SET @TT = LEN(@TEXTI);
		SET @SANA = 0;
		SET @SALASANA = 0;
		SET @G=0;

		WHILE @TT > 0
			BEGIN
					SET @SANA = ASCII(SUBSTRING (@TEXTI, @CC, 1));
					SET @CC = @CC + 1;
					SET @G=@G + 1;
					SET @X1=0;

					IF ( @G = 6 )
						BEGIN
								SET @G=0
						END

					SET @X1 = ( CASE WHEN @G = 0 THEN @SANA + ( @SALASANA - 2 )
											WHEN @G = 1 THEN @SANA - ( @SALASANA - 5 )
											WHEN @G = 2 THEN @SANA + ( @SALASANA - 4 )
											WHEN @G = 3 THEN @SANA - ( @SALASANA - 2 )
											WHEN @G = 4 THEN @SANA + ( @SALASANA - 3 )
											WHEN @G = 5 THEN @SANA - ( @SALASANA - 5 )
											END ) - @G;
					SET @CRYPTED = @CRYPTED + CONVERT(VARCHAR(5), CHAR(@X1))
					SET @TT=@TT - 1;
			END

		--INSERT dbo.#Teste VALUES (@CRYPTED)
		--PRINT N'SENHA ' + @CRYPTED
		SELECT
			SUBSTRING(master.dbo.FN_VARBINTOHEXSTR(HASHBYTES('SHA1', @CRYPTED)), 3, 40) AS SHA1

--SELECT * FROM #Teste
--SELECT TOP 1 SUBSTRING(MASTER.DBO.FN_VARBINTOHEXSTR(HASHBYTES('SHA1', RTRIM(LTRIM(Ds_Texto)))),3,40) AS SHA1 FROM #Teste;
GO 
