Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to backup Symmetric Key in SQL Server?

I use the next code to create SQL Encryption keys

CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<Pass>'
CREATE CERTIFICATE MyEncryptCert WITH SUBJECT = 'Descryption', EXPIRY_DATE = '2115-1-1'
CREATE SYMMETRIC KEY MySymmetricKey WITH ALGORITHM = AES_256 ENCRYPTION BY CERTIFICATE MyEncryptCert

How I encrypt data

OPEN SYMMETRIC KEY MySymmetricKey DECRYPTION BY CERTIFICATE MyEncryptCert
SET @Result = ENCRYPTBYKEY(KEY_GUID('MySymmetricKey'), '<String to encrypt>')
CLOSE SYMMETRIC KEY MySymmetricKey

I am able to backup Database Master Key and Certificate.

BACKUP MASTER KEY TO FILE = 'c:\temp\key' ENCRYPTION BY PASSWORD = '<Pass>';
BACKUP CERTIFICATE MyEncryptCert TO FILE = 'c:\temp\cert' WITH PRIVATE KEY(ENCRYPTION BY PASSWORD='<Pass>', FILE='C:\temp\cert.pvk')

But I can not backup Symmetric Key. Without it I can not decrypt the encrypted data if I move the encrypted table to another Database.

Is there any solutions?

P.S. I tried the next code, but seems it is not safe to me, because if you know KEY_SOURCE and IDENTITY_VALUE you actually do not need original Database Master Key and Certificate to decrypt the data

CREATE SYMMETRIC KEY MySymmetricKey WITH KEY_SOURCE = '<Pass1>', ALGORITHM = AES_256, IDENTITY_VALUE = '<Pass2>' ENCRYPTION BY CERTIFICATE MyEncryptCert
like image 424
Alexander T Avatar asked Dec 08 '16 05:12

Alexander T


Video Answer


1 Answers

If you need to have the ability to duplicate a symmetric key, you should provide KEY_SOURCE and IDENTITY_VALUE. Your assessment is correct in that by knowing those two values, you can re-create the key. Observe the following code that shows that I can create the same key twice as is evidence by my encrypting a value with the "first" key, dropping the key, re-generating it with the same KEY_SOURCE and IDENTITY_VALUE, and then decrypting the encrypted value.

CREATE SYMMETRIC KEY MySymmetricKey WITH 
    KEY_SOURCE = '<Pass1>', 
    ALGORITHM = AES_256, 
    IDENTITY_VALUE = '<Pass2>' 
    ENCRYPTION BY Password = 'foobar!23'

open symmetric key MySymmetricKey
    decryption by password = 'foobar!23';
declare @encrypted varbinary(max);
select @encrypted = ENCRYPTBYKEY(KEY_GUID('MySymmetricKey'), 'my secrets!');

close symmetric key MySymmetricKey;
drop symmetric key MySymmetricKey;

CREATE SYMMETRIC KEY MySymmetricKey WITH 
    KEY_SOURCE = '<Pass1>', 
    ALGORITHM = AES_256, 
    IDENTITY_VALUE = '<Pass2>' 
    ENCRYPTION BY Password = 'foobar!23'

open symmetric key MySymmetricKey
    decryption by password = 'foobar!23';

select cast(DECRYPTBYKEY(@encrypted) as varchar(max))
close symmetric key MySymmetricKey;
drop symmetric key MySymmetricKey;
like image 96
Ben Thul Avatar answered Sep 20 '22 12:09

Ben Thul