WALTER | Workable Algorithms for Location-aware Transmission, Encryption Response

StringExtensions..::..ToSqlBinaryString Method

Converts a byte array to a T-SQL compatible hexadecimal string.

Namespace:  System
Assembly:  Walter (in Walter.dll)

Syntax


public static string ToSqlBinaryString(
	byte[] bytes
)

Parameters

bytes
Type: array<Byte>[]()[][]
The byte array to convert.

Return Value

A hexadecimal string representation of the byte array.

Examples


sometimes it can be usefull to be able to generate data like SQL server needs it. The bellow code shows you how to take a string and convert it to a byte array, then take the byte array and show the value as varbinary
Generate string that can be used in a TSQL statement
// Sample to demonstrate GDPR-compliant encryption of sensitive data using deterministic encryption
// for storage in a third-party hosted SQL server.
        ///
// Define the company name to be encrypted.
string companyName = "Undefined Corp";
        ///
// Create an instance of the symmetric encryption service with a secure password and salt.
// Note: In a production environment, securely manage the password and salt, avoiding hardcoded values.
var encryptionService = new Walter.Cypher.DeterministicEncryption(
password: "My $ectet Pa$w0rd",
salt: "123456789+*ç%&/"
);
        ///
// Encrypt the company name into a byte array.
byte[] encryptedBytes = encryptionService.Encrypt(companyName.ToBytes());
        ///
// Prepare the T-SQL command for data insertion, using the encrypted company name.
var tsql = @$"
declare @UndefinedCorp Varbinary(64) = {encryptedBytes.ToSqlBinaryString()};
declare @checksum int = CHECKSUM(@UndefinedCorp);
        ///
// Check for the existence of the company and insert if not present.
if not exists(select * from [dbo].[Companies] where [CompanyName] = @UndefinedCorp and [cs_CompanyName] = @checksum)
BEGIN
INSERT [dbo].[Companies] ([CompanyName],[cs_CompanyName],[TrueUpDays],[AutoInvoice],[ApplicableLicenseExcempt])
Values(@UndefinedCorp, @checksum, -1, 0, 1);
END
";
        ///
// Execute the T-SQL command to store the encrypted data.
using var con = new SqlConnection(config.GetConnectionString("Billing"));
using var cmd = con.CreateCommand();
cmd.CommandText = tsql;
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();