USE Hashgroups GO /* Create the keys and certificates required to encrypt SSn numbers. Values for passwords here are for demo purposes only. If you use this code modify the password and names according to your requirements. To see the various changes it is recommended to have set statsistics time on as well as 'show actual execution plan' */ SELECT COUNT(1) FROM dbo.cust go select TOP 10 custID , ssn FROM dbo.cust; go -- create basic keys & certificates to be able to use encryption! CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'P(-"2w2+]?*5/3+@06.15*) 0) SET @Result = @Result % @Divisor; RETURN @Result; END GO -- show what the parts do DECLARE @Result INT; SET @Result = HASHBYTES('SHA1', 'thisismyhashinginput-withsalt'); SELECT @Result AS result_value SET @Result = @Result % 50; SELECT @Result AS result_group_number -- apply the hashgrouping - aprox UPDATE dbo.SSN_encr set ssn_hg = dbo.ufn_GroupData(ssn,10000) FROM ssn_encr INNER JOIN cust ON cust.custid = ssn_encr.custID; go SELECT TOP 1000 * FROM dbo.ssn_encr -- what the distribution looks like SELECT ssn_hg, COUNT(1) AS group_members FROM dbo.ssn_encr GROUP by ssn_hg ORDER BY ssn_hg -- only a few indexes for now --CREATE clustered INDEX ix_hg ON ssn_encr (ssn_hg); --go -- use random value below -- turn on execution plan! SET STATISTICS TIME ON; DBCC freeproccache; DBCC DROPCLEANBUFFERS; DECLARE @ssn VARCHAR(9) SET @ssn = '033578781' SELECT custID , ssn FROM cust WHERE ssn =@ssn go DBCC FREEPROCCACHE; DBCC DROPCLEANBUFFERS; -- check performance on having encrypted the data OPEN SYMMETRIC KEY HGssnkey DECRYPTION BY CERTIFICATE SSN_Encrypt go DECLARE @ssn VARCHAR(9) SET @ssn = '033578781' /* Get a random record based on SSN coming in and being decrypted for comparison */ SELECT custid , ssn_encr , CONVERT(VARCHAR, DECRYPTBYKEY(ssn_encr)) AS decrypted_ssn , ssn_hg FROM dbo.SSN_encr WHERE CONVERT(VARCHAR, DECRYPTBYKEY(ssn_encr)) = @ssn CLOSE SYMMETRIC KEY HGssnkey; go -- drop any optimizations DBCC FREEPROCCACHE; DBCC DROPCLEANBUFFERS; go -- add the Hash group lookup to the select OPEN SYMMETRIC KEY HGssnkey DECRYPTION BY CERTIFICATE SSN_Encrypt go DECLARE @ssn VARCHAR(9) SET @ssn = '033578781' SELECT custid , ssn_encr , CONVERT(VARCHAR, DECRYPTBYKEY(ssn_encr)) AS decrypted_ssn , ssn_hg FROM dbo.SSN_encr WHERE CONVERT(VARCHAR, DECRYPTBYKEY(ssn_encr)) = @ssn AND dbo.ufn_GroupData(@ssn,10000) = SSN_HG CLOSE SYMMETRIC KEY HGssnkey; go