Encrypt and decrypt a string

Source: Internet
Author: User
Tags decrypt

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.