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 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.IdentityModel
{
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IdentityModel.Tokens;
using System.IdentityModel.Selectors;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
sealed class SignedXml : ISignatureValueSecurityElement
{
internal const string DefaultPrefix = XmlSignatureStrings.Prefix;
SecurityTokenSerializer tokenSerializer;
readonly Signature signature;
TransformFactory transformFactory;
DictionaryManager dictionaryManager;
public SignedXml(DictionaryManager dictionaryManager, SecurityTokenSerializer tokenSerializer)
: this(new StandardSignedInfo(dictionaryManager), dictionaryManager, tokenSerializer)
{
}
internal SignedXml(SignedInfo signedInfo, DictionaryManager dictionaryManager, SecurityTokenSerializer tokenSerializer)
{
if (signedInfo == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("signedInfo"));
}
if (dictionaryManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dictionaryManager");
}
if (tokenSerializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenSerializer");
}
this.transformFactory = StandardTransformFactory.Instance;
this.tokenSerializer = tokenSerializer;
this.signature = new Signature(this, signedInfo);
this.dictionaryManager = dictionaryManager;
}
public bool HasId
{
get { return true; }
}
public string Id
{
get { return this.signature.Id; }
set { this.signature.Id = value; }
}
public SecurityTokenSerializer SecurityTokenSerializer
{
get { return this.tokenSerializer; }
}
public Signature Signature
{
get { return this.signature; }
}
public TransformFactory TransformFactory
{
get { return this.transformFactory; }
set { this.transformFactory = value; }
}
void ComputeSignature(HashAlgorithm hash, AsymmetricSignatureFormatter formatter, string signatureMethod)
{
this.Signature.SignedInfo.ComputeReferenceDigests();
this.Signature.SignedInfo.ComputeHash(hash);
byte[] signature;
if (SecurityUtils.RequiresFipsCompliance && signatureMethod == SecurityAlgorithms.RsaSha256Signature)
{
// This is to avoid the RSAPKCS1SignatureFormatter.CreateSignature from using SHA256Managed (non-FIPS-Compliant).
// Hence we precompute the hash using SHA256CSP (FIPS compliant) and pass it to method.
// NOTE: RSAPKCS1SignatureFormatter does not understand SHA256CSP inherently and hence this workaround.
formatter.SetHashAlgorithm("SHA256");
signature = formatter.CreateSignature(hash.Hash);
}
else
{
signature = formatter.CreateSignature(hash);
}
this.Signature.SetSignatureValue(signature);
}
void ComputeSignature(KeyedHashAlgorithm hash)
{
this.Signature.SignedInfo.ComputeReferenceDigests();
this.Signature.SignedInfo.ComputeHash(hash);
byte[] signature = hash.Hash;
this.Signature.SetSignatureValue(signature);
}
public void ComputeSignature(SecurityKey signingKey)
{
string signatureMethod = this.Signature.SignedInfo.SignatureMethod;
SymmetricSecurityKey symmetricKey = signingKey as SymmetricSecurityKey;
if (symmetricKey != null)
{
using (KeyedHashAlgorithm algorithm = symmetricKey.GetKeyedHashAlgorithm(signatureMethod))
{
if (algorithm == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UnableToCreateKeyedHashAlgorithm, symmetricKey, signatureMethod)));
}
ComputeSignature(algorithm);
}
}
else
{
AsymmetricSecurityKey asymmetricKey = signingKey as AsymmetricSecurityKey;
if (asymmetricKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UnknownICryptoType, signingKey)));
}
using (HashAlgorithm hash = asymmetricKey.GetHashAlgorithmForSignature(signatureMethod))
{
if (hash == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UnableToCreateHashAlgorithmFromAsymmetricCrypto, signatureMethod, asymmetricKey)));
}
AsymmetricSignatureFormatter formatter = asymmetricKey.GetSignatureFormatter(signatureMethod);
if (formatter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UnableToCreateSignatureFormatterFromAsymmetricCrypto, signatureMethod, asymmetricKey)));
}
ComputeSignature(hash, formatter, signatureMethod);
}
}
}
public void CompleteSignatureVerification()
{
this.Signature.SignedInfo.EnsureAllReferencesVerified();
}
public void EnsureDigestValidity(string id, object resolvedXmlSource)
{
this.Signature.SignedInfo.EnsureDigestValidity(id, resolvedXmlSource);
}
public bool EnsureDigestValidityIfIdMatches(string id, object resolvedXmlSource)
{
return this.Signature.SignedInfo.EnsureDigestValidityIfIdMatches(id, resolvedXmlSource);
}
public byte[] GetSignatureValue()
{
return this.Signature.GetSignatureBytes();
}
public void ReadFrom(XmlReader reader)
{
ReadFrom(XmlDictionaryReader.CreateDictionaryReader(reader));
}
public void ReadFrom(XmlDictionaryReader reader)
{
this.signature.ReadFrom(reader, this.dictionaryManager);
}
void VerifySignature(KeyedHashAlgorithm hash)
{
this.Signature.SignedInfo.ComputeHash(hash);
if (!CryptoHelper.IsEqual(hash.Hash, GetSignatureValue()))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.SignatureVerificationFailed)));
}
}
void VerifySignature(HashAlgorithm hash, AsymmetricSignatureDeformatter deformatter, string signatureMethod)
{
this.Signature.SignedInfo.ComputeHash(hash);
bool result;
if (SecurityUtils.RequiresFipsCompliance && signatureMethod == SecurityAlgorithms.RsaSha256Signature)
{
// This is to avoid the RSAPKCS1SignatureFormatter.VerifySignature from using SHA256Managed (non-FIPS-Compliant).
// Hence we precompute the hash using SHA256CSP (FIPS compliant) and pass it to method.
// NOTE: RSAPKCS1SignatureFormatter does not understand SHA256CSP inherently and hence this workaround.
deformatter.SetHashAlgorithm("SHA256");
result = deformatter.VerifySignature(hash.Hash, GetSignatureValue());
}
else
{
result = deformatter.VerifySignature(hash, GetSignatureValue());
}
if (!result)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.SignatureVerificationFailed)));
}
}
public void StartSignatureVerification(SecurityKey verificationKey)
{
string signatureMethod = this.Signature.SignedInfo.SignatureMethod;
SymmetricSecurityKey symmetricKey = verificationKey as SymmetricSecurityKey;
if (symmetricKey != null)
{
using (KeyedHashAlgorithm hash = symmetricKey.GetKeyedHashAlgorithm(signatureMethod))
{
if (hash == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(
SR.GetString(SR.UnableToCreateKeyedHashAlgorithmFromSymmetricCrypto, signatureMethod, symmetricKey)));
}
VerifySignature(hash);
}
}
else
{
AsymmetricSecurityKey asymmetricKey = verificationKey as AsymmetricSecurityKey;
if (asymmetricKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UnknownICryptoType, verificationKey)));
}
using (HashAlgorithm hash = asymmetricKey.GetHashAlgorithmForSignature(signatureMethod))
{
if (hash == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(
SR.GetString(SR.UnableToCreateHashAlgorithmFromAsymmetricCrypto, signatureMethod, asymmetricKey)));
}
AsymmetricSignatureDeformatter deformatter = asymmetricKey.GetSignatureDeformatter(signatureMethod);
if (deformatter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(
SR.GetString(SR.UnableToCreateSignatureDeformatterFromAsymmetricCrypto, signatureMethod, asymmetricKey)));
}
VerifySignature(hash, deformatter, signatureMethod);
}
}
}
public void WriteTo(XmlDictionaryWriter writer)
{
this.WriteTo(writer, this.dictionaryManager);
}
public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
this.signature.WriteTo(writer, dictionaryManager);
}
}
sealed class Signature
{
SignedXml signedXml;
string id;
SecurityKeyIdentifier keyIdentifier;
string prefix = SignedXml.DefaultPrefix;
readonly SignatureValueElement signatureValueElement = new SignatureValueElement();
readonly SignedInfo signedInfo;
public Signature(SignedXml signedXml, SignedInfo signedInfo)
{
this.signedXml = signedXml;
this.signedInfo = signedInfo;
}
public string Id
{
get { return this.id; }
set { this.id = value; }
}
public SecurityKeyIdentifier KeyIdentifier
{
get { return this.keyIdentifier; }
set { this.keyIdentifier = value; }
}
public SignedInfo SignedInfo
{
get { return this.signedInfo; }
}
public ISignatureValueSecurityElement SignatureValue
{
get { return this.signatureValueElement; }
}
public byte[] GetSignatureBytes()
{
return this.signatureValueElement.Value;
}
public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
{
reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.Signature, dictionaryManager.XmlSignatureDictionary.Namespace);
this.prefix = reader.Prefix;
this.Id = reader.GetAttribute(dictionaryManager.UtilityDictionary.IdAttribute, null);
reader.Read();
this.signedInfo.ReadFrom(reader, signedXml.TransformFactory, dictionaryManager);
this.signatureValueElement.ReadFrom(reader, dictionaryManager);
if (signedXml.SecurityTokenSerializer.CanReadKeyIdentifier(reader))
{
this.keyIdentifier = signedXml.SecurityTokenSerializer.ReadKeyIdentifier(reader);
}
reader.ReadEndElement(); // Signature
}
public void SetSignatureValue(byte[] signatureValue)
{
this.signatureValueElement.Value = signatureValue;
}
public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.Signature, dictionaryManager.XmlSignatureDictionary.Namespace);
if (this.id != null)
{
writer.WriteAttributeString(dictionaryManager.UtilityDictionary.IdAttribute, null, this.id);
}
this.signedInfo.WriteTo(writer, dictionaryManager);
this.signatureValueElement.WriteTo(writer, dictionaryManager);
if (this.keyIdentifier != null)
{
this.signedXml.SecurityTokenSerializer.WriteKeyIdentifier(writer, this.keyIdentifier);
}
writer.WriteEndElement(); // Signature
}
sealed class SignatureValueElement : ISignatureValueSecurityElement
{
string id;
string prefix = SignedXml.DefaultPrefix;
byte[] signatureValue;
string signatureText;
public bool HasId
{
get { return true; }
}
public string Id
{
get { return this.id; }
set { this.id = value; }
}
internal byte[] Value
{
get { return this.signatureValue; }
set
{
this.signatureValue = value;
this.signatureText = null;
}
}
public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
{
reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.SignatureValue, dictionaryManager.XmlSignatureDictionary.Namespace);
this.prefix = reader.Prefix;
this.Id = reader.GetAttribute(UtilityStrings.IdAttribute, null);
reader.Read();
this.signatureText = reader.ReadString();
this.signatureValue = System.Convert.FromBase64String(signatureText.Trim());
reader.ReadEndElement(); // SignatureValue
}
public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.SignatureValue, dictionaryManager.XmlSignatureDictionary.Namespace);
if (this.id != null)
{
writer.WriteAttributeString(dictionaryManager.UtilityDictionary.IdAttribute, null, this.id);
}
if (this.signatureText != null)
{
writer.WriteString(this.signatureText);
}
else
{
writer.WriteBase64(this.signatureValue, 0, this.signatureValue.Length);
}
writer.WriteEndElement(); // SignatureValue
}
byte[] ISignatureValueSecurityElement.GetSignatureValue()
{
return this.Value;
}
}
}
internal interface ISignatureReaderProvider
{
XmlDictionaryReader GetReader(object callbackContext);
}
abstract class SignedInfo : ISecurityElement
{
readonly ExclusiveCanonicalizationTransform canonicalizationMethodElement = new ExclusiveCanonicalizationTransform(true);
string id;
ElementWithAlgorithmAttribute signatureMethodElement;
SignatureResourcePool resourcePool;
DictionaryManager dictionaryManager;
MemoryStream canonicalStream;
ISignatureReaderProvider readerProvider;
object signatureReaderProviderCallbackContext;
bool sendSide = true;
protected SignedInfo(DictionaryManager dictionaryManager)
{
if (dictionaryManager == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dictionaryManager");
this.signatureMethodElement = new ElementWithAlgorithmAttribute(dictionaryManager.XmlSignatureDictionary.SignatureMethod);
this.dictionaryManager = dictionaryManager;
}
protected DictionaryManager DictionaryManager
{
get { return this.dictionaryManager; }
}
protected MemoryStream CanonicalStream
{
get { return this.canonicalStream; }
set { this.canonicalStream = value; }
}
protected bool SendSide
{
get { return this.sendSide; }
set { this.sendSide = value; }
}
public ISignatureReaderProvider ReaderProvider
{
get { return this.readerProvider; }
set { this.readerProvider = value; }
}
public object SignatureReaderProviderCallbackContext
{
get { return this.signatureReaderProviderCallbackContext; }
set { this.signatureReaderProviderCallbackContext = value; }
}
public string CanonicalizationMethod
{
get { return this.canonicalizationMethodElement.Algorithm; }
set
{
if (value != this.canonicalizationMethodElement.Algorithm)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedTransformAlgorithm)));
}
}
}
public XmlDictionaryString CanonicalizationMethodDictionaryString
{
set
{
if (value != null && value.Value != this.canonicalizationMethodElement.Algorithm)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedTransformAlgorithm)));
}
}
}
public bool HasId
{
get { return true; }
}
public string Id
{
get { return this.id; }
set { this.id = value; }
}
public abstract int ReferenceCount
{
get;
}
public string SignatureMethod
{
get { return this.signatureMethodElement.Algorithm; }
set { this.signatureMethodElement.Algorithm = value; }
}
public XmlDictionaryString SignatureMethodDictionaryString
{
get { return this.signatureMethodElement.AlgorithmDictionaryString; }
set { this.signatureMethodElement.AlgorithmDictionaryString = value; }
}
public SignatureResourcePool ResourcePool
{
get
{
if (this.resourcePool == null)
{
this.resourcePool = new SignatureResourcePool();
}
return this.resourcePool;
}
set
{
this.resourcePool = value;
}
}
public void ComputeHash(HashAlgorithm algorithm)
{
if ((this.CanonicalizationMethod != SecurityAlgorithms.ExclusiveC14n) && (this.CanonicalizationMethod != SecurityAlgorithms.ExclusiveC14nWithComments))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.UnsupportedTransformAlgorithm)));
}
HashStream hashStream = this.ResourcePool.TakeHashStream(algorithm);
ComputeHash(hashStream);
hashStream.FlushHash();
}
protected virtual void ComputeHash(HashStream hashStream)
{
if (this.sendSide)
{
XmlDictionaryWriter utf8Writer = this.ResourcePool.TakeUtf8Writer();
utf8Writer.StartCanonicalization(hashStream, false, null);
WriteTo(utf8Writer, this.dictionaryManager);
utf8Writer.EndCanonicalization();
}
else if (this.canonicalStream != null)
{
this.canonicalStream.WriteTo(hashStream);
}
else
{
if (this.readerProvider == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.InclusiveNamespacePrefixRequiresSignatureReader)));
XmlDictionaryReader signatureReader = this.readerProvider.GetReader(this.signatureReaderProviderCallbackContext);
DiagnosticUtility.DebugAssert(signatureReader != null, "Require a Signature reader to validate signature.");
if (!signatureReader.CanCanonicalize)
{
MemoryStream stream = new MemoryStream();
XmlDictionaryWriter bufferingWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, this.DictionaryManager.ParentDictionary);
string[] inclusivePrefix = GetInclusivePrefixes();
if (inclusivePrefix != null)
{
bufferingWriter.WriteStartElement("a");
for (int i = 0; i < inclusivePrefix.Length; ++i)
{
string ns = GetNamespaceForInclusivePrefix(inclusivePrefix[i]);
if (ns != null)
{
bufferingWriter.WriteXmlnsAttribute(inclusivePrefix[i], ns);
}
}
}
signatureReader.MoveToContent();
bufferingWriter.WriteNode(signatureReader, false);
if (inclusivePrefix != null)
bufferingWriter.WriteEndElement();
bufferingWriter.Flush();
byte[] buffer = stream.ToArray();
int bufferLength = (int)stream.Length;
bufferingWriter.Close();
signatureReader.Close();
// Create a reader around the buffering Stream.
signatureReader = XmlDictionaryReader.CreateBinaryReader(buffer, 0, bufferLength, this.DictionaryManager.ParentDictionary, XmlDictionaryReaderQuotas.Max);
if (inclusivePrefix != null)
signatureReader.ReadStartElement("a");
}
signatureReader.ReadStartElement(dictionaryManager.XmlSignatureDictionary.Signature, dictionaryManager.XmlSignatureDictionary.Namespace);
signatureReader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.SignedInfo, dictionaryManager.XmlSignatureDictionary.Namespace);
signatureReader.StartCanonicalization(hashStream, false, GetInclusivePrefixes());
signatureReader.Skip();
signatureReader.EndCanonicalization();
signatureReader.Close();
}
}
public abstract void ComputeReferenceDigests();
protected string[] GetInclusivePrefixes()
{
return this.canonicalizationMethodElement.GetInclusivePrefixes();
}
protected virtual string GetNamespaceForInclusivePrefix(string prefix)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public abstract void EnsureAllReferencesVerified();
public void EnsureDigestValidity(string id, object resolvedXmlSource)
{
if (!EnsureDigestValidityIfIdMatches(id, resolvedXmlSource))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(
SR.GetString(SR.RequiredTargetNotSigned, id)));
}
}
public abstract bool EnsureDigestValidityIfIdMatches(string id, object resolvedXmlSource);
public virtual bool HasUnverifiedReference(string id)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
protected void ReadCanonicalizationMethod(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
{
// we will ignore any comments in the SignedInfo elemnt when verifying signature
this.canonicalizationMethodElement.ReadFrom(reader, dictionaryManager, false);
}
public abstract void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager);
protected void ReadSignatureMethod(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
{
this.signatureMethodElement.ReadFrom(reader, dictionaryManager);
}
protected void WriteCanonicalizationMethod(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
this.canonicalizationMethodElement.WriteTo(writer, dictionaryManager);
}
protected void WriteSignatureMethod(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
this.signatureMethodElement.WriteTo(writer, dictionaryManager);
}
public abstract void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager);
}
// whitespace preservation convention: ws1 immediately inside open tag; ws2 immediately after end tag.
class StandardSignedInfo : SignedInfo
{
string prefix = SignedXml.DefaultPrefix;
List<Reference> references;
Dictionary<string, string> context;
public StandardSignedInfo(DictionaryManager dictionaryManager)
: base(dictionaryManager)
{
this.references = new List<Reference>();
}
public override int ReferenceCount
{
get { return this.references.Count; }
}
public Reference this[int index]
{
get { return this.references[index]; }
}
public void AddReference(Reference reference)
{
reference.ResourcePool = this.ResourcePool;
this.references.Add(reference);
}
public override void EnsureAllReferencesVerified()
{
for (int i = 0; i < this.references.Count; i++)
{
if (!this.references[i].Verified)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new CryptographicException(SR.GetString(SR.UnableToResolveReferenceUriForSignature, this.references[i].Uri)));
}
}
}
public override bool EnsureDigestValidityIfIdMatches(string id, object resolvedXmlSource)
{
for (int i = 0; i < this.references.Count; i++)
{
if (this.references[i].EnsureDigestValidityIfIdMatches(id, resolvedXmlSource))
{
return true;
}
}
return false;
}
public override bool HasUnverifiedReference(string id)
{
for (int i = 0; i < this.references.Count; i++)
{
if (!this.references[i].Verified && this.references[i].ExtractReferredId() == id)
{
return true;
}
}
return false;
}
public override void ComputeReferenceDigests()
{
if (this.references.Count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.AtLeastOneReferenceRequired)));
}
for (int i = 0; i < this.references.Count; i++)
{
this.references[i].ComputeAndSetDigest();
}
}
public override void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager)
{
this.SendSide = false;
if (reader.CanCanonicalize)
{
this.CanonicalStream = new MemoryStream();
reader.StartCanonicalization(this.CanonicalStream, false, null);
}
reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.SignedInfo, dictionaryManager.XmlSignatureDictionary.Namespace);
this.prefix = reader.Prefix;
this.Id = reader.GetAttribute(dictionaryManager.UtilityDictionary.IdAttribute, null);
reader.Read();
ReadCanonicalizationMethod(reader, dictionaryManager);
ReadSignatureMethod(reader, dictionaryManager);
while (reader.IsStartElement(dictionaryManager.XmlSignatureDictionary.Reference, dictionaryManager.XmlSignatureDictionary.Namespace))
{
Reference reference = new Reference(dictionaryManager);
reference.ReadFrom(reader, transformFactory, dictionaryManager);
AddReference(reference);
}
reader.ReadEndElement(); // SignedInfo
if (reader.CanCanonicalize)
reader.EndCanonicalization();
string[] inclusivePrefixes = GetInclusivePrefixes();
if (inclusivePrefixes != null)
{
// Clear the canonicalized stream. We cannot use this while inclusive prefixes are
// specified.
this.CanonicalStream = null;
this.context = new Dictionary<string, string>(inclusivePrefixes.Length);
for (int i = 0; i < inclusivePrefixes.Length; i++)
{
this.context.Add(inclusivePrefixes[i], reader.LookupNamespace(inclusivePrefixes[i]));
}
}
}
public override void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.SignedInfo, dictionaryManager.XmlSignatureDictionary.Namespace);
if (this.Id != null)
{
writer.WriteAttributeString(dictionaryManager.UtilityDictionary.IdAttribute, null, this.Id);
}
WriteCanonicalizationMethod(writer, dictionaryManager);
WriteSignatureMethod(writer, dictionaryManager);
for (int i = 0; i < this.references.Count; i++)
{
this.references[i].WriteTo(writer, dictionaryManager);
}
writer.WriteEndElement(); // SignedInfo
}
protected override string GetNamespaceForInclusivePrefix(string prefix)
{
if (this.context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
if (prefix == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("prefix");
return context[prefix];
}
protected string Prefix
{
get { return prefix; }
set { prefix = value; }
}
protected Dictionary<string, string> Context
{
get { return context; }
set { context = value; }
}
}
sealed class WifSignedInfo : StandardSignedInfo, IDisposable
{
MemoryStream _bufferedStream;
string _defaultNamespace = String.Empty;
bool _disposed;
public WifSignedInfo(DictionaryManager dictionaryManager)
: base(dictionaryManager)
{
}
~WifSignedInfo()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
//
// Free all of our managed resources
//
if (_bufferedStream != null)
{
_bufferedStream.Close();
_bufferedStream = null;
}
}
// Free native resources, if any.
_disposed = true;
}
protected override void ComputeHash(HashStream hashStream)
{
if (SendSide)
{
using (XmlDictionaryWriter utf8Writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null, Encoding.UTF8, false))
{
utf8Writer.StartCanonicalization(hashStream, false, null);
WriteTo(utf8Writer, DictionaryManager);
utf8Writer.EndCanonicalization();
}
}
else if (CanonicalStream != null)
{
CanonicalStream.WriteTo(hashStream);
}
else
{
_bufferedStream.Position = 0;
// We are creating a XmlDictionaryReader with a hard-coded Max XmlDictionaryReaderQuotas. This is a reader that we
// are creating over an already buffered content. The content was initially read off user provided XmlDictionaryReader
// with the correct quotas and hence we know the data is valid.
// Note: signedinfoReader will close _bufferedStream on Dispose.
using (XmlDictionaryReader signedinfoReader = XmlDictionaryReader.CreateTextReader(_bufferedStream, XmlDictionaryReaderQuotas.Max))
{
signedinfoReader.MoveToContent();
using (XmlDictionaryWriter bufferingWriter = XmlDictionaryWriter.CreateTextWriter(Stream.Null, Encoding.UTF8, false))
{
bufferingWriter.WriteStartElement("a", _defaultNamespace);
string[] inclusivePrefix = GetInclusivePrefixes();
for (int i = 0; i < inclusivePrefix.Length; ++i)
{
string ns = GetNamespaceForInclusivePrefix(inclusivePrefix[i]);
if (ns != null)
{
bufferingWriter.WriteXmlnsAttribute(inclusivePrefix[i], ns);
}
}
bufferingWriter.StartCanonicalization(hashStream, false, inclusivePrefix);
bufferingWriter.WriteNode(signedinfoReader, false);
bufferingWriter.EndCanonicalization();
bufferingWriter.WriteEndElement();
}
}
}
}
public override void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager)
{
reader.MoveToStartElement(XmlSignatureConstants.Elements.SignedInfo, XmlSignatureConstants.Namespace);
SendSide = false;
_defaultNamespace = reader.LookupNamespace(String.Empty);
_bufferedStream = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.NewLineHandling = NewLineHandling.None;
using (XmlWriter bufferWriter = XmlTextWriter.Create(_bufferedStream, settings))
{
bufferWriter.WriteNode(reader, true);
bufferWriter.Flush();
}
_bufferedStream.Position = 0;
//
// We are creating a XmlDictionaryReader with a hard-coded Max XmlDictionaryReaderQuotas. This is a reader that we
// are creating over an already buffered content. The content was initially read off user provided XmlDictionaryReader
// with the correct quotas and hence we know the data is valid.
// Note: effectiveReader will close _bufferedStream on Dispose.
//
using (XmlDictionaryReader effectiveReader = XmlDictionaryReader.CreateTextReader(_bufferedStream, XmlDictionaryReaderQuotas.Max))
{
CanonicalStream = new MemoryStream();
effectiveReader.StartCanonicalization(CanonicalStream, false, null);
effectiveReader.MoveToStartElement(XmlSignatureConstants.Elements.SignedInfo, XmlSignatureConstants.Namespace);
Prefix = effectiveReader.Prefix;
Id = effectiveReader.GetAttribute(WSSecurityUtilityConstants.Attributes.Id, null);
effectiveReader.Read();
ReadCanonicalizationMethod(effectiveReader, DictionaryManager);
ReadSignatureMethod(effectiveReader, DictionaryManager);
while (effectiveReader.IsStartElement(XmlSignatureConstants.Elements.Reference, XmlSignatureConstants.Namespace))
{
Reference reference = new Reference(DictionaryManager);
reference.ReadFrom(effectiveReader, transformFactory, DictionaryManager);
AddReference(reference);
}
effectiveReader.ReadEndElement();
effectiveReader.EndCanonicalization();
}
string[] inclusivePrefixes = GetInclusivePrefixes();
if (inclusivePrefixes != null)
{
// Clear the canonicalized stream. We cannot use this while inclusive prefixes are
// specified.
CanonicalStream = null;
Context = new Dictionary<string, string>(inclusivePrefixes.Length);
for (int i = 0; i < inclusivePrefixes.Length; i++)
{
Context.Add(inclusivePrefixes[i], reader.LookupNamespace(inclusivePrefixes[i]));
}
}
}
}
sealed class Reference
{
ElementWithAlgorithmAttribute digestMethodElement;
DigestValueElement digestValueElement = new DigestValueElement();
string id;
string prefix = SignedXml.DefaultPrefix;
object resolvedXmlSource;
readonly TransformChain transformChain = new TransformChain();
string type;
string uri;
SignatureResourcePool resourcePool;
bool verified;
string referredId;
DictionaryManager dictionaryManager;
public Reference(DictionaryManager dictionaryManager)
: this(dictionaryManager, null)
{
}
public Reference(DictionaryManager dictionaryManager, string uri)
: this(dictionaryManager, uri, null)
{
}
public Reference(DictionaryManager dictionaryManager, string uri, object resolvedXmlSource)
{
if (dictionaryManager == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dictionaryManager");
this.dictionaryManager = dictionaryManager;
this.digestMethodElement = new ElementWithAlgorithmAttribute(dictionaryManager.XmlSignatureDictionary.DigestMethod);
this.uri = uri;
this.resolvedXmlSource = resolvedXmlSource;
}
public string DigestMethod
{
get { return this.digestMethodElement.Algorithm; }
set { this.digestMethodElement.Algorithm = value; }
}
public XmlDictionaryString DigestMethodDictionaryString
{
get { return this.digestMethodElement.AlgorithmDictionaryString; }
set { this.digestMethodElement.AlgorithmDictionaryString = value; }
}
public string Id
{
get { return this.id; }
set { this.id = value; }
}
public SignatureResourcePool ResourcePool
{
get { return this.resourcePool; }
set { this.resourcePool = value; }
}
public TransformChain TransformChain
{
get { return this.transformChain; }
}
public int TransformCount
{
get { return this.transformChain.TransformCount; }
}
public string Type
{
get { return this.type; }
set { this.type = value; }
}
public string Uri
{
get { return this.uri; }
set { this.uri = value; }
}
public bool Verified
{
get { return this.verified; }
}
public void AddTransform(Transform transform)
{
this.transformChain.Add(transform);
}
public void EnsureDigestValidity(string id, byte[] computedDigest)
{
if (!EnsureDigestValidityIfIdMatches(id, computedDigest))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(
SR.GetString(SR.RequiredTargetNotSigned, id)));
}
}
public void EnsureDigestValidity(string id, object resolvedXmlSource)
{
if (!EnsureDigestValidityIfIdMatches(id, resolvedXmlSource))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(
SR.GetString(SR.RequiredTargetNotSigned, id)));
}
}
public bool EnsureDigestValidityIfIdMatches(string id, byte[] computedDigest)
{
if (this.verified || id != ExtractReferredId())
{
return false;
}
if (!CryptoHelper.IsEqual(computedDigest, GetDigestValue()))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new CryptographicException(SR.GetString(SR.DigestVerificationFailedForReference, this.uri)));
}
this.verified = true;
return true;
}
public bool EnsureDigestValidityIfIdMatches(string id, object resolvedXmlSource)
{
if (this.verified)
{
return false;
}
// During StrTransform the extractedReferredId on the reference will point to STR and hence will not be
// equal to the referred element ie security token Id.
if (id != ExtractReferredId() && !this.IsStrTranform())
{
return false;
}
this.resolvedXmlSource = resolvedXmlSource;
if (!CheckDigest())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new CryptographicException(SR.GetString(SR.DigestVerificationFailedForReference, this.uri)));
}
this.verified = true;
return true;
}
public bool IsStrTranform()
{
return this.TransformChain.TransformCount == 1 && this.TransformChain[0].Algorithm == SecurityAlgorithms.StrTransform;
}
public string ExtractReferredId()
{
if (this.referredId == null)
{
if (StringComparer.OrdinalIgnoreCase.Equals(uri, String.Empty))
{
return String.Empty;
}
if (this.uri == null || this.uri.Length < 2 || this.uri[0] != '#')
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new CryptographicException(SR.GetString(SR.UnableToResolveReferenceUriForSignature, this.uri)));
}
this.referredId = this.uri.Substring(1);
}
return this.referredId;
}
/// <summary>
/// We look at the URI reference to decide if we should preserve comments while canonicalization.
/// Only when the reference is xpointer(/) or xpointer(id(SomeId)) do we preserve comments during canonicalization
/// of the reference element for computing the digest.
/// </summary>
/// <param name="uri">The Uri reference </param>
/// <returns>true if comments should be preserved.</returns>
private static bool ShouldPreserveComments(string uri)
{
bool preserveComments = false;
if (!String.IsNullOrEmpty(uri))
{
//removes the hash
string idref = uri.Substring(1);
if (idref == "xpointer(/)")
{
preserveComments = true;
}
else if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal) && (idref.IndexOf(")", StringComparison.Ordinal) > 0))
{
// Dealing with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional
preserveComments = true;
}
}
return preserveComments;
}
public bool CheckDigest()
{
byte[] computedDigest = ComputeDigest();
bool result = CryptoHelper.IsEqual(computedDigest, GetDigestValue());
#if LOG_DIGESTS
Console.WriteLine(">>> Checking digest for reference '{0}', result {1}", uri, result);
Console.WriteLine(" Computed digest {0}", Convert.ToBase64String(computedDigest));
Console.WriteLine(" Received digest {0}", Convert.ToBase64String(GetDigestValue()));
#endif
return result;
}
public void ComputeAndSetDigest()
{
this.digestValueElement.Value = ComputeDigest();
}
public byte[] ComputeDigest()
{
if (this.transformChain.TransformCount == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.EmptyTransformChainNotSupported)));
}
if (this.resolvedXmlSource == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(
SR.GetString(SR.UnableToResolveReferenceUriForSignature, this.uri)));
}
return this.transformChain.TransformToDigest(this.resolvedXmlSource, this.ResourcePool, this.DigestMethod, this.dictionaryManager);
}
public byte[] GetDigestValue()
{
return this.digestValueElement.Value;
}
public void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager)
{
reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.Reference, dictionaryManager.XmlSignatureDictionary.Namespace);
this.prefix = reader.Prefix;
this.Id = reader.GetAttribute(UtilityStrings.IdAttribute, null);
this.Uri = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.URI, null);
this.Type = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Type, null);
reader.Read();
if (reader.IsStartElement(dictionaryManager.XmlSignatureDictionary.Transforms, dictionaryManager.XmlSignatureDictionary.Namespace))
{
this.transformChain.ReadFrom(reader, transformFactory, dictionaryManager, ShouldPreserveComments(this.Uri));
}
this.digestMethodElement.ReadFrom(reader, dictionaryManager);
this.digestValueElement.ReadFrom(reader, dictionaryManager);
reader.MoveToContent();
reader.ReadEndElement(); // Reference
}
public void SetResolvedXmlSource(object resolvedXmlSource)
{
this.resolvedXmlSource = resolvedXmlSource;
}
public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.Reference, dictionaryManager.XmlSignatureDictionary.Namespace);
if (this.id != null)
{
writer.WriteAttributeString(dictionaryManager.UtilityDictionary.IdAttribute, null, this.id);
}
if (this.uri != null)
{
writer.WriteAttributeString(dictionaryManager.XmlSignatureDictionary.URI, null, this.uri);
}
if (this.type != null)
{
writer.WriteAttributeString(dictionaryManager.XmlSignatureDictionary.Type, null, this.type);
}
if (this.transformChain.TransformCount > 0)
{
this.transformChain.WriteTo(writer, dictionaryManager);
}
this.digestMethodElement.WriteTo(writer, dictionaryManager);
this.digestValueElement.WriteTo(writer, dictionaryManager);
writer.WriteEndElement(); // Reference
}
struct DigestValueElement
{
byte[] digestValue;
string digestText;
string prefix;
internal byte[] Value
{
get { return this.digestValue; }
set
{
this.digestValue = value;
this.digestText = null;
}
}
public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
{
reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.DigestValue, dictionaryManager.XmlSignatureDictionary.Namespace);
this.prefix = reader.Prefix;
reader.Read();
reader.MoveToContent();
this.digestText = reader.ReadString();
this.digestValue = System.Convert.FromBase64String(digestText.Trim());
reader.MoveToContent();
reader.ReadEndElement(); // DigestValue
}
public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
writer.WriteStartElement(this.prefix ?? XmlSignatureStrings.Prefix, dictionaryManager.XmlSignatureDictionary.DigestValue, dictionaryManager.XmlSignatureDictionary.Namespace);
if (this.digestText != null)
{
writer.WriteString(this.digestText);
}
else
{
writer.WriteBase64(this.digestValue, 0, this.digestValue.Length);
}
writer.WriteEndElement(); // DigestValue
}
}
}
sealed class TransformChain
{
string prefix = SignedXml.DefaultPrefix;
MostlySingletonList<Transform> transforms;
public TransformChain()
{
}
public int TransformCount
{
get { return this.transforms.Count; }
}
public Transform this[int index]
{
get
{
return this.transforms[index];
}
}
public bool NeedsInclusiveContext
{
get
{
for (int i = 0; i < this.TransformCount; i++)
{
if (this[i].NeedsInclusiveContext)
{
return true;
}
}
return false;
}
}
public void Add(Transform transform)
{
this.transforms.Add(transform);
}
public void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager, bool preserveComments)
{
reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.Transforms, dictionaryManager.XmlSignatureDictionary.Namespace);
this.prefix = reader.Prefix;
reader.Read();
while (reader.IsStartElement(dictionaryManager.XmlSignatureDictionary.Transform, dictionaryManager.XmlSignatureDictionary.Namespace))
{
string transformAlgorithmUri = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null);
Transform transform = transformFactory.CreateTransform(transformAlgorithmUri);
transform.ReadFrom(reader, dictionaryManager, preserveComments);
Add(transform);
}
reader.MoveToContent();
reader.ReadEndElement(); // Transforms
if (this.TransformCount == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.AtLeastOneTransformRequired)));
}
}
public byte[] TransformToDigest(object data, SignatureResourcePool resourcePool, string digestMethod, DictionaryManager dictionaryManager)
{
DiagnosticUtility.DebugAssert(TransformCount > 0, "");
for (int i = 0; i < this.TransformCount - 1; i++)
{
data = this[i].Process(data, resourcePool, dictionaryManager);
}
return this[this.TransformCount - 1].ProcessAndDigest(data, resourcePool, digestMethod, dictionaryManager);
}
public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
writer.WriteStartElement(this.prefix, dictionaryManager.XmlSignatureDictionary.Transforms, dictionaryManager.XmlSignatureDictionary.Namespace);
for (int i = 0; i < this.TransformCount; i++)
{
this[i].WriteTo(writer, dictionaryManager);
}
writer.WriteEndElement(); // Transforms
}
}
struct ElementWithAlgorithmAttribute
{
readonly XmlDictionaryString elementName;
string algorithm;
XmlDictionaryString algorithmDictionaryString;
string prefix;
public ElementWithAlgorithmAttribute(XmlDictionaryString elementName)
{
if (elementName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("elementName"));
}
this.elementName = elementName;
this.algorithm = null;
this.algorithmDictionaryString = null;
this.prefix = SignedXml.DefaultPrefix;
}
public string Algorithm
{
get { return this.algorithm; }
set { this.algorithm = value; }
}
public XmlDictionaryString AlgorithmDictionaryString
{
get { return this.algorithmDictionaryString; }
set { this.algorithmDictionaryString = value; }
}
public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
{
reader.MoveToStartElement(this.elementName, dictionaryManager.XmlSignatureDictionary.Namespace);
this.prefix = reader.Prefix;
bool isEmptyElement = reader.IsEmptyElement;
this.algorithm = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null);
if (this.algorithm == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(
SR.GetString(SR.RequiredAttributeMissing, dictionaryManager.XmlSignatureDictionary.Algorithm, this.elementName)));
}
reader.Read();
reader.MoveToContent();
if (!isEmptyElement)
{
reader.MoveToContent();
reader.ReadEndElement();
}
}
public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager)
{
writer.WriteStartElement(this.prefix, this.elementName, dictionaryManager.XmlSignatureDictionary.Namespace);
writer.WriteStartAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null);
if (this.algorithmDictionaryString != null)
{
writer.WriteString(this.algorithmDictionaryString);
}
else
{
writer.WriteString(this.algorithm);
}
writer.WriteEndAttribute();
writer.WriteEndElement();
}
}
}
|