TSQL DECRYPTBYPASSPHRASE如何更改日期

时间:2018-03-14 09:48:53

标签: sql tsql

我有以下查询来检查到期日期:

SET DATEFORMAT DMY
DECLARE @LICENCE_EXPIRY_DATE AS DATETIME
SET @LICENCE_EXPIRY_DATE =
(SELECT
CAST(CAST(DecryptByPassPhrase('PassPhrase', EncryptedExpiryDate) AS 
VARCHAR(16)) AS DATETIME)
FROM TableA
WHERE ID = 1)
SELECT  CAST(CASE when getdate() > @LICENCE_EXPIRY_DATE THEN 1 ELSE 0 END AS 
INT) AS Expired

表定义:

CREATE TABLE [dbo].[TableA](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [LicenteExpiryDate] [datetime] NULL,
    [EncryptedExpiryDate] [varbinary](256) NULL,
    [UserCreated] [nvarchar](100) NULL,
    [DateCreated] [datetime] NULL,
    [UserUpdated] [nvarchar](100) NULL,
    [DateUpdated] [datetime] NULL)

目前的到期日是2018年3月9日。我需要将其更新至2019年3月9日。

说实话,我从来没有碰到它,我不知道该怎么做。我会尝试,但如果有人能告诉我正确的方法,我将非常感激。

感谢。

1 个答案:

答案 0 :(得分:0)

这是一个简单的脚本,用于显示密码短语的加密方式:

DECLARE @Date DATE = '2018-03-08'

SELECT @Date
-- Result: 2018-03-08 (date format)

DECLARE @DateAsText VARCHAR(100) = CONVERT(VARCHAR(200), @Date)

SELECT @DateAsText
-- Result: 2018-03-08 (text format)

DECLARE @EncryptedDate VARBINARY(256) = ENCRYPTBYPASSPHRASE('passphrase', @DateAsText)

SELECT @EncryptedDate
-- Result: 0x01000000DE109FF181873328E82F91352D1E0ACB9680211F9CC1180B3D2AA515C4A43776 (varbinary format)


SELECT
    Stored = @EncryptedDate, -- Varbinary format
    DecryptedText = 
        CONVERT(VARCHAR(200), 
            DECRYPTBYPASSPHRASE('passphrase', @EncryptedDate)),
    DecryptedDate = 
        CONVERT(DATE, 
            CONVERT(VARCHAR(200), 
                DECRYPTBYPASSPHRASE('passphrase', @EncryptedDate)))

/*
Result (pivoted for easier read):

Stored: 0x0100000085C2A665CFA891558AE752021D1D8F0238D597117E7B871E71737FD8F6C8BFFB
DecryptedText: 2018-03-08
DecryptedDate: 2018-03-08
*/

要更改您的值,您可以执行以下操作(小心保持事务处于打开状态):

BEGIN TRANSACTION

UPDATE T SET
    EncryptedExpiryDate = 
        ENCRYPTBYPASSPHRASE('PassPhrase', 
            CONVERT(VARCHAR(200),
                CONVERT(DATE, '2019-08-09')))
FROM
    TableA AS T
WHERE
    T.ID = 1

-- You can check updated value (without commiting) with 
SELECT
    EncryptedExpiryDate,
    DecryptedDate = CAST(CAST(DecryptByPassPhrase('PassPhrase', EncryptedExpiryDate) AS VARCHAR(200)) AS DATETIME)
FROM
    TableA AS T
WHERE
    T.ID = 1

-- If it shows OK
COMMIT

-- If it doesn't
ROLLBACK

请注意,在将DATEDATETIME转换为VARCHAR时,有多种格式(yyyy-MM-dddd-MM-yyyy等)。格式将影响最终VARBINARY,因此请确保您使用正确的格式。