BLOGS

ByHariharan Rajendran

Stretch Database – Filter

We can easily filter the rows to migrate the data to azure  through T-SQL statement. Need to associate that filter function with the script to enable the data migration to azure.

This article explains the same filter concept through wizard. we can easily apply the filter with few clicks.

1. Right click your database->Tasks->Stretch->Enable

2. Choose the table and look for a column “Migrate” and click the hyperlink “Entire Table”

image

3. Filter the rows in the below window

image

image

image

ByHariharan Rajendran

Always Encrypted–PowerShell Scripts Part-2

Applying the encryption to the table column is easy with the PowerShell. Please make sure to follow the below steps before run the below scripts.

1. Connect to SQL Server from PowerShell

2. Create column master key & column encryption key   – You can create by using wizard or PowerShell Scripts

Wizard method

PowerShell Script

3. Choose the column which you want to apply the encryption.

4. Defined the encryption type

 

Run the below script just continue with this script

$ces = @()
$ces += New-SqlColumnEncryptionSettings -ColumnName “dbo.Patients.SSN” -EncryptionType “Deterministic” -EncryptionKey “CEK1”

Set-SqlColumnEncryption -InputObject $database -ColumnEncryptionSettings $ces

You can append multiple encryption by adding + symbol, like below

$ces = @()
$ces += New-SqlColumnEncryptionSettings -ColumnName “dbo.Patients.SSN” -EncryptionType “Deterministic” -EncryptionKey “CEK1”
$ces += New-SqlColumnEncryptionSettings -ColumnName “dbo.Patients.BirthDate” -EncryptionType “Randomized” -EncryptionKey “CEK1”
Set-SqlColumnEncryption -InputObject $database -ColumnEncryptionSettings $ces

ByHariharan Rajendran

Always Encrypted–PowerShell Scripts

We have discussed that how to create a Always encrypted columns and steps to create custom column master key & column encryption key.

This article explains about the creation of keys with the help of PowerShell scripts.

Latest PowerShell Cmdelt’s update from Microsoft, https://blogs.technet.microsoft.com/dataplatforminsider/2016/06/30/sql-powershell-july-2016-update/

Pre-Requisites:

Since Always Encrypted feature introduced in SQL Server 2016, we need to upgrade our SQLPS.exe. If you use the older version of SQLPS then that will not recognize the some of the below cmdlets. So make sure to upgrade SQLPS.exe first.

You can upgrade by installing the latest version of SSMS (SQL Server management studio) 2016.

Check for the below modules installed in PowerShell,

#List directory wise installed modules

Get-Module –ListAvailable

image

Check for SQLASCMDLETS & SQLPS. If there is no modules then make sure you have SQLPS.exe file available in below location

C:\Program Files (x86)\Microsoft SQL Server\130\Tools\PowerShell\Modules

# Import the SQL Server Module.
Import-Module Sqlps -DisableNameChecking;

 

Steps to Create a Column Master Key & Column Encryption Key.

In the Below script, we need to specify following information,

  • Server Name
  • Database Name
  • Column Master Key Name
  • Column Encryption Key Name

First Connect to the Server and Database using PowerShell Script

# Connect to your database.
$serverName = “<server name>”
$databaseName = “<database name>”

$connStr = “Server = ” + $serverName + “; Database = ” + $databaseName + “; Integrated Security = True”
$connection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection
$connection.ConnectionString = $connStr
$connection.Connect()
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($connection)
$database = $server.Databases[$databaseName]

As we know, we have different key stores available. This below script using “Windows Certification Store – Current User”.

# Create a column master key in Windows Certificate Store.
$cert1 = New-SelfSignedCertificate -Subject “AlwaysEncryptedCert” -CertStoreLocation Cert:CurrentUser\My -KeyExportPolicy Exportable -Type DocumentEncryptionCert -KeyUsage DataEncipherment -KeySpec KeyExchange

In the above script, you can check the “CertStoreLocation”. To identify the location, you can check in T-SQL Statement to create master key. I just highlighted in below script for understanding purpose.

USE [Sample_Encrypt]
CREATE COLUMN MASTER KEY [test1]
WITH
(
    KEY_STORE_PROVIDER_NAME = N’MSSQL_CERTIFICATE_STORE’,
    KEY_PATH = N’CurrentUser/My/55A4DDAF58D274547B9C3BA5ABA154662CDF62D0′
)

GO

# Create a SqlColumnMasterKeySettings object for your column master key.
$cmkSettings = New-SqlCertificateStoreColumnMasterKeySettings -CertificateStoreLocation “CurrentUser” -Thumbprint $cert1.Thumbprint

# Create column master key metadata in the database.
$cmkName = “<cmk name>”
New-SqlColumnMasterKey -Name $cmkName -InputObject $database -ColumnMasterKeySettings $cmkSettings

# Generate a column encryption key, encrypt it with the column master key and create column encryption key metadata in the database.
$cekName = “<cek name>”
New-SqlColumnEncryptionKey -Name $cekName -InputObject $database -ColumnMasterKey $cmkName

Verify the keys in SQL Server Database Security folder.

ByHariharan Rajendran

Always Encrypted–Key Stores

As you know, we can create “Column Master Key” & “Column Encryption Key” to encrypt the column values. You can check here to learn about key creation. Usually these keys are associated with the certificate which includes the details like,

Issued To, Issued By, Expiration Date, Thumbprint & etc.

In Always encryption, we have four different Key store options are available which helps us to secure our keys. These keys are associated with the table columns. We can decrypt the values using these keys so we need to make sure to secure the keys.

Key stores,

  1. Windows Certificate Store – Current User
  2. Windows Certificate Store – Local Machine
  3. Azure Key Vault
  4. Key Storage Provider (CNG)

image

 

Widows Certificate Store – Current User

This type of certificate store is local to current user on the computer. This is located in the registry of the computer, specifically on HKEY_CURRENT_USER root

We need to compare the current user certificate store with local machine certificate store. Current user certificate always inherit the content of the local machine certificate.

image

We can generate the certificate by our self and that will be available for one year and we can use that to encrypt the column values.

T-SQL Statement to create a master key, we can select the certificate (Thumbprint) which I highlighted.

image

Windows Certificate Store – Local Machine

This will be available on the computer which is global to all users on the computer. This is located under HKEY_LOCAL_MACHINE registry.

This will list out all the available certificates in your computer and choose for encryption.

 

image

Azure Key Vault

This should be used to safeguard the keys in cloud (Azure). It requires a Azure subscription.

 

Key Storage Provider (CNG)

It provides different providers,

  1. Microsoft Passport Key Storage Provider
  2. Microsoft Smart Card Key Storage Provider
  3. Microsoft Software Key Storage Provider

We can choose any of the above provider, for more information about the algorithm, key length & etc., check Microsoft article here.

image

ByHariharan Rajendran

Always Encrypted in SQL Server – Part 2

We can easily enable the encryption using wizard which you can check it here.

Disabling the encryption is also an easy task through wizard.

Steps to disable the encryption,

Step 1: Right Click on your database and choose Tasks->Encrypt Columns..

Step 2: Select next on the introduction page.

Step 3: When you are enter into column selection page, you can see the lock symbol on the columns which you enabled the encryption. Under encryption type, you can see the drop down values which includes “Plaintext”, “Deterministic” & “Randomized”. Choose the “Plaintext” and proceed next.

image

image

image

Step 4: Go through further steps and finish it.

Step 5: Now, run the select statement on table and you should see the result without an encryption.

 

We can define the “Encryption Key” & “Master key” Name manually.

Follow the steps to create custom names and to make use for encryption.

Step 1: Go to Security folder of your database.

image

Step 2: Expand the security folder and you should see the folder called “Always Encrypted Keys”. Expand the folder.

image

Step 3: You should see another two folders, Column Master Keys & Column Encryption Keys. Right click on Column Master Keys folder and choose “New Column Master Key..”

image

Step 4: Define the name of the master key and choose the key store where you want to store your key safely and click OK. Master will be created.

image

Step 5: Right click on Column Encryption Keys folder and choose “New Column Encryption Keys”

image

Step 6: Give the name and choose the master key from drop down. You should see the master key which you created in above step 4 and click OK.

image

Step 7: Now, go and create an encrypted column and you should see the option to choose your encryption key. Master key also will be applied automatically.

image

ByHariharan Rajendran

Always Encrypted SQL Server 2016

I have discussed “Always Encrypted” concept and covered steps to create Always encrypted columns through T-SQL Statement. Check column level encryption using Always Encrypted in SQL Server 2016

We can enable the encryption to the database table columns through wizard as well .

Before Always Encryption,

image

After Always Encryption,

image

Steps to encrypt the column,

Step 1: Right click your database where your tables are there to encrypt.

Step 2: Go to Tasks->Encrypt Columns… and choose.

image

Step 3: You will see the Introduction page, click Next

image

Step 4: Choose the columns from table and choose the encryption type. To know more about encryption type, visit here. The encryption key name will be created like “CEK_Auto”. It will keep extend like “CEK_Auto1”, …Auto2, etc. You can use the same encryption key for multiple columns.

image

image

Step 5: Once selected the required options, Next option will be enabled and click Next

image

Step 6: Master Key Configuration will be created for your database. It is an one time activity.

image

Step 7: Click Next and you can see two options,

  1. Generate PowerShell Script to run later – Basically this enabling the encryption should be done while doing database maintenance.
  2. Proceed to finish now

image

image

Step 8: Check the configuration in summary page and click next to proceed. The scripts will start run in the background and will encrypt the selected columns.

image

image

Step 9: Run the table and check the column values.

image

ByHariharan Rajendran

For Loop in R

In a real time, we will be in a position to handle the logic using loops. Loop concept is available in all programming language and also in R.

For example, if we want to generate first 200 prime numbers, we have to use loop to get the result.

In R, “for loop” is used to iterate over a vector.

Syntax

for (val in sequence) {

statement

}

In the above syntax, sequence is a vector which we can define and assign into an object and can use the object or we can directly place the vector with the expression. “val” will take the value of sequence and process in a loop. The statement will be triggered until the length of the sequence is completed.

Example,

x <- c(1,2,3,4,5,6,7,8,9,10)

count <- 0

for (val in x) {

if(val %% 2 == 0) count = count+1

}

print(count)

image

Using Next

We can use the word next inside the for loop and it will change the flow of the process. Check the below example,

for (i in 1:10) {

if (!i %% 2){

}

print(i)

}

image

If you run above script, I will get the result as 1,2,3,4,5,6,7,8,9,10 (All the values from the 1:10 sequence).

If you want to display only the odd number for the same sequence input then I can just add a “next” keyword inside if loop.

for (i in 1:10) {

if (!i %% 2){

next

}

print(i)

}

image

First “i” value 1 will go to if condition once the value reaches the keyword “next”. It will redirect to for loop again and it will come again for the second number i.e. 2 and it will continue up to 10.

ByHariharan Rajendran

If and Else function in R

I have discussed that how to use if and else statement in R in my previous article.

In a real time coding, we will be expecting a short form of code which should give the same expected result.

Vectors are basic building block of R Programming and will be used as input.

To apply the same if and else logic for the vector input, we can use if and else function which will give the same result but as a output vector.

 

Syntax:

Ifelse(test_expression,x,y)

The output of the function could be a vector. In the above syntax, test_expression is a condition which we can apply into the input vector and x is nothing but a custom value or expression, in logical it is called TRUE. If the condition is satisfied then x (TRUE) will display, you can replace x with any value. Here y is FALSE, if the test_expression is not satisfied then y will display.

Example,

number = c(3,5,7,10)
ifelse(number %% 2 == 0,”even”,”odd”)

image

Logically the result would be FALSE, FALSE, FALSE, TRUE.