My SQL Server CLR function is very slow - c#

I have created two methods in C#:
public static string Encrypt(string clearText, string encryptionKey)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
var pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
public static string Decrypt(string cipherText, string encryptionKey)
{
try
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
var pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
}
catch (Exception)
{
}
return cipherText;
}
By following the steps given in This Link, I have created a CLR function in SQL Server and I am trying to call it like:
SELECT dbo.Decrypt(MyEncrypted, EncryptionKey)
FROM MyTable
The problem is, it is taking TOO MUCH TIME. Like for only 1000 rows, it took 1.5 minutes. If I call my query without the CLR function, it took less than 1 second.
Is there any thing I can do to improve the performance of the CLR functions?

I've analyzed your Decrypt method with the Performance Analyzer in VS2010 by running it 100 times:
As you can see the GetBytes method of the Rfc2898DeriveBytes instance take the most time.
I'm not sure why you have these specific encryption/decryption requirements but one way influence the time the GetBytes method takes is to instantiate the Rfc2898DeriveBytes using the constructor that takes iterations as the third parameter. Default it is on 1000, I can set it as low as 1. BUT THIS IS STRONGLY ADVISED AGAINST
var pdb = new Rfc2898DeriveBytes(encryptionKey, salt, 10);
This iterations does need to be the same for both the Encrypt and Decrypt so you'll have to Decrypt\Encrypt your current values if you want to change that.
One other option might be to cache the IV values as seems to recommended in this answer. I'm not enough of an expert if they talk there about using the same Key as well but if that is an option you might cache the call to GetBytes for the key as well.
All the described change have impact on how your data is encrypted and the strength of your encryption. Consider both impacts when testing the solutions.

Related

Encode data from .net (c#) and decode with angular(ts)

i'm actually use this code to encode my data with c#.
public static string encrypt_data(string clearText ,string EncryptionKey) {
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
and i'm looking for the code to decode the data in angular 8 (ts)

Encrypting a string in .net and decrypting it in python

I'm trying to encrypt password using system.Security.Cryptography which is working properly
This is the code (.Net)
if (clearText == null)
{
clearText = "";
}
string EncryptionKey = "****";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
And this is decryption code in python which is not working properly
def Decryptstr(self, text):
try:
EncryptionKey = "****"
if text is None:
return
else:
cipherbytes = base64.b64decode(text)
salt = '\0x49\0x76\0x61\0x6e\0x20\0x4d\0x65\0x64\0x76\0x65\0x64\0x65\0x76'
key_bytes = KDF.PBKDF2(EncryptionKey, salt, dkLen=32)
iv = KDF.PBKDF2(EncryptionKey, salt,dkLen=16)
cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
password = cipher.decrypt(cipherbytes).decode('utf-16')
print(password)
return password
except Exception as err:
print(err)
following is the output of the above code for the encrypted string ('eet123')
䏺꧴퐄妯৞軸힡薟
Any help will be appreciated.
It seems that your PBKDF2HMAC key extraction in python side is incorrect. You need to pass correct parameters and get a 48 bytes key. Then use first 32 bytes as Key and last 16 bytes as IV (in your design).
Here is a working C#/Python code pair. First C# part:
static string encrypt(string clearText = "")
{
if (clearText == null)
{
clearText = "";
}
string EncryptionKey = "****";
byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }, 100000, HashAlgorithmName.SHA1);
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
encryptor.Mode = CipherMode.CBC;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
About this C# code:
By default Rfc2898DeriveBytes uses SHA1 and only 1000 rounds. My suggestion is that you should use at least 100,000. I have seen code apps that use 1,000,000 rounds. You can change hash too if you like, but number of rounds is more important.
Specify mode too. Even though it uses CBC by default, I think it is better to specify it.
Since C# uses key length to select AES algorithm, this code uses AES-256.
Now Python part:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
def Decryptstr(self, text):
try:
if text is None:
return
else:
backend = default_backend()
EncryptionKey = "****"
salt = bytes([ 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 ])
kdf = PBKDF2HMAC(algorithm=hashes.SHA1(),length=48,salt=salt,iterations=100000,backend=backend)
key_bytes = kdf.derive(bytes(EncryptionKey, 'utf-8'))
key = key_bytes[0:32]
iv = key_bytes[32:]
cipherbytes = base64.b64decode(text)
cipher = AES.new(key, AES.MODE_CBC, iv)
password = cipher.decrypt(cipherbytes).decode('utf-8')
print(password)
return password
except Exception as err:
print(err)
As you see, I used another PBKDF2HMAC library. I used it to create 48 bytes and used first 32 as Key and last 16 bytes as IV.

Invalid length for a Base-64 char array error

As the title says, I am getting:
Invalid length for a Base-64 char array.
So what I am doing is that i construct the email for delivery using the below method:
smsg += "<br><b>To complete your registration, verify your email</b>" + "<br>HERE!";
The Encrypt method looks like this:
private static string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
Here is what the HTML looks like in hotmail:
http://localhost:30850/Activation.aspx?username=9mQkc5vEebsl2Qg6hbxL+r3KVNhOEsig32oP6eb6rd0=
On the receiving end, the Activation.aspx.cs page has the line:
String username = Request.QueryString["username"].ToString();
Label1.Text = Decrypt(username);
And also the Decryption Method:
private string Decrypt(string cipherText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
So basically when I input username like foe example Jonathan it have no problem displaying Jonathan on the receiving end label. However, if i input anything that is not a multiple of 4 i get error. I understand that Base64 takes in multiple of 4, if it has 7 characters it will add space to it. Is there any solution to this? Thank you very much.
The base64 username string is padded with an '=' at the end; this is ignored when the URL query string is being interpreted. ie:
username => "9mQkc5vEebsl2Qg6hbxL+r3KVNhOEsig32oP6eb6rd0="
becomes:
username => 9mQkc5vEebsl2Qg6hbxL+r3KVNhOEsig32oP6eb6rd0
in the request handler.
You need to URL encode the string before using it in a URL.
Default set of Base64 characters is not safe to use in Url, especially + (space) and = (name/value separator for query params).
You can use modified set (manually replace some characters with other once) or carefully encode your data to make sure each character is preserved (+ in particular as ASP.Net treats it as space).
See Base64 on Wikipedia for links to specifications and Passing base64 encoded strings in URL for similar question in PHP.

AES encrypt in c# decrypt in T-SQL

I have written the following code to decrypt some sensitive data, in most of the cases i need to query data using T-SQL where i can't decrypt the the data that is encrypted by this code. so my question is this how can i write a function in T-SQL that work the same way as like it work in C#, I will consume that in Stored procedures.
thanks in Advance
Encryption Function:
public static string Encrypt(string text)
{
if (string.IsNullOrEmpty(EncryptionKey))
return string.Empty;
if (string.IsNullOrEmpty(text))
return string.Empty;
var clearBytes = Encoding.Unicode.GetBytes(text);
using (var encryptor = Aes.Create())
{
var pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[]
{
0x49,
0x76,
0x61,
0x6e,
0x20,
0x4d,
0x65,
0x64,
0x76,
0x65,
0x64,
0x65,
0x76
});
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
}
text = Convert.ToBase64String(ms.ToArray());
}
}
return text;
}
Decryption Function:
public static string Decrypt(string text)
{
if (string.IsNullOrEmpty(EncryptionKey))
return string.Empty;
if (string.IsNullOrEmpty(text))
return string.Empty;
var cipherBytes = Convert.FromBase64String(text);
using (var encryptor = Aes.Create())
{
var pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[]
{
0x49,
0x76,
0x61,
0x6e,
0x20,
0x4d,
0x65,
0x64,
0x76,
0x65,
0x64,
0x65,
0x76
});
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
}
text = Encoding.Unicode.GetString(ms.ToArray());
}
}
return text;
}
You can create a CLR UDF in SQL Server.
Refer following links for more info:
http://blog.sqlauthority.com/2008/10/19/sql-server-introduction-to-clr-simple-example-of-clr-stored-procedure/
https://msdn.microsoft.com/en-us/library/w2kae45k(v=vs.90).aspx

Corresponding T-SQL to perform same encryption/decryption as C# code

Could anyone provide an example of performing exactly the same encryption/decryption as the C# code below, but with T-SQL?
The below functions are used to encrypt/decrypt given strings for later storage in a database. But I'm just curious to know whether there is a T-SQL-way of doing the exact same thing.
Note: The value of the string variable "EncryptionKey" is made up for this specific purpose
private string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
private string Decrypt(string cipherText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}

Categories

Resources