1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
|
/*=========================================================================
Program: DICOM for VTK
Copyright (c) 2012-2024 David Gobbi
All rights reserved.
See Copyright.txt or http://dgobbi.github.io/bsd3.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDICOMUIDGenerator.h"
#include "vtkDICOMFile.h"
#include "vtkDICOMUtilities.h"
#include "vtkObjectFactory.h"
#include "vtkStringArray.h"
#include <string.h>
// needed for random number generation and time
#ifdef _WIN32
#include <windows.h>
#ifndef DICOM_DEPRECATE_WINXP
#include <wincrypt.h>
#else
#include <bcrypt.h>
#endif
#endif
vtkStandardNewMacro(vtkDICOMUIDGenerator);
vtkDICOMUIDGenerator *vtkDICOMUIDGenerator::Default;
//----------------------------------------------------------------------------
// A helper class to delete static variables when program exits.
static unsigned int vtkDICOMUIDGeneratorInitializerCounter;
// Perform initialization of static variables.
vtkDICOMUIDGeneratorInitializer::vtkDICOMUIDGeneratorInitializer()
{
if (vtkDICOMUIDGeneratorInitializerCounter++ == 0)
{
vtkDICOMUIDGenerator::Default = vtkDICOMUIDGenerator::New();
}
}
// Perform cleanup of static variables.
vtkDICOMUIDGeneratorInitializer::~vtkDICOMUIDGeneratorInitializer()
{
if (--vtkDICOMUIDGeneratorInitializerCounter == 0)
{
if (vtkDICOMUIDGenerator::Default)
{
vtkDICOMUIDGenerator::Default->Delete();
}
}
}
//----------------------------------------------------------------------------
vtkDICOMUIDGenerator::vtkDICOMUIDGenerator()
{
this->UIDPrefix = nullptr;
}
//----------------------------------------------------------------------------
vtkDICOMUIDGenerator::~vtkDICOMUIDGenerator()
{
}
//----------------------------------------------------------------------------
void vtkDICOMUIDGenerator::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "UIDPrefix: "
<< (this->UIDPrefix ? this->UIDPrefix : "(NULL)") << "\n";
}
//----------------------------------------------------------------------------
const char *vtkDICOMUIDGenerator::GetUIDPrefix()
{
const char *prefix = this->UIDPrefix;
if (prefix == nullptr)
{
prefix = vtkDICOMUtilities::GetUIDPrefix();
}
return prefix;
}
//----------------------------------------------------------------------------
void vtkDICOMUIDGenerator::SetUIDPrefix(const char *uid)
{
if (uid)
{
this->UIDPrefix = this->UIDPrefixStore;
strncpy(this->UIDPrefix, uid, 63);
this->UIDPrefix[63] = '\0';
}
else
{
this->UIDPrefix = nullptr;
}
}
//----------------------------------------------------------------------------
namespace {
// divide a hexadecimal string by 10 and return the remainder,
// this is a helper function for converting a long hex string
// (a uuid) into a decimal string (for a uid)
int vtkDivideHexStringBy10(char *value)
{
char *cp = value;
// convert hex string to binary
unsigned int x = 0;
while (*cp != '\0')
{
// skip any hyphens
if (*cp == '-')
{
cp++;
continue;
}
// convert hex digit to a nibble
unsigned int d = *cp;
if ((d -= '0') > 9)
{
if ((d -= ('A' - '0' - 10)) > 15)
{
d -= ('a' - 'A');
}
}
// append the nibble
x <<= 4;
x += d;
// divide by 10
unsigned int y = (10 << 3);
unsigned int z = 0;
int i;
for (i = 0; i < 4; i++)
{
z <<= 1;
int nx = x - y;
if (nx >= 0)
{
x = nx;
z++;
}
y >>= 1;
}
// convert quotient to new hex digit
if ((z += '0') > '9')
{
z += ('A' - '0' - 10);
}
*cp++ = static_cast<char>(z);
}
// return the remainder
return static_cast<int>(x);
}
// convert a hex uuid string to a decimal uid string, the
// supplied uid will be at most 1.5 times as long as the uuid
void vtkConvertHexToDecimal(const char *uuid, char *uid)
{
// max characters in a uuid and uid
const unsigned int uuidlen = 36;
const unsigned int uidlen = 64;
char x[uuidlen + 4];
char y[uidlen + 4];
if (uuid[0] == '0' && uuid[1] == 'x')
{
uuid += 2;
}
strncpy(x, uuid, uuidlen);
x[uuidlen] = '\0';
char *cp = y + uidlen;
*cp = '\0';
char *dp = x;
do
{
*(--cp) = vtkDivideHexStringBy10(x) + '0';
// remove any leading zeros
while (*dp == '0' || *dp == '-')
{
dp++;
}
}
while (*dp != '\0');
// copy out the result
strcpy(uid, cp);
}
// convert a byte into two hexadecimal digits, used to convert raw
// binary into a hexadecimal string one byte at a time
inline void vtkGenerateHexDigits(unsigned char y, char cp[2])
{
unsigned int z = (y >> 4);
for (int j = 0; j < 2; j++)
{
if ((z += '0') > '9')
{
z += ('A' - '0' - 10);
}
cp[j] = static_cast<char>(z);
z = (y & 0x0F);
}
}
// convert n raw bytes into 2*n hexadecimal digits
void vtkConvertBytesToHex(const unsigned char *bytes, size_t n, char *cp)
{
for (size_t i = 0; i < n; i++)
{
vtkGenerateHexDigits(*bytes, cp);
bytes++;
cp += 2;
}
*cp = '\0';
}
// generate a 36-character uuid from a 128-bit random number
// (the supplied uuid pointer must have 37 bytes of available space)
void vtkConvertRandomToUUID(const unsigned char bytes[16], char *uuid)
{
// copy it so that we can modify it
char r[16];
for (int j = 0; j < 16; j++)
{
r[j] = bytes[j];
}
// set bits to show that this is a version 4 uuid
r[6] = ((r[6] & 0x0f) | 0x40);
// set the uuid variant to "0b10" (0b == binary)
r[8] = ((r[8] & 0x3f) | 0x80);
// convert the uuid into hexadecimal text
char *cp = uuid;
for (unsigned int i = 0; i < 16; i++)
{
// add hyphens to the uuid (just to be pedantic)
if (i == 4 || i == 6 || i == 8 || i == 10)
{
*cp++ = '-';
}
vtkGenerateHexDigits(r[i], cp);
cp += 2;
}
*cp = '\0';
}
// convert a 36-character uuid to a 44-character uid
void vtkConvertUUIDToUID(const char *uuid, char *uid)
{
memcpy(uid, "2.25.", 5);
vtkConvertHexToDecimal(uuid, uid + 5);
}
// read from the random number generator, cryptographic quality random
// numbers are needed to ensure uniqueness of the generated uids
void vtkGenerateRandomBytes(unsigned char *bytes, vtkIdType n)
{
int r = 0;
#ifdef _WIN32
#ifndef DICOM_DEPRECATE_WINXP
// legacy interface (Windows XP and later)
HCRYPTPROV hProv;
r = CryptAcquireContext(&hProv, nullptr, nullptr, PROV_RSA_FULL,
CRYPT_SILENT | CRYPT_VERIFYCONTEXT);
if (r == 0 && GetLastError() == NTE_BAD_KEYSET)
{
r = CryptAcquireContext(&hProv, nullptr, nullptr, PROV_RSA_FULL,
CRYPT_SILENT | CRYPT_NEWKEYSET);
}
if (r != 0)
{
r = CryptGenRandom(hProv, n, reinterpret_cast<BYTE *>(bytes));
CryptReleaseContext(hProv, 0);
}
#else
// modern interface (Windows Vista and later), requires bcrypt.lib
BCRYPT_ALG_HANDLE hProv;
ULONG dwFlags = 0;
if (BCryptOpenAlgorithmProvider(&hProv, BCRYPT_RNG_ALGORITHM, nullptr, 0) != 0)
{
// couldn't open algorithm, fall back to default
hProv = 0;
dwFlags = BCRYPT_USE_SYSTEM_PREFERRED_RNG;
}
if (BCryptGenRandom(hProv, reinterpret_cast<BYTE *>(bytes), n, dwFlags) == 0)
{
// success!
r = 1;
}
if (dwFlags == 0)
{
BCryptCloseAlgorithmProvider(hProv, 0);
}
#endif
#else
// use /dev/urandom, because /dev/random is too slow
vtkDICOMFile infile("/dev/urandom", vtkDICOMFile::In);
if (infile.GetError() == 0)
{
size_t m = infile.Read(bytes, n);
r = (m == static_cast<size_t>(n));
infile.Close();
}
#endif
if (r == 0)
{
memset(bytes, '\0', n);
vtkGenericWarningMacro(
"vtkDICOMUIDGenerator::GenerateUID() failed to read from "
"the random number generator");
}
}
// generate a single-digit numerical prefix for UIDs that identifies the
// purpose of the uid (this is just for convenience in recognizing the
// uid types, it is not suggested by the DICOM standard)
char vtkDICOMTagToDigit(vtkDICOMTag tag)
{
char d = '1';
if (tag == DC::SOPInstanceUID ||
tag == DC::MediaStorageSOPInstanceUID)
{
d = '2';
}
else if (tag == DC::SeriesInstanceUID ||
tag == DC::ConcatenationUID)
{
d = '3';
}
else if (tag == DC::StudyInstanceUID)
{
d = '4';
}
else if (tag == DC::FrameOfReferenceUID ||
tag == DC::VolumeFrameOfReferenceUID ||
tag == DC::SourceFrameOfReferenceUID ||
tag == DC::SynchronizationFrameOfReferenceUID ||
tag == DC::TableFrameOfReferenceUID)
{
d = '5';
}
return d;
}
// get the number of random bytes to generate after this prefix,
// to ensure that we don't go over the 64 byte limit for UID length
vtkIdType vtkRandomBytesForPrefix(const char *prefix)
{
size_t n = strlen(prefix);
if (n > 0 && prefix[n-1] != '.')
{
n++;
}
n = 64 - n;
vtkIdType m = 0;
if (n > 40)
{
m = 16; // use 128 bit random number
}
else
{
m = 12; // use 96 bit random number
}
return m;
}
// generate a prefixed UID using the provided random bytes
void vtkGeneratePrefixedUID(
const unsigned char *r, vtkIdType m, const char *prefix, char d,
char uid[64])
{
size_t i = 0;
while (*prefix != '\0' && i < 62)
{
uid[i++] = *prefix++;
}
if (i > 0 && i < 62 && uid[i-1] != '.')
{
uid[i++] = '.';
}
char hexs[36];
vtkConvertBytesToHex(r, m, hexs);
char decs[40];
vtkConvertHexToDecimal(hexs, decs);
// generate the leading digit as the UID type
if (d >= '1' && d <= '9')
{
// decimal digits required to store an integer with N-1 bytes
static const int maxDigits[16] = {
3, 5, 8, 10, 13, 15, 17, 20, 22, 25, 27, 29, 32, 34, 37, 39
};
uid[i++] = d;
// add zeros so all uids will be the same length
size_t n = maxDigits[(m-1) & 0x0f];
for (size_t l = strlen(decs); l < n && i < 63; l++)
{
uid[i++] = '0';
}
}
const char *cp = decs;
while (i < 63 && *cp != '\0')
{
uid[i++] = *cp++;
}
while (i < 64)
{
uid[i++] = '\0';
}
}
} // end anonymous namespace
//----------------------------------------------------------------------------
std::string vtkDICOMUIDGenerator::GenerateUID(vtkDICOMTag tag)
{
const char *prefix = this->GetUIDPrefix();
char uid[64];
if (prefix[0] == '\0' ||
(prefix[0] == '2' && prefix[1] == '.' && prefix[2] == '2' &&
prefix[3] == '5' && (prefix[4] == '.' || prefix[4] == '\0')))
{
// generate a 128-bit random number
unsigned char r[16];
vtkGenerateRandomBytes(r, 16);
// convert to a hexadecimal uuid
char uuid[40];
vtkConvertRandomToUUID(r, uuid);
// convert the hexadedimal uuid into a DICOM UID with root 2.25
vtkConvertUUIDToUID(uuid, uid);
}
else
{
// after prefix, add a "UID type" digit followed by random digits
unsigned char r[16];
vtkIdType m = vtkRandomBytesForPrefix(prefix);
vtkGenerateRandomBytes(r, m);
char d = vtkDICOMTagToDigit(tag);
vtkGeneratePrefixedUID(r, m, prefix, d, uid);
}
return uid;
}
//----------------------------------------------------------------------------
void vtkDICOMUIDGenerator::GenerateUIDs(vtkDICOMTag tag, vtkStringArray *uids)
{
const char *prefix = this->GetUIDPrefix();
bool useUUIDForUID =
(prefix[0] == '\0' ||
(prefix[0] == '2' && prefix[1] == '.' && prefix[2] == '2' &&
prefix[3] == '5' && (prefix[4] == '.' || prefix[4] == '\0')));
vtkIdType m = 16;
char d = '0';
if (!useUUIDForUID)
{
m = vtkRandomBytesForPrefix(prefix);
d = vtkDICOMTagToDigit(tag);
}
// read from random number generator
vtkIdType n = uids->GetNumberOfValues();
unsigned char *r = new unsigned char[n*m];
vtkGenerateRandomBytes(r, n*m);
for (vtkIdType i = 0; i < n; i++)
{
char uid[64];
if (useUUIDForUID)
{
char uuid[40];
vtkConvertRandomToUUID(r + i*m, uuid);
vtkConvertUUIDToUID(uuid, uid);
}
else
{
vtkGeneratePrefixedUID(r + i*m, m, prefix, d, uid);
}
// put uids into the array in order (simple insertion sort)
vtkIdType j = 0;
for (; j < i; j++)
{
if (vtkDICOMUtilities::CompareUIDs(uids->GetValue(j).c_str(), uid) > 0)
{
break;
}
}
for (vtkIdType k = i; k > j; --k)
{
uids->SetValue(k, uids->GetValue(k - 1));
}
uids->SetValue(j, uid);
}
delete [] r;
}
//----------------------------------------------------------------------------
void vtkDICOMUIDGenerator::SetDefault(vtkDICOMUIDGenerator *uidgen)
{
if (uidgen != vtkDICOMUIDGenerator::Default)
{
if (vtkDICOMUIDGenerator::Default)
{
vtkDICOMUIDGenerator::Default->Delete();
}
if (uidgen)
{
uidgen->Register(nullptr);
}
else
{
uidgen = vtkDICOMUIDGenerator::New();
}
vtkDICOMUIDGenerator::Default = uidgen;
}
}
|