سؤال

I had a datetime column in a SQL Server table. We needed to encrypt it. So, I cast it to a varbinary in SSMS. I simply edited the table, set the datetime type to varbinary and let SQL Server convert it. Following that, I wrote throwaway C# code to pull it out, encrypt it (using the encryption algorithms in our middle layer) and push it back into the database. Did the same for some nvarchars for names and other string types.

When I pull out the encrypted data (using NHibernate), I pull the varbinary into a byte[] and decrypt it. I then try to convert it back to the original value.

The nvarchar-as-varbinary columns convert fine; for example, I get may names back.

return Encoding.Unicode.GetString(source.FirstName);

However, I'm having a hard time converting the dates back into their original form. I'm using:

long ticks = BitConverter.ToInt64(source.DateOfBirth, 0);
return new DateTime?(new DateTime(1980, 1, 1).AddMilliseconds(ticks));

This does not seem to return the date properly. What's the correct way to cast it back to a DateTime?

Update: A sample value was requested. A datetime that was originally 1/1/1901, when decrypted, yields a byte[] where byte[2]=1 and byte[3]=109, and all others are 0. Another datetime '1941-04-26' yields byte[2]=58 and byte[3]=242 upon decryption.

هل كانت مفيدة؟

المحلول

The date is stored as the number of days since 1900-01-01.

Example:

byte[] data = {0,0,58,242};

if (BitConverter.IsLittleEndian) {
  Array.Reverse(data);
}
int days = BitConverter.ToInt32(data, 0);
DateTime date = new DateTime(1900, 1, 1).AddDays(days);

Console.WriteLine(date);

Output:

1941-04-26 00:00:00

نصائح أخرى

Int64 ticks = BitConverter.ToInt64(source.DateOfBirth, 0);
DateTime dt = DateTime.FromBinary(ticks);

After you decrypt the varbinary data, can you get the string value and run it through SSMS? Something like:

SELECT CONVERT(datetime, 0x0000A149016D7FD9)

What does your varbinary data look like in SQL Server? I suspect something is being messed up in translations.

Good luck.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top