SQL Server中可以通過使用內置的加密函數和算法來進行數據加密和解密。以下是一些常用的方法:
示例代碼:
-- 加密數據
DECLARE @input VARCHAR(100) = 'Sensitive data'
DECLARE @password VARCHAR(100) = 'MySecretPassword'
DECLARE @encrypted VARBINARY(MAX)
SET @encrypted = ENCRYPTBYPASSPHRASE(@password, @input)
SELECT @encrypted AS EncryptedData
-- 解密數據
DECLARE @decrypted VARCHAR(100)
SET @decrypted = CAST(DECRYPTBYPASSPHRASE(@password, @encrypted) AS VARCHAR(100))
SELECT @decrypted AS DecryptedData
示例代碼:
-- 創建對稱密鑰
CREATE SYMMETRIC KEY MySymmetricKey
WITH ALGORITHM = AES_256
ENCRYPTION BY PASSWORD = 'MySecretPassword'
-- 加密數據
DECLARE @input VARCHAR(100) = 'Sensitive data'
DECLARE @encrypted VARBINARY(MAX)
OPEN SYMMETRIC KEY MySymmetricKey
SET @encrypted = ENCRYPTBYKEY(KEY_GUID('MySymmetricKey'), @input)
SELECT @encrypted AS EncryptedData
CLOSE SYMMETRIC KEY MySymmetricKey
-- 解密數據
DECLARE @decrypted VARCHAR(100)
OPEN SYMMETRIC KEY MySymmetricKey
SET @decrypted = CAST(DECRYPTBYKEY(@encrypted) AS VARCHAR(100))
SELECT @decrypted AS DecryptedData
CLOSE SYMMETRIC KEY MySymmetricKey
需要注意的是,加密和解密過程中需要保護好密鑰和密碼,確保數據的安全性。