I have a SQL Server table tbl
with the schema
ID int,
LongText varbinary(max)
And I have the following functions to encrypt/decrypt the LongText
when inserting/fetching records.
For encrypting:
CREATE FUNCTION Encrypt
(
@ValueToEncrypt varchar(max)
)
RETURNS varbinary(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varbinary(max)
SET @Result = EncryptByKey(Key_GUID('My_Encryption_Symmetric_Key'), @ValueToEncrypt)
-- Return the result of the function
RETURN @Result
END
For decrypting:
CREATE FUNCTION Decrypt
(
@ValueToDecrypt varbinary(max)
)
RETURNS varchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varchar(max)
SET @Result = DecryptByKey(@ValueToDecrypt)
-- Return the result of the function
RETURN @Result
END
While inserting and fetching records, I am calling these functions as follows:
For inserting:
--Open symmetric keys
INSERT INTO tbl
VALUES (1, Encrypt('some long text here'))
For fetching:
--Open symmetric keys
SELECT ID, Decrypt(LongText)
FROM tbl
Now when I try to insert values in the table, for larger values I get an error
String or binary data would be truncated.
The statement has been terminated.
This happens for larger values which is understandable by the message. I read somewhere that EncryptByKey
/DecryptByKey
have a limit of 8000 bytes. Is it what is causing this problem? If Yes, is there any workaround or alternative approach that I can use? If No, then what am I doing wrong here? For the life of me, I am not able to figure out what the problem is.