Skip to content

Commit 52c3cf0

Browse files
committed
PhysicalDiskControl: Decode HEX encoded disk serial number
1 parent 4b1a459 commit 52c3cf0

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

DiskAccessLibrary/Win32/Utilities/PhysicalDiskControl.cs

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
/* Copyright (C) 2014-2016 Tal Aloni <[email protected]>. All rights reserved.
1+
/* Copyright (C) 2014-2019 Tal Aloni <[email protected]>. All rights reserved.
22
*
33
* You can redistribute this program and/or modify it under the terms of
44
* the GNU Lesser Public License as published by the Free Software Foundation,
55
* either version 3 of the License, or (at your option) any later version.
66
*/
77
using System;
88
using System.Collections.Generic;
9+
using System.Globalization;
910
using System.IO;
1011
using System.Runtime.InteropServices;
1112
using System.Text;
@@ -371,11 +372,45 @@ public static string GetDeviceSerialNumber(SafeFileHandle hDevice)
371372
{
372373
int offset = (int)deviceDescriptor.SerialNumberOffset - Marshal.SizeOf(deviceDescriptor);
373374
string serialNumber = ByteReader.ReadNullTerminatedAnsiString(deviceDescriptor.RawDeviceProperties, offset);
374-
return serialNumber.Trim();
375+
return DecodeDeviceSerialNumber(serialNumber.Trim());
375376
}
376377
return String.Empty;
377378
}
378379

380+
/// <summary>
381+
/// Serial number may be encoded in HEX (with each two characters swapped)
382+
/// </summary>
383+
private static string DecodeDeviceSerialNumber(string serialNumber)
384+
{
385+
if (serialNumber.Length % 2 == 0)
386+
{
387+
StringBuilder builder = new StringBuilder();
388+
for (int index = 0; index < serialNumber.Length; index += 2)
389+
{
390+
short character;
391+
if (!Int16.TryParse(serialNumber.Substring(index, 2), NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture.NumberFormat, out character))
392+
{
393+
// This is not an HEX string
394+
return serialNumber;
395+
}
396+
397+
// Each two characters are swapped
398+
if (builder.Length % 2 == 1)
399+
{
400+
builder.Insert(builder.Length - 1, (char)character);
401+
}
402+
else
403+
{
404+
builder.Append((char)character);
405+
}
406+
}
407+
408+
return builder.ToString().Trim();
409+
}
410+
411+
return serialNumber;
412+
}
413+
379414
public static STORAGE_DEVICE_DESCRIPTOR GetDeviceDescriptor(SafeFileHandle hDevice)
380415
{
381416
const int StorageDeviceProperty = 0;

0 commit comments

Comments
 (0)