I'm trying to insert encrypted data into my SQL Server table. First step, I created a master key, a certificate and a private key:
CREATE MASTER KEY
ENCRYPTION BY PASSWORD = 'PASSWORD#123'
GO
CREATE CERTIFICATE ElipseCert
ENCRYPTION BY PASSWORD = 'SENHA#123'
WITH SUBJECT = 'Certificado Senha Usuario'
GO
CREATE SYMMETRIC KEY KeyElipse
WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE ElipseCert
GO
After I tried to insert data:
OPEN SYMMETRIC KEY KeyElipse
DECRYPTION BY CERTIFICATE ElipseCert
DECLARE #GUID UNIQUEIDENTIFIER = (SELECT KEY_GUID('KeyElipse'))
INSERT INTO Usuario VALUES ('FONSECA', ENCRYPTBYKEY(#GUID, 'Abcd1234'))
GO
SELECT * FROM Usuario
CLOSE SYMMETRIC KEY KeyElipse
But when I executed the code returns me:
The certificate has a private key that is protected by a user defined password. That password needs to be provided to enable the use of the private key.
What's wrong?
Thanks a lot!
The certificate has a private key that is protected by a user defined password. That password needs to be provided to enable the use of the private key
So provide the password, replace this code
OPEN SYMMETRIC KEY KeyElipse
DECRYPTION BY CERTIFICATE ElipseCert
with this one
OPEN SYMMETRIC KEY KeyElipse
DECRYPTION BY CERTIFICATE ElipseCert WITH PASSWORD = 'SENHA#123';
Related
I have copied encrypted tables data (on column level) from database A to database B within the same server and followed below steps while creating and restoring keys and certificates, but column level decryption is not working in Database B.
Eg: In Database A, table name is "employee" and encrypted column name is "emp_id_proof". Now I have created the same "employee" table copy in database B from database A within the same server and restored certificates and keys in new databases but I am not able to decrypt "emp_id_proof" column data in Database B.
1) Steps to create master key, certificate and symmetric key in database A
USE DatabaseA
go
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'MyStrongPWD#2022'
go
CREATE CERTIFICATE Certificate_test WITH SUBJECT = 'Protect my data'
go
CREATE SYMMETRIC KEY SymKey01 WITH
KEY_SOURCE = 'SymKey01KeySource',
ALGORITHM = AES_256 ,
IDENTITY_VALUE = 'SymKey01IdentityValue'
ENCRYPTION BY CERTIFICATE Certificate_test
go
2) Steps for backup of master key and certificate in database A
USE DatabaseA
go
BACKUP MASTER KEY TO FILE = 'C:\Users\Administrator\Desktop\ENCRYPTION\ExportMasterkey'
ENCRYPTION BY PASSWORD = 'abc#2022'
go
BACKUP CERTIFICATE Certificate_test TO FILE = 'C:\Users\Administrator\Desktop\ENCRYPTION\ExportCert'
WITH PRIVATE KEY ( FILE = 'C:\Users\Administrator\Desktop\ENCRYPTION\ExportCertPK' ,
ENCRYPTION BY PASSWORD = 'xyz#2022' )
go
3) Steps for restoration/creation of master key,certificate and symmetric key in Database B
USE DatabaseB
go
RESTORE MASTER KEY
FROM FILE = 'C:\Users\Administrator\Desktop\ENCRYPTION\ExportMasterkey'
DECRYPTION BY PASSWORD = 'abc#2022'
ENCRYPTION BY PASSWORD = 'MyStrongPWD#2022'
go
CREATE CERTIFICATE [Certificate_test]
FROM FILE = 'C:\Users\Administrator\Desktop\ENCRYPTION\ExportCert'
WITH PRIVATE KEY (FILE = 'C:\Users\Administrator\Desktop\ENCRYPTION\ExportCertPK',
DECRYPTION BY PASSWORD = 'xyz#2022')
go
CREATE SYMMETRIC KEY SymKey01 WITH
KEY_SOURCE = 'SymKey01KeySource',
ALGORITHM = AES_256 ,
IDENTITY_VALUE = 'SymKey01IdentityValue'
ENCRYPTION BY CERTIFICATE Certificate_test
go
Could you please let me know what went wrong??
Also let me know the steps if I have to copy encrypted columns data from one server to another server database.
--symmetric key not encrypted by certification
create symmetric key SQLSymKey
with algorithm = aes_192
encryption by password ='uuu)) %';
--symmetric key encrypted by certification
CREATE SYMMETRIC KEY SQLSymKey
WITH ALGORITHM = AES_128
ENCRYPTION BY CERTIFICATE SelfSignedCertificate;
Setup: I'm trying to read data from an encrypted column
Always Encrypted column was setup on Server A for the local sql instance that it's hosting(I know it defeats the purpose for AE, but this is just for testing)
Now I am trying to decrypt the data from Server B by first Exporting the CNG key from server A and importing it in server B and recreating an CNG key with the same configurations and name but I am receiving this error when I try to read data from Server B:
Msg 0, Level 11, State 0, Line 0
Failed to decrypt column 'Name'.
Msg 0, Level 11, State 0, Line 0
Failed to decrypt a column encryption key using key store provider: 'MSSQL_CNG_STORE'. Verify the properties of the column encryption key and its column master key in your database. The last 10 bytes of the encrypted column encryption key are: 'U3-2A-2V-2D-F5-03-C7-C9-4A-C4'.
Msg 0, Level 11, State 0, Line 0
The specified encrypted column encryption key signature does not match the signature computed with the column master key (asymmetric key) in 'Microsoft Software Key Storage Provider/AE_CNG_PS_test'. The encrypted column encryption key may be corrupt, or the specified path may be incorrect.
Parameter name: encryptedColumnEncryptionKey
Code is below:
#Server A
CNG Key Creation for Creating Master Key and Encryption Key
# Create a column master key in a key store that has a CNG provider, a.k.a key store provider (KSP).
$cngProviderName = "Microsoft Software Key Storage Provider" # If you have an HSM, you can use a KSP for your HSM instead of a Microsoft KSP
$cngAlgorithmName = "RSA"
$cngKeySize = 2048 # Recommended key size for Always Encrypted column master keys
$cngKeyName = "AE_CNG_PS_test" # Name identifying your new key in the KSP
$cngProvider = New-Object System.Security.Cryptography.CngProvider($cngProviderName)
$cngKeyParams = New-Object System.Security.Cryptography.CngKeyCreationParameters
$cngKeyParams.provider = $cngProvider
$cngKeyParams.KeyCreationOptions = [System.Security.Cryptography.CngKeyCreationOptions]::OverwriteExistingKey
$keySizeProperty = New-Object System.Security.Cryptography.CngProperty("Length", [System.BitConverter]::GetBytes($cngKeySize), [System.Security.Cryptography.CngPropertyOptions]::None);
$cngKeyParams.Parameters.Add($keySizeProperty)
$cngAlgorithm = New-Object System.Security.Cryptography.CngAlgorithm($cngAlgorithmName)
$cngKey = [System.Security.Cryptography.CngKey]::Create($cngAlgorithm, $cngKeyName, $cngKeyParams)
Exporting the CNG key
[byte]$PubKey = $cngKey.Export([System.Security.Cryptography.CngKeyBlobFormat]::GenericPublicBlob)
[String]$ExpPubKey = [Convert]::ToBase64String($PubKey)
$ExpPubKey | Out-File C:\FakePath\PubKey.txt
## C:\FakePath\PubKey.txt = UlNasasdasgerferferferfsASIurh34e23t23gSgzxkTFTuFpPYlTzYAYuurypos6nutcXg5Ek4wXQ/JsDLAXXcKxTYl/SBo490b1QP303rwXsdgU67Hy67aXrhywCO9BjzXAEf0qJDLqt3r7RAUByrSaUg1Jp2RrdTb7uS6Vf8bDYmwDDSfqQbEHkm2fA36diLGDxQ==
CNG Key For Server A
PS C:\Users\Test> $cngKey
AlgorithmGroup : RSA
Algorithm : RSA
ExportPolicy : None
Handle : Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle
IsEphemeral : False
IsMachineKey : False
KeyName : AE_CNG_PS_test
KeySize : 2048
KeyUsage : AllUsages
ParentWindowHandle : 0
Provider : Microsoft Software Key Storage Provider
ProviderHandle : Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle
UniqueName : va9356ed810cc3dg272b6a921g53daad_b13750ab-b64d-4234-aff4-1ffs23593b6fca
UIPolicy : System.Security.Cryptography.CngUIPolicy
#Server B
Import the CNG Key
[string]$ImpPubKey = 'UlNasasdasgerferferferfsASIurh34e23t23gSgzxkTFTuFpPYlTzYAYuurypos6nutcXg5Ek4wXQ/JsDLAXXcKxTYl/SBo490b1QP303rwXsdgU67Hy67aXrhywCO9BjzXAEf0qJDLqt3r7RAUByrSaUg1Jp2RrdTb7uS6Vf8bDYmwDDSfqQbEHkm2fA36diLGDxQ=='
$ImpBlob = [Convert]::FromBase64String($ImpPubKey)
$cngKey = [System.Security.Cryptography.CngKey]::Import($ImpBlob,[System.Security.Cryptography.CngKeyBlobFormat]::GenericPublicBlob)
$cngKeyParams = New-Object System.Security.Cryptography.CngKeyCreationParameters
$cngKeyParams.provider = $cngKey.Provider
$cngKeyParams.KeyCreationOptions = [System.Security.Cryptography.CngKeyCreationOptions]::OverwriteExistingKey
$keySizeProperty = New-Object System.Security.Cryptography.CngProperty("Length", [System.BitConverter]::GetBytes($cngKey.KeySize), [System.Security.Cryptography.CngPropertyOptions]::None);
$cngKeyParams.Parameters.Add($keySizeProperty)
$NewlyCreatedCNGFromImport = [System.Security.Cryptography.CngKey]::Create($cngKey.Algorithm,'AE_CNG_PS_test',$cngKeyParams)
CNG for newly created CNG in Server B
PS C:\Users\Test> $NewlyCreatedCNGFromImport
AlgorithmGroup : RSA
Algorithm : RSA
ExportPolicy : None
Handle : Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle
IsEphemeral : False
IsMachineKey : False
KeyName : AE_CNG_PS_test
KeySize : 2048
KeyUsage : AllUsages
ParentWindowHandle : 0
Provider : Microsoft Software Key Storage Provider
ProviderHandle : Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle
UniqueName : a25ag6356ed810c3fd472shees121ea4daad_f023yd98-44V3-75G7-819b-02cf6d3t5470
UIPolicy : System.Security.Cryptography.CngUIPolicy
It seems that when I read the data of Sever A from Server B, SQL cannot find or decrypt the column using the CNG key which was imported. Could it be an issue for the path? or an issue on the export/import(+recreate in server B) of the CNG key?
I had the need to encrypt/decrypt some personal information in my database such as credit card no and passwords.
Following the steps from Microsoft I was successfully encrypt & decrypt the data.
But after some test I have questions.
Assume someone gets unauthorized access to the database (hack) and can see the database in SSMS from his own computer. Surly he can see that I had some certificate and symmetric key setup.
In order to display the data the examples shows the following query
OPEN symmetric KEY symmetrickey1
decryption BY certificate certificate1
Now list the original ID, the encrypted ID
SELECT customer_id,
credit_card_number_encrypt AS
'Encrypted Credit Card Number',
CONVERT(VARCHAR, Decryptbykey(credit_card_number_encrypt)) AS
'Decrypted Credit Card Number'
FROM dbo.customer_data;
-- Close the symmetric key
CLOSE symmetric KEY symmetrickey1;
If the above query returns the data and can see the credit card how can then be protected? Shouldn't it be necessary to pass a password somewhere in the query?
I am sure that I miss something here. Can anyone explain this to me?
i had to include a password to the cerificate
CREATE CERTIFICATE Certificate1
Encryption By Password='Password123'
WITH SUBJECT = 'Protect Data'
for retrieving data
OPEN Symmetric KEY SymmetricKey1
DECRYPTION BY CERTIFICATE Certificate1 With Password='Password123'
;
select *,CONVERT(nvarchar(255),DECRYPTBYKEY(Credit_Card_No)) as
[Credit_Card_No3] from Customers
;
Close Symmetric Key SymmetricKey1
Im trying to copy an encrypted database from the default server to my server for testing purposes
but im having troubles doing so because i have never done it
so im going to explain my procedure and the errors i got
first i create a master key :
USE master
GO
CREATE MASTER KEY ENCRYPTION BY PASSWORD ='DB-PaSSw0rD'
GO
all is good for now :
Command(s) completed successfully.
then i create a certificate by importing the certificate created on the default server:
CREATE CERTIFICATE TDECERT
FROM FILE = 'C:\temp\TDECert.cer'
WITH PRIVATE KEY (FILE = 'C:\temp\TDECertKey.pvk' ,
DECRYPTION BY PASSWORD ='pAssW0rD')
GO
but i get :
Msg 15581, Level 16, State 1, Line 1
Please create a master key in the database or open the master key in the session before performing this operation.
to resolve this i try to open the master key:
OPEN MASTER KEY DECRYPTION BY PASSWORD ='DB-PaSSw0rD'
ALTER MASTER KEY ADD ENCRYPTION BY SERVICE MASTER KEY
but i get :
Cannot find the symmetric key 'master key', because it does not exist or you do not have permission.
then to resolve this second issue i try to grant it access:
GRANT CONTROL ON CERTIFICATE :: TDECERT To Administrator
but i get :
Cannot find the certificate 'TDECERT', because it does not exist or you do not have permission.
thanks in advance for ur time
problem solved
all i had to do is add
USE master
before
CREATE CERTIFICATE TDECERT
FROM FILE = 'C:\temp\TDECert.cer'
WITH PRIVATE KEY (FILE = 'C:\temp\TDECertKey.pvk' ,
DECRYPTION BY PASSWORD ='pAssW0rD')
GO
and didnt need anything else
that easy!