|
1 | | -/* Copyright (C) 2014-2016 Tal Aloni <[email protected]>. All rights reserved. |
| 1 | +/* Copyright (C) 2014-2019 Tal Aloni <[email protected]>. All rights reserved. |
2 | 2 | * |
3 | 3 | * You can redistribute this program and/or modify it under the terms of |
4 | 4 | * the GNU Lesser Public License as published by the Free Software Foundation, |
5 | 5 | * either version 3 of the License, or (at your option) any later version. |
6 | 6 | */ |
7 | 7 | using System; |
8 | 8 | using System.Collections.Generic; |
| 9 | +using System.Globalization; |
9 | 10 | using System.IO; |
10 | 11 | using System.Runtime.InteropServices; |
11 | 12 | using System.Text; |
@@ -371,11 +372,45 @@ public static string GetDeviceSerialNumber(SafeFileHandle hDevice) |
371 | 372 | { |
372 | 373 | int offset = (int)deviceDescriptor.SerialNumberOffset - Marshal.SizeOf(deviceDescriptor); |
373 | 374 | string serialNumber = ByteReader.ReadNullTerminatedAnsiString(deviceDescriptor.RawDeviceProperties, offset); |
374 | | - return serialNumber.Trim(); |
| 375 | + return DecodeDeviceSerialNumber(serialNumber.Trim()); |
375 | 376 | } |
376 | 377 | return String.Empty; |
377 | 378 | } |
378 | 379 |
|
| 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 | + |
379 | 414 | public static STORAGE_DEVICE_DESCRIPTOR GetDeviceDescriptor(SafeFileHandle hDevice) |
380 | 415 | { |
381 | 416 | const int StorageDeviceProperty = 0; |
|
0 commit comments