Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrypt Data From SQL Server 2008 R2

I need some help translating this procedure (see below) to Entity Framework 4.0. Does anyone have any suggestions of how to port this over. The target project includes; Silverlight 4, WCF RIA Services, EF 4.0, SQL Server 2008 R2.

The only requirement I have is that it will need to be placed in the managed code and not in a stored procedure.

    Try 
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.Text;
        string sql = "OPEN SYMMETRIC KEY " + this._encryptKey;
        sql += " DECRYPTION BY CERTIFICATE " + this._encrpytCert; 
        sql += " SELECT TOP (1) CONVERT(nvarchar(50),DECRYPTBYKEY(Field1)) AS Name";
        sql += " FROM Table3"; 
        sql += " ORDER BY CONVERT(nvarchar(50),DECRYPTBYKEY(Field1))";
        cmd.CommandText = sql;
        Name = (String)cmd.ExecuteScalar();
        bRtn = false;
    }
        catch (Exception ex)
    {
        System.Diagnostics.Debug.Print(ex.ToString());
    }

Please let me know how I should set this up and thanks!

like image 935
Dave Navarro Avatar asked Jun 30 '26 06:06

Dave Navarro


1 Answers

You could run the query via the Entity Framework and get strongly typed results by using the ObjectContext.ExecuteStoreQuery<>() function (see this example).

Unfortunately, however, I don't think there's any way to get around having to generate the T-SQL statement yourself. While you can use many of SQL Server's functions in Linq-to-Entities queries via the SqlFuntions class, there is no function that translates SQL Server's DECRYPTBYKEY function, not to mention the fact that the Entity Framework won't generate a statement to open the key.

like image 117
Ryan Avatar answered Jul 01 '26 21:07

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!