Simple encryption with MSSQL

ApocDen 0 Tallied Votes 313 Views Share

This is a User Defined Function to perform simple encryption on an input string. This is performed by transposing the ASCII value of each character in the string by the increment value (@increment in the parameter list)

Pass the function the string you wish encrypted and the increment value, which is normally 128 or 256

/*Encryption function*/
CREATE FUNCTION dbo.udfEncryptString (@input_str VARCHAR(100), @increment INT)
RETURNS NVARCHAR(100) WITH ENCRYPTION AS
BEGIN
    
    DECLARE @encrypted_str NVARCHAR(100)
    DECLARE @index INT
    
    SET @index = 1
    SET @encrypted_str = ''
    
	/*
	loop as long as @index is shorter than the
	length of the input string
	*/
    WHILE @index <= LEN(@input_str)
		BEGIN
			--transpose the ASCII value of each character by @increment
			SET @encrypted_str = @encrypted_str + NCHAR(ASCII(SUBSTRING(@input_str, @index, 1)) + @increment + @index - 1)
			--incement the current index
			SET @index = @index + 1
		END
    
    RETURN @encrypted_str
END
GO

/*Decryption function*/
CREATE FUNCTION dbo.udfDecryptString (@input_str NVARCHAR(100), @increment INT)
RETURNS VARCHAR(100) WITH ENCRYPTION AS
BEGIN
	DECLARE @decrypted_str VARCHAR(100)
	DECLARE @index INT

	SET @index = 1
	SET @decrypted_str = ''

	WHILE @index <= LEN(@input_str)
		BEGIN
			SET @decrypted_str = @decrypted_str +  CHAR(UNICODE(SUBSTRING(@input_str, @index, 1)) -  @increment - @index + 1)
			SET @index = @index + 1
		END

	RETURN @decrypted_str
END
GO