Sara Diaz
Sara Diaz

Reputation: 73

"Simple" Decryption Not Working 100% of the times

I have two functions. An encryption function and a decryption function (see below). The decryption function doesn't work 100% of the time with specific words and I cannot figure out the reason why. Can someone help me figure this out? I am testing this two functions using the following select statements after the functions are in place.

select [dbo].[ufn_EncryptString]('Test1') --This string works
select [dbo].[ufn_DecryptString]('Ôæõ÷µ') 

select [dbo].[ufn_EncryptString]('diaz-mayo') --This string doesn't work 
select [dbo].[ufn_DecryptString]('äêãý±òçĀ÷')

You would think it has something to do with "-" but there are instances when is just a plain name with no spaces or special character and the string cannot be decrypted.

See functions below:

 CREATE FUNCTION [dbo].[ufn_EncryptString] ( @pClearString VARCHAR(100) )
    RETURNS NVARCHAR(100) AS
    BEGIN

    DECLARE @vEncryptedString NVARCHAR(100)
    DECLARE @vIdx INT
    DECLARE
 @vBaseIncrement INT

    SET @vIdx = 1
    SET @vBaseIncrement = 128
    SET @vEncryptedString = ''

    WHILE @vIdx <= LEN(@pClearString)
    BEGIN
        SET @vEncryptedString = @vEncryptedString + 
                                NCHAR(ASCII(SUBSTRING(@pClearString, @vIdx, 1)) +

      @vBaseIncrement + @vIdx - 1)
        SET @vIdx = @vIdx + 1
    END

    RETURN @vEncryptedString

END
GO


CREATE FUNCTION [dbo].[ufn_DecryptString] ( @pEncryptedString NVARCHAR(100) )
RETURNS VARCHAR(100) AS
BEGIN

DECLARE @vClearString VARCHAR(100)
DECLARE @vIdx INT
DECLARE @vBaseIncrement INT

SET @vIdx = 1
SET @vBaseIncrement = 128
SET @vClearString = ''

WHILE @vIdx <= LEN(@pEncryptedString)
BEGIN
    SET @vClearString = @vClearString + 

            CHAR(UNICODE(SUBSTRING(@pEncryptedString, @vIdx, 1)) - 

        @vBaseIncrement - @vIdx + 1)
    SET @vIdx = @vIdx + 1
END

RETURN @vClearString

END
GO

Upvotes: 2

Views: 355

Answers (1)

Michael Fredrickson
Michael Fredrickson

Reputation: 37388

I think your function works fine, your example is the issue.

select [dbo].[ufn_DecryptString]('äêãý±òçĀ÷')

Doesn't work... however the following works just fine:

select [dbo].[ufn_DecryptString](N'äêãý±òçĀ÷')

Notice the leading N on the string literal? Since your input parameter is actually a UNICODE string, you need to prefix the literal with N in order to prevent it from being cast to a ASCII string...

From MSDN:

Unicode constants are specified with a leading N: N'A Unicode string'.

Otherwise, when it is converted to ASCII, you're actually passing in äêãý±òçA÷... only the Ā character isn't represented in the CHAR literal, which is why your issue was intermittent.

Upvotes: 4

Related Questions