CREATE VIEW V_rand
As
Select C=unicode (CAST (Round (rand () *255,0) as tinyint)
Go
Create function F_jmstr
(
@str varchar (8000),
@type bit
)
Returns varchar (8000)
/*
* Parameter Description
*STR: The string to encrypt or the character that has been encrypted
*type: Operation type--0 Encryption--decryption
* Return Value Description
* When the operation type is encrypted (type--0): Returns the encrypted STR, which is the string stored in the database
* When the operation type is decrypted (TYPE--1): Returns the actual string, which is the original string after the encrypted string is decrypted
*/
As
Begin
DECLARE @re varchar (8000)--return value
Declare @c int--encrypted characters
DECLARE @i int
/*
* Encryption method is an original character xor or a random ASCII character
*/
If @type =0--encryption
Begin
Select @c=c, @re = ", @i=len (@str) from V_rand
While @i>0
Select @re =nchar (Unicode (substring (@str, @i,1)) ^@c^@i) [email protected]
, @[email protected]
Set @[email Protected]+nchar (@c)
End
else--decryption
Begin
Select @i=len (@str) -1,@c=unicode (substring (@str, @i+1,1)), @re = "
While @i>0
Select @re =nchar (Unicode (substring (@str, @i,1)) ^@c^@i) [email protected], @[email protected]
End
Return (@re)
End
Go
--Test
DECLARE @tempstr varchar (20)
Set @tempstr = ' 1 2 3aA '
Select ' Original value: ', @tempstr
Select ' Encrypted: ', Dbo.f_jmstr (@tempstr, 0)
Select ' Decrypted: ', Dbo.f_jmstr (dbo.f_jmstr (@tempstr, 0), 1)
--Output results
/*
Original value: 1 2 3aA
After encryption: __0 ' 15 ' 17__°{1
After decryption: 1 2 3aA
*/
Encrypt and decrypt a string