Possible to encrypt/decrypt field value to save to SQL database in .NET?

+1 vote
asked Mar 1, 2016 by Rebex KB (8,210 points)

I am on the trial for your products, including the Rebex Security module.

Is it possible to simply encrypt/decrypt a field to be stored in a SQL database?

I have a string value and want to encrypt it and then store it in a data column. If so, a sample encrypt/decrypt code in VB.net would be helpful.

Also, what format would I use for the database column (varchar, etc?)

Thanks for any help!

1 Answer

0 votes
answered Mar 1, 2016 by Tomas Knopp (58,580 points)
edited Mar 1, 2016 by Tomas Knopp
Best answer

Although we plan to add it, the Rebex Security does not have a dedicated API for ecnrypting strings yet. So for now please use the Stream based overrides of the FileEncryption.Encrypt and Decrypt methods.

Here is a sample code that encrypts a string and converts the result to BASE64 so that you can safely save it as varchar to your SQL database. Just download the free trial of Rebex Security and give this code a try:

Dim dataIn As String = "string to be encrypted"

' feed the string into memory stream - choose preferred encoding, UTF-8 is good choice *
Dim bytes As Byte() = Encoding.UTF8.GetBytes(dataIn)
Dim memoryStreamIn = New MemoryStream(bytes)

Dim memoryStreamEncrypted = New MemoryStream()
Dim memoryStreamOut = New MemoryStream()

Dim encryption As New FileEncryption()
encryption.EncryptionAlgorithm = FileEncryptionAlgorithm.TripleDesCbc
encryption.SetPassword("your secret password")

' encrypt
encryption.Encrypt(memoryStreamIn, memoryStreamEncrypted)

' result of encryption is array of bytes
Dim result As Byte() = memoryStreamEncrypted.ToArray()
' convert the bytest to base64 string, so that you can safely save it to varchar in your SQL database
Dim base64result As String = Convert.ToBase64String(result) 'save this to your DB

' for decrypting later - feed the byte array into memory stream - decode from base64 first
Dim memoryStreamEnc = New MemoryStream(Convert.FromBase64String(base64result))
' and decrypt
encryption.Decrypt(memoryStreamEnc, memoryStreamOut)

Dim dataOut As String = Encoding.UTF8.GetString(memoryStreamOut.ToArray()) ' use the same encoding as in the first step *