Encrypting SQL Server Data with Certificate and Symmetric Key - sql

I am trying to encrypt database columns using a certificate and a symmetric key.
I successfully created the certificate and symmetric key using the following:
CREATE CERTIFICATE MyCertificate
ENCRYPTION BY PASSWORD = 'password'
WITH SUBJECT = 'Public Access Data'
GO
CREATE SYMMETRIC KEY MySSNKey
WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE MyCertificate
I tried encrypting and decrypting some data using the following:
DECLARE #Text VARCHAR(100)
SET #Text = 'Some Text'
DECLARE #EncryptedText VARBINARY(128)
-- Open the symmetric key with which to encrypt the data.
OPEN SYMMETRIC KEY MySSNKey
DECRYPTION BY CERTIFICATE MyCertificate;
SELECT #EncryptedText = EncryptByKey(Key_GUID('MySSNKey'), #Text)
SELECT CONVERT(VARCHAR(100), DecryptByKey(#EncryptedText)) AS DecryptedText
When I do so, I get the following error message:
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.
Ultimately, what I am trying to do is write a stored procedure that will take some unencrypted data as input, encrypt it, then store it as encrypted varbinary. Then I'd like to write a 2nd stored procedure that will do the opposite - i.e., decrypt the encrypted varbinary and convert it back to a human-readable data type. I would rather not have to specify the password directly in the stored procedure. Is there any way to do that? What am I doing wrong in my code above?
Thanks.

You just need to use:
OPEN SYMMETRIC KEY MySSNKey
DECRYPTION BY CERTIFICATE MyCertificate WITH PASSWORD = 'password';

You nead use MASTER KEY
Example:
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'MasterPassword';
CREATE CERTIFICATE MyCertificate WITH SUBJECT = 'Public Access Data';
CREATE SYMMETRIC KEY MySSNKey WITH ALGORITHM = AES_256 ENCRYPTION BY CERTIFICATE MyCertificate;
OPEN SYMMETRIC KEY MySSNKey DECRYPTION BY CERTIFICATE MyCertificate;
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 SYMMETRIC KEY MySSNKey ;

Related

How to create RsaSecurityKey.KeyId with IdentityServer4

I'm using IdentiyServer4 to generate tokens, I'm using the AddDeveloperSigningCredential() method to generate my RSA key with a KeyId.
But, in production, I'm using AddSigningCredential(CreateSigningCredential()), to generate a key like this :
private SigningCredentials CreateSigningCredential()
{
var signinkey = new RsaSecurityKey(RSA.Create());
signinkey.KeyId = "abcdefghijklmnopqrstuvwxyz";//How to generate KeyId ??
var credentials = new SigningCredentials(signinkey,
SecurityAlgorithms.RsaSha256);
return credentials;
}
How can I generate a KeyId? Can I set it to any arbitrary value?
You don't need to set the keyId and also creating the RSA key youself in code, sounds like bad practice. Then you can just as well use the AddDeveloperSigningCredential method.
You can actually look at the source for that method here to see how they do it in code:
https://github.com/DuendeSoftware/IdentityServer/blob/main/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Crypto.cs
But, in production you should generate the key externally and pass it in to IdentityServer, so the key is the same across redeployment/restarts. Otherwise previously issued tokens will not be valid anymore.
You can for example store the key in Azure Key Vault, or using some other configuration/secret system. Or in a database or as a file somewhere.
If you want to create one manually, using OpenSSL, then you can write
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -aes256 -out rsa-private-key.pem

certificate signing request: Does it contain public key or private key?

I am trying to demystify how CSR is generated, and role of the public and private key.
Server1:
Generate a public and private key
Now, I want CSR and for that, I will go to a CA for signing.
For creating a CSR request, is it based on server's public key or private key?
I referred to this SO question; in there, it says the server (which is requesting for CSR) itself signs CSR by its private key, before sending it to CA.
I am bit confused, have the following questions:
The end product (the signed certificate by CA): Does it contain server's private key or public key? I understand that the end product should contain the public key of the server requesting CSR.
While initiating a CSR request, why a server needs to sign a CSR by its private key? Is it correct?
Is server's public key part of CSR?
Eventually, does CA generate a certificate from CSR and how it derives the public key of the server from CSR?
The end product (the signed certificate by CA): Does it contain server's private key or public key?
The certificate is a public document. It therefore can only contain the public key. If it contained the private key, then that key wouldn't be private any more.
While initiating a CSR request, why a server needs to sign a CSR by its private key? Is it correct?
Yes, it is generally correct. This concept is called Proof of Possession (PoPo) and it used to prove to the CA that you (or the server in this case) have the private key corresponding to the public key which will be signed by the CA (or at least had it at the time just before the CA signed your certificate). If the CA didn't insist on PoPo then you could repudiate any signed future message as follows:
You have your public key signed by the CA to create your certificate. At the time, you sign your request with your private key as you should. Everything is good.
I come along and copy your public key from your certificate. I now present that to the CA as a CSR but without PoPo. The CA signs it and sends me a certificate, which now contains my name and your public key.
At some point, you send a digitally signed (with your private key) message to a third party, say your bank, asking them to donate $1000 to Stack Overflow.
You later decide that the $1000 would be better spent on a vacation, so you dispute the signed message to your bank.
The bank says But you digitally signed the message to authenticate it!!
As you know the CA signs certificates without PoPo, you simply have to say that I must have sent the message instead, using your private key which I've now destroyed in an attempt to hide the evidence.
The bank cannot prove that (6) isn't true as they didn't check I had possession of the private key corresponding to the public key in my request, and therefore your statement of it wasn't me cannot be rejected - the bank has to reimburse you.
If the bank insisted on PoPo when I submitted your public key to the CA, my request would have failed and you could not repudiate your message later. But once a CA signs a request without PoPo - all bets are off for non-repudiation.
Eventually, does CA generate a certificate from CSR and how it derives the public key of the server from CSR?
There is no derivation to do - your server's public key is in the request in a construct called a CertificateRequestInfo.
This CertificateRequestInfo contains your (or server's) name and the public key. It can also contain other elements such as requested extensions. The CA takes whatever information it requires from this CertificateRequestInfo (only the public key is mandatory) and uses the info to generate a construct called a tbsCertificate (the 'tbs' stands for To Be Signed). This construct contains your name, your public key and whatever extensions the CA deems fit. It then signs this tbsCertificate to create your certificate.

Format Public key

I am working on signing certificate with HSM, and I need to format the CA public key and output it. I read the EMV Book and the format as follows:
Field Name Length Description Format
Registered
Application Provider 5 Identifies the payment system to b
Identifier (RID) which the Certification Authority
Public Key is associated
Certification
Authority Public Key 1 Identifies the Certification
Index Authority Public Key in b
conjunction with the RID
Certification
Authority Hash 1 Identifies the hash algorithm used b
Algorithm Indicator to produce the Hash Result in the
digital signature scheme
Certification
Authority Public Key 1 Identifies the digital signature
Algorithm Indicator algorithm to be used with the b
Certification Authority Public Key
Certification
Authority Public Key Var. Value of the modulus part of the b
Modulus (max Certification Authority Public Key
248)
Certification
Authority Public Key 1 or 3 Value of the exponent part of the b
Exponent Certification Authority Public Key,
equal to 3 or 216 + 1
Certification
Authority Public Key 20 A check value calculated on the b
Check Sum36 concatenation of all parts of the
Certification Authority Public Key
(RID, Certification Authority
Public Key Index, Certification
Authority Public Key Modulus,
Certification Authority Public Key
Exponent) using SHA-1
I am writing the code with Visual Basic.net.How can I format this in the code and output? I made a Class named PublicKey, and there has three functions, ExportPublicKey, FormatPublicKey and WritePublicKeyToFile.
Can anyone help? Thank you very much.
What ever you have given is the minimum required data to be available in the terminal to validate Issuer Public Key Certificate signed by CA Private Key. On the terminal you will have the CA Public key list which you will match with the data from the card(using RID and exponent from card), get the correct CA Pubic key and open the certificate. But your requirement "format the CA public key and output it" makes no sense to me.
The format of Issuer Public Key certificate will be as below.
On a HSM Racal 9000, the command to generate a certificate will be EW, however I have not used it ever.
Note : The above are based my understanding of your issue. If you think my understanding meets your requirement, go through the whole section which explains about Offline Data Authentication. It is very interesting. Otherwise gently ignore ;)

MS SQL column encryption without certificate

I am trying to encrypt one of my sensitive columns in a SQL Server table.
I tried AES256 encryption with this script, and it works perfect.
But I don't want to create Certificates, or Symmetric Keys on my SQL Server as it may be a security problem later.
How can I encrypt the data with a single password or key in my query ?
Another problem with this method is, I can use only a single master password for
my encryption.
CREATE MASTER KEY ENCRYPTION
BY PASSWORD = '$Passw0rd'
GO
CREATE CERTIFICATE AESEncryptTestCert
WITH SUBJECT = 'AESEncrypt'
GO
CREATE SYMMETRIC KEY AESEncrypt
WITH ALGORITHM = AES_256 ENCRYPTION -- TRIPLE_DES ENCRYPTION
BY CERTIFICATE AESEncryptTestCert;
OPEN SYMMETRIC KEY AESEncrypt DECRYPTION
BY CERTIFICATE AESEncryptTestCert
SELECT ENCRYPTBYKEY(KEY_GUID('AESEncrypt'),'The text to be encrypted');
You can use EncryptByPassPhrase and DecryptByPassPhrase, for example:
DECLARE #CypherText varbinary(8000)
DECLARE #ClearText varchar(128) = 'Text to encrypt'
SET #CypherText = EncryptByPassPhrase ('MyP#ssword123', #ClearText)
DECLARE #DecryptedText varchar(128)
SET #DecryptedText = DecryptByPassPhrase('MyP#ssword123', #CypherText)
SELECT #CypherText AS CypherText, #DecryptedText As DecryptedText
EDIT:
The above code produces the following output
+----------------------------------------------------------------------------+-----------------+
| CypherText | DecryptedText |
+----------------------------------------------------------------------------+-----------------+
| 0x01000000F1D813F399246484FDA8D7C7D22BFBCF748D3F6033D4E9980FCDC58A387A1A93 | Text to encrypt |
+----------------------------------------------------------------------------+-----------------+

gpg signing and encrypting using my private key and end users public key

Currently we use Kleopatra to Sign and Encrypt files sent to a third party. We sign with our private key and encrypt with our public key and the third party's public key...
Using gpg by itself, do I make multiple calls adding each piece as i go? i.e.:
gpg.BinaryPath = (path to GnuPG)
gpg.Recipient = myUserID
gpg.Passphrase = myPassword
gpg.Sign( origfile, signedfile )
gpg.Encrypt( signedFile, signedAndEncryptedFile )
gpg.Recipient = thirdPartyUserID
gpg.Encrypt( signedAndEncryptedFile , thirdPartySignedAndEncryptedFile )
Any help would be appreciated...