Quantcast
Channel: Rebex Q&A Forum - Recent questions and answers
Viewing all articles
Browse latest Browse all 3860

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

$
0
0

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 *

Viewing all articles
Browse latest Browse all 3860

Trending Articles