在sqlserver中,可以通过内置函数EncryptByPassPhrase对字符串进行加密,通过内置函数DecryptByPassPhrase对加密后的密文进行解密。
代码如下:
declare @UserName nvarchar(100)='张三' declare @Encrypt varbinary(max)=null --加密 select @Encrypt=ENCRYPTBYPASSPHRASE('12312#$#2sj',@UserName) select @Encrypt as EncryptText --解密 select CONVERT(nvarchar,DECRYPTBYPASSPHRASE('12312#$#2sj',@Encrypt)) as DecryptText
EncryptByPassPhrase与DecryptByPassPhrase在配对的时候,一定要记住加密时字符串的类型,nvarchar和varchar是不一样的。加密时为nvarchar,解密时转为varchar,解密后的字符串是乱码。加密和解密时,对应的字符串类型一定要一样,同是nvarchar,或同是varchar。为何?编码不一样!
如下代码:
declare @UserName nvarchar(100)='张三' declare @Encrypt varbinary(max)=null --加密 select @Encrypt=ENCRYPTBYPASSPHRASE('12312#$#2sj',@UserName) select @Encrypt as EncryptText --解密 select CONVERT(varchar,DECRYPTBYPASSPHRASE('12312#$#2sj',@Encrypt)) as DecryptText
@UserName的累心是nvarchar,而以varchar类型作为解密的文本类型,则会产生如下错误结果:
参考资料:https://docs.microsoft.com/zh-cn/sql/t-sql/functions/encryptbypassphrase-transact-sql?redirectedfrom=MSDN&view=sql-server-ver15