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 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
|
//
// PKCS12.cs: PKCS 12 - Personal Information Exchange Syntax
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004,2005,2006 Novell Inc. (http://www.novell.com)
//
// Key derivation translated from Bouncy Castle JCE (http://www.bouncycastle.org/)
// See bouncycastle.txt for license.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Mono.Security;
using Mono.Security.Cryptography;
namespace Mono.Security.X509 {
#if INSIDE_CORLIB
internal
#else
public
#endif
class PKCS5 {
public const string pbeWithMD2AndDESCBC = "1.2.840.113549.1.5.1";
public const string pbeWithMD5AndDESCBC = "1.2.840.113549.1.5.3";
public const string pbeWithMD2AndRC2CBC = "1.2.840.113549.1.5.4";
public const string pbeWithMD5AndRC2CBC = "1.2.840.113549.1.5.6";
public const string pbeWithSHA1AndDESCBC = "1.2.840.113549.1.5.10";
public const string pbeWithSHA1AndRC2CBC = "1.2.840.113549.1.5.11";
public PKCS5 () {}
}
#if INSIDE_CORLIB
internal
#else
public
#endif
class PKCS9 {
public const string friendlyName = "1.2.840.113549.1.9.20";
public const string localKeyId = "1.2.840.113549.1.9.21";
public PKCS9 () {}
}
internal class SafeBag {
private string _bagOID;
private ASN1 _asn1;
public SafeBag(string bagOID, ASN1 asn1) {
_bagOID = bagOID;
_asn1 = asn1;
}
public string BagOID {
get { return _bagOID; }
}
public ASN1 ASN1 {
get { return _asn1; }
}
}
#if INSIDE_CORLIB
internal
#else
public
#endif
class PKCS12 : ICloneable {
public const string pbeWithSHAAnd128BitRC4 = "1.2.840.113549.1.12.1.1";
public const string pbeWithSHAAnd40BitRC4 = "1.2.840.113549.1.12.1.2";
public const string pbeWithSHAAnd3KeyTripleDESCBC = "1.2.840.113549.1.12.1.3";
public const string pbeWithSHAAnd2KeyTripleDESCBC = "1.2.840.113549.1.12.1.4";
public const string pbeWithSHAAnd128BitRC2CBC = "1.2.840.113549.1.12.1.5";
public const string pbeWithSHAAnd40BitRC2CBC = "1.2.840.113549.1.12.1.6";
// bags
public const string keyBag = "1.2.840.113549.1.12.10.1.1";
public const string pkcs8ShroudedKeyBag = "1.2.840.113549.1.12.10.1.2";
public const string certBag = "1.2.840.113549.1.12.10.1.3";
public const string crlBag = "1.2.840.113549.1.12.10.1.4";
public const string secretBag = "1.2.840.113549.1.12.10.1.5";
public const string safeContentsBag = "1.2.840.113549.1.12.10.1.6";
// types
public const string x509Certificate = "1.2.840.113549.1.9.22.1";
public const string sdsiCertificate = "1.2.840.113549.1.9.22.2";
public const string x509Crl = "1.2.840.113549.1.9.23.1";
// Adapted from BouncyCastle PKCS12ParametersGenerator.java
public class DeriveBytes {
public enum Purpose {
Key,
IV,
MAC
}
static private byte[] keyDiversifier = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 };
static private byte[] ivDiversifier = { 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 };
static private byte[] macDiversifier = { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3 };
private string _hashName;
private int _iterations;
private byte[] _password;
private byte[] _salt;
public DeriveBytes () {}
public string HashName {
get { return _hashName; }
set { _hashName = value; }
}
public int IterationCount {
get { return _iterations; }
set { _iterations = value; }
}
public byte[] Password {
get { return (byte[]) _password.Clone (); }
set {
if (value == null)
_password = new byte [0];
else
_password = (byte[]) value.Clone ();
}
}
public byte[] Salt {
get { return (byte[]) _salt.Clone (); }
set {
if (value != null)
_salt = (byte[]) value.Clone ();
else
_salt = null;
}
}
private void Adjust (byte[] a, int aOff, byte[] b)
{
int x = (b[b.Length - 1] & 0xff) + (a [aOff + b.Length - 1] & 0xff) + 1;
a [aOff + b.Length - 1] = (byte) x;
x >>= 8;
for (int i = b.Length - 2; i >= 0; i--) {
x += (b [i] & 0xff) + (a [aOff + i] & 0xff);
a [aOff + i] = (byte) x;
x >>= 8;
}
}
private byte[] Derive (byte[] diversifier, int n)
{
HashAlgorithm digest = HashAlgorithm.Create (_hashName);
int u = (digest.HashSize >> 3); // div 8
int v = 64;
byte[] dKey = new byte [n];
byte[] S;
if ((_salt != null) && (_salt.Length != 0)) {
S = new byte[v * ((_salt.Length + v - 1) / v)];
for (int i = 0; i != S.Length; i++) {
S[i] = _salt[i % _salt.Length];
}
}
else {
S = new byte[0];
}
byte[] P;
if ((_password != null) && (_password.Length != 0)) {
P = new byte[v * ((_password.Length + v - 1) / v)];
for (int i = 0; i != P.Length; i++) {
P[i] = _password[i % _password.Length];
}
}
else {
P = new byte[0];
}
byte[] I = new byte [S.Length + P.Length];
Buffer.BlockCopy (S, 0, I, 0, S.Length);
Buffer.BlockCopy (P, 0, I, S.Length, P.Length);
byte[] B = new byte[v];
int c = (n + u - 1) / u;
for (int i = 1; i <= c; i++) {
digest.TransformBlock (diversifier, 0, diversifier.Length, diversifier, 0);
digest.TransformFinalBlock (I, 0, I.Length);
byte[] A = digest.Hash;
digest.Initialize ();
for (int j = 1; j != _iterations; j++) {
A = digest.ComputeHash (A, 0, A.Length);
}
for (int j = 0; j != B.Length; j++) {
B [j] = A [j % A.Length];
}
for (int j = 0; j != I.Length / v; j++) {
Adjust (I, j * v, B);
}
if (i == c) {
Buffer.BlockCopy(A, 0, dKey, (i - 1) * u, dKey.Length - ((i - 1) * u));
}
else {
Buffer.BlockCopy(A, 0, dKey, (i - 1) * u, A.Length);
}
}
return dKey;
}
public byte[] DeriveKey (int size)
{
return Derive (keyDiversifier, size);
}
public byte[] DeriveIV (int size)
{
return Derive (ivDiversifier, size);
}
public byte[] DeriveMAC (int size)
{
return Derive (macDiversifier, size);
}
}
static private int recommendedIterationCount = 2000;
//private int _version;
private byte[] _password;
private ArrayList _keyBags;
private X509CertificateCollection _certs;
private bool _keyBagsChanged;
private bool _certsChanged;
private int _iterations;
private ArrayList _safeBags;
private RandomNumberGenerator _rng;
// constructors
public PKCS12 ()
{
_iterations = recommendedIterationCount;
_keyBags = new ArrayList ();
_certs = new X509CertificateCollection ();
_keyBagsChanged = false;
_certsChanged = false;
_safeBags = new ArrayList ();
}
public PKCS12 (byte[] data)
: this ()
{
Password = null;
Decode (data);
}
/*
* PFX ::= SEQUENCE {
* version INTEGER {v3(3)}(v3,...),
* authSafe ContentInfo,
* macData MacData OPTIONAL
* }
*
* MacData ::= SEQUENCE {
* mac DigestInfo,
* macSalt OCTET STRING,
* iterations INTEGER DEFAULT 1
* -- Note: The default is for historical reasons and its use is deprecated. A higher
* -- value, like 1024 is recommended.
* }
*
* SafeContents ::= SEQUENCE OF SafeBag
*
* SafeBag ::= SEQUENCE {
* bagId BAG-TYPE.&id ({PKCS12BagSet}),
* bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),
* bagAttributes SET OF PKCS12Attribute OPTIONAL
* }
*/
public PKCS12 (byte[] data, string password)
: this ()
{
Password = password;
Decode (data);
}
#if NET_2_0
public PKCS12 (byte[] data, byte[] password)
: this ()
{
_password = password;
Decode (data);
}
#endif
private void Decode (byte[] data)
{
ASN1 pfx = new ASN1 (data);
if (pfx.Tag != 0x30)
throw new ArgumentException ("invalid data");
ASN1 version = pfx [0];
if (version.Tag != 0x02)
throw new ArgumentException ("invalid PFX version");
//_version = version.Value [0];
PKCS7.ContentInfo authSafe = new PKCS7.ContentInfo (pfx [1]);
if (authSafe.ContentType != PKCS7.Oid.data)
throw new ArgumentException ("invalid authenticated safe");
// now that we know it's a PKCS#12 file, check the (optional) MAC
// before decoding anything else in the file
if (pfx.Count > 2) {
ASN1 macData = pfx [2];
if (macData.Tag != 0x30)
throw new ArgumentException ("invalid MAC");
ASN1 mac = macData [0];
if (mac.Tag != 0x30)
throw new ArgumentException ("invalid MAC");
ASN1 macAlgorithm = mac [0];
string macOid = ASN1Convert.ToOid (macAlgorithm [0]);
if (macOid != "1.3.14.3.2.26")
throw new ArgumentException ("unsupported HMAC");
byte[] macValue = mac [1].Value;
ASN1 macSalt = macData [1];
if (macSalt.Tag != 0x04)
throw new ArgumentException ("missing MAC salt");
_iterations = 1; // default value
if (macData.Count > 2) {
ASN1 iters = macData [2];
if (iters.Tag != 0x02)
throw new ArgumentException ("invalid MAC iteration");
_iterations = ASN1Convert.ToInt32 (iters);
}
byte[] authSafeData = authSafe.Content [0].Value;
byte[] calculatedMac = MAC (_password, macSalt.Value, _iterations, authSafeData);
if (!Compare (macValue, calculatedMac))
throw new CryptographicException ("Invalid MAC - file may have been tampered!");
}
// we now returns to our original presentation - PFX
ASN1 authenticatedSafe = new ASN1 (authSafe.Content [0].Value);
for (int i=0; i < authenticatedSafe.Count; i++) {
PKCS7.ContentInfo ci = new PKCS7.ContentInfo (authenticatedSafe [i]);
switch (ci.ContentType) {
case PKCS7.Oid.data:
// unencrypted (by PKCS#12)
ASN1 safeContents = new ASN1 (ci.Content [0].Value);
for (int j=0; j < safeContents.Count; j++) {
ASN1 safeBag = safeContents [j];
ReadSafeBag (safeBag);
}
break;
case PKCS7.Oid.encryptedData:
// password encrypted
PKCS7.EncryptedData ed = new PKCS7.EncryptedData (ci.Content [0]);
ASN1 decrypted = new ASN1 (Decrypt (ed));
for (int j=0; j < decrypted.Count; j++) {
ASN1 safeBag = decrypted [j];
ReadSafeBag (safeBag);
}
break;
case PKCS7.Oid.envelopedData:
// public key encrypted
throw new NotImplementedException ("public key encrypted");
default:
throw new ArgumentException ("unknown authenticatedSafe");
}
}
}
~PKCS12 ()
{
if (_password != null) {
Array.Clear (_password, 0, _password.Length);
}
_password = null;
}
// properties
public string Password {
set {
if (value != null) {
if (value.Length > 0) {
int size = value.Length;
int nul = 0;
if (size < MaximumPasswordLength) {
// if not present, add space for a NULL (0x00) character
if (value[size - 1] != 0x00)
nul = 1;
} else {
size = MaximumPasswordLength;
}
_password = new byte[(size + nul) << 1]; // double for unicode
Encoding.BigEndianUnicode.GetBytes (value, 0, size, _password, 0);
} else {
// double-byte (Unicode) NULL (0x00) - see bug #79617
_password = new byte[2];
}
} else {
// no password
_password = null;
}
}
}
public int IterationCount {
get { return _iterations; }
set { _iterations = value; }
}
public ArrayList Keys {
get {
if (_keyBagsChanged) {
_keyBags.Clear ();
foreach (SafeBag sb in _safeBags) {
if (sb.BagOID.Equals (keyBag)) {
ASN1 safeBag = sb.ASN1;
ASN1 bagValue = safeBag [1];
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (bagValue.Value);
byte[] privateKey = pki.PrivateKey;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
_keyBags.Add (PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p));
break;
case 0x30:
_keyBags.Add (PKCS8.PrivateKeyInfo.DecodeRSA (privateKey));
break;
default:
break;
}
Array.Clear (privateKey, 0, privateKey.Length);
} else if (sb.BagOID.Equals (pkcs8ShroudedKeyBag)) {
ASN1 safeBag = sb.ASN1;
ASN1 bagValue = safeBag [1];
PKCS8.EncryptedPrivateKeyInfo epki = new PKCS8.EncryptedPrivateKeyInfo (bagValue.Value);
byte[] decrypted = Decrypt (epki.Algorithm, epki.Salt, epki.IterationCount, epki.EncryptedData);
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (decrypted);
byte[] privateKey = pki.PrivateKey;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
_keyBags.Add (PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p));
break;
case 0x30:
_keyBags.Add (PKCS8.PrivateKeyInfo.DecodeRSA (privateKey));
break;
default:
break;
}
Array.Clear (privateKey, 0, privateKey.Length);
Array.Clear (decrypted, 0, decrypted.Length);
}
}
_keyBagsChanged = false;
}
return ArrayList.ReadOnly(_keyBags);
}
}
public X509CertificateCollection Certificates {
get {
if (_certsChanged) {
_certs.Clear ();
foreach (SafeBag sb in _safeBags) {
if (sb.BagOID.Equals (certBag)) {
ASN1 safeBag = sb.ASN1;
ASN1 bagValue = safeBag [1];
PKCS7.ContentInfo cert = new PKCS7.ContentInfo (bagValue.Value);
_certs.Add (new X509Certificate (cert.Content [0].Value));
}
}
_certsChanged = false;
}
return _certs;
}
}
internal RandomNumberGenerator RNG {
get {
if (_rng == null)
_rng = RandomNumberGenerator.Create ();
return _rng;
}
}
// private methods
private bool Compare (byte[] expected, byte[] actual)
{
bool compare = false;
if (expected.Length == actual.Length) {
for (int i=0; i < expected.Length; i++) {
if (expected [i] != actual [i])
return false;
}
compare = true;
}
return compare;
}
private SymmetricAlgorithm GetSymmetricAlgorithm (string algorithmOid, byte[] salt, int iterationCount)
{
string algorithm = null;
int keyLength = 8; // 64 bits (default)
int ivLength = 8; // 64 bits (default)
PKCS12.DeriveBytes pd = new PKCS12.DeriveBytes ();
pd.Password = _password;
pd.Salt = salt;
pd.IterationCount = iterationCount;
switch (algorithmOid) {
case PKCS5.pbeWithMD2AndDESCBC: // no unit test available
pd.HashName = "MD2";
algorithm = "DES";
break;
case PKCS5.pbeWithMD5AndDESCBC: // no unit test available
pd.HashName = "MD5";
algorithm = "DES";
break;
case PKCS5.pbeWithMD2AndRC2CBC: // no unit test available
// TODO - RC2-CBC-Parameter (PKCS5)
// if missing default to 32 bits !!!
pd.HashName = "MD2";
algorithm = "RC2";
keyLength = 4; // default
break;
case PKCS5.pbeWithMD5AndRC2CBC: // no unit test available
// TODO - RC2-CBC-Parameter (PKCS5)
// if missing default to 32 bits !!!
pd.HashName = "MD5";
algorithm = "RC2";
keyLength = 4; // default
break;
case PKCS5.pbeWithSHA1AndDESCBC: // no unit test available
pd.HashName = "SHA1";
algorithm = "DES";
break;
case PKCS5.pbeWithSHA1AndRC2CBC: // no unit test available
// TODO - RC2-CBC-Parameter (PKCS5)
// if missing default to 32 bits !!!
pd.HashName = "SHA1";
algorithm = "RC2";
keyLength = 4; // default
break;
case PKCS12.pbeWithSHAAnd128BitRC4: // no unit test available
pd.HashName = "SHA1";
algorithm = "RC4";
keyLength = 16;
ivLength = 0; // N/A
break;
case PKCS12.pbeWithSHAAnd40BitRC4: // no unit test available
pd.HashName = "SHA1";
algorithm = "RC4";
keyLength = 5;
ivLength = 0; // N/A
break;
case PKCS12.pbeWithSHAAnd3KeyTripleDESCBC:
pd.HashName = "SHA1";
algorithm = "TripleDES";
keyLength = 24;
break;
case PKCS12.pbeWithSHAAnd2KeyTripleDESCBC: // no unit test available
pd.HashName = "SHA1";
algorithm = "TripleDES";
keyLength = 16;
break;
case PKCS12.pbeWithSHAAnd128BitRC2CBC: // no unit test available
pd.HashName = "SHA1";
algorithm = "RC2";
keyLength = 16;
break;
case PKCS12.pbeWithSHAAnd40BitRC2CBC:
pd.HashName = "SHA1";
algorithm = "RC2";
keyLength = 5;
break;
default:
throw new NotSupportedException ("unknown oid " + algorithm);
}
SymmetricAlgorithm sa = SymmetricAlgorithm.Create (algorithm);
sa.Key = pd.DeriveKey (keyLength);
// IV required only for block ciphers (not stream ciphers)
if (ivLength > 0) {
sa.IV = pd.DeriveIV (ivLength);
sa.Mode = CipherMode.CBC;
}
return sa;
}
public byte[] Decrypt (string algorithmOid, byte[] salt, int iterationCount, byte[] encryptedData)
{
SymmetricAlgorithm sa = null;
byte[] result = null;
try {
sa = GetSymmetricAlgorithm (algorithmOid, salt, iterationCount);
ICryptoTransform ct = sa.CreateDecryptor ();
result = ct.TransformFinalBlock (encryptedData, 0, encryptedData.Length);
}
finally {
if (sa != null)
sa.Clear ();
}
return result;
}
public byte[] Decrypt (PKCS7.EncryptedData ed)
{
return Decrypt (ed.EncryptionAlgorithm.ContentType,
ed.EncryptionAlgorithm.Content [0].Value,
ASN1Convert.ToInt32 (ed.EncryptionAlgorithm.Content [1]),
ed.EncryptedContent);
}
public byte[] Encrypt (string algorithmOid, byte[] salt, int iterationCount, byte[] data)
{
byte[] result = null;
using (SymmetricAlgorithm sa = GetSymmetricAlgorithm (algorithmOid, salt, iterationCount)) {
ICryptoTransform ct = sa.CreateEncryptor ();
result = ct.TransformFinalBlock (data, 0, data.Length);
}
return result;
}
private void AddPrivateKey (PKCS8.PrivateKeyInfo pki)
{
byte[] privateKey = pki.PrivateKey;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
_keyBags.Add (PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p));
break;
case 0x30:
_keyBags.Add (PKCS8.PrivateKeyInfo.DecodeRSA (privateKey));
break;
default:
Array.Clear (privateKey, 0, privateKey.Length);
throw new CryptographicException ("Unknown private key format");
}
Array.Clear (privateKey, 0, privateKey.Length);
}
private void ReadSafeBag (ASN1 safeBag)
{
if (safeBag.Tag != 0x30)
throw new ArgumentException ("invalid safeBag");
ASN1 bagId = safeBag [0];
if (bagId.Tag != 0x06)
throw new ArgumentException ("invalid safeBag id");
ASN1 bagValue = safeBag [1];
string oid = ASN1Convert.ToOid (bagId);
switch (oid) {
case keyBag:
// NEED UNIT TEST
AddPrivateKey (new PKCS8.PrivateKeyInfo (bagValue.Value));
break;
case pkcs8ShroudedKeyBag:
PKCS8.EncryptedPrivateKeyInfo epki = new PKCS8.EncryptedPrivateKeyInfo (bagValue.Value);
byte[] decrypted = Decrypt (epki.Algorithm, epki.Salt, epki.IterationCount, epki.EncryptedData);
AddPrivateKey (new PKCS8.PrivateKeyInfo (decrypted));
Array.Clear (decrypted, 0, decrypted.Length);
break;
case certBag:
PKCS7.ContentInfo cert = new PKCS7.ContentInfo (bagValue.Value);
if (cert.ContentType != x509Certificate)
throw new NotSupportedException ("unsupport certificate type");
X509Certificate x509 = new X509Certificate (cert.Content [0].Value);
_certs.Add (x509);
break;
case crlBag:
// TODO
break;
case secretBag:
// TODO
break;
case safeContentsBag:
// TODO - ? recurse ?
break;
default:
throw new ArgumentException ("unknown safeBag oid");
}
if (safeBag.Count > 2) {
ASN1 bagAttributes = safeBag [2];
if (bagAttributes.Tag != 0x31)
throw new ArgumentException ("invalid safeBag attributes id");
for (int i = 0; i < bagAttributes.Count; i++) {
ASN1 pkcs12Attribute = bagAttributes[i];
if (pkcs12Attribute.Tag != 0x30)
throw new ArgumentException ("invalid PKCS12 attributes id");
ASN1 attrId = pkcs12Attribute [0];
if (attrId.Tag != 0x06)
throw new ArgumentException ("invalid attribute id");
string attrOid = ASN1Convert.ToOid (attrId);
ASN1 attrValues = pkcs12Attribute[1];
for (int j = 0; j < attrValues.Count; j++) {
ASN1 attrValue = attrValues[j];
switch (attrOid) {
case PKCS9.friendlyName:
if (attrValue.Tag != 0x1e)
throw new ArgumentException ("invalid attribute value id");
break;
case PKCS9.localKeyId:
if (attrValue.Tag != 0x04)
throw new ArgumentException ("invalid attribute value id");
break;
default:
// Unknown OID -- don't check Tag
break;
}
}
}
}
_safeBags.Add (new SafeBag(oid, safeBag));
}
private ASN1 Pkcs8ShroudedKeyBagSafeBag (AsymmetricAlgorithm aa, IDictionary attributes)
{
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo ();
if (aa is RSA) {
pki.Algorithm = "1.2.840.113549.1.1.1";
pki.PrivateKey = PKCS8.PrivateKeyInfo.Encode ((RSA)aa);
}
else if (aa is DSA) {
pki.Algorithm = null;
pki.PrivateKey = PKCS8.PrivateKeyInfo.Encode ((DSA)aa);
}
else
throw new CryptographicException ("Unknown asymmetric algorithm {0}", aa.ToString ());
PKCS8.EncryptedPrivateKeyInfo epki = new PKCS8.EncryptedPrivateKeyInfo ();
epki.Algorithm = pbeWithSHAAnd3KeyTripleDESCBC;
epki.IterationCount = _iterations;
epki.EncryptedData = Encrypt (pbeWithSHAAnd3KeyTripleDESCBC, epki.Salt, _iterations, pki.GetBytes ());
ASN1 safeBag = new ASN1 (0x30);
safeBag.Add (ASN1Convert.FromOid (pkcs8ShroudedKeyBag));
ASN1 bagValue = new ASN1 (0xA0);
bagValue.Add (new ASN1 (epki.GetBytes ()));
safeBag.Add (bagValue);
if (attributes != null) {
ASN1 bagAttributes = new ASN1 (0x31);
IDictionaryEnumerator de = attributes.GetEnumerator ();
while (de.MoveNext ()) {
string oid = (string)de.Key;
switch (oid) {
case PKCS9.friendlyName:
ArrayList names = (ArrayList)de.Value;
if (names.Count > 0) {
ASN1 pkcs12Attribute = new ASN1 (0x30);
pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.friendlyName));
ASN1 attrValues = new ASN1 (0x31);
foreach (byte[] name in names) {
ASN1 attrValue = new ASN1 (0x1e);
attrValue.Value = name;
attrValues.Add (attrValue);
}
pkcs12Attribute.Add (attrValues);
bagAttributes.Add (pkcs12Attribute);
}
break;
case PKCS9.localKeyId:
ArrayList keys = (ArrayList)de.Value;
if (keys.Count > 0) {
ASN1 pkcs12Attribute = new ASN1 (0x30);
pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.localKeyId));
ASN1 attrValues = new ASN1 (0x31);
foreach (byte[] key in keys) {
ASN1 attrValue = new ASN1 (0x04);
attrValue.Value = key;
attrValues.Add (attrValue);
}
pkcs12Attribute.Add (attrValues);
bagAttributes.Add (pkcs12Attribute);
}
break;
default:
break;
}
}
if (bagAttributes.Count > 0) {
safeBag.Add (bagAttributes);
}
}
return safeBag;
}
private ASN1 KeyBagSafeBag (AsymmetricAlgorithm aa, IDictionary attributes)
{
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo ();
if (aa is RSA) {
pki.Algorithm = "1.2.840.113549.1.1.1";
pki.PrivateKey = PKCS8.PrivateKeyInfo.Encode ((RSA)aa);
}
else if (aa is DSA) {
pki.Algorithm = null;
pki.PrivateKey = PKCS8.PrivateKeyInfo.Encode ((DSA)aa);
}
else
throw new CryptographicException ("Unknown asymmetric algorithm {0}", aa.ToString ());
ASN1 safeBag = new ASN1 (0x30);
safeBag.Add (ASN1Convert.FromOid (keyBag));
ASN1 bagValue = new ASN1 (0xA0);
bagValue.Add (new ASN1 (pki.GetBytes ()));
safeBag.Add (bagValue);
if (attributes != null) {
ASN1 bagAttributes = new ASN1 (0x31);
IDictionaryEnumerator de = attributes.GetEnumerator ();
while (de.MoveNext ()) {
string oid = (string)de.Key;
switch (oid) {
case PKCS9.friendlyName:
ArrayList names = (ArrayList)de.Value;
if (names.Count > 0) {
ASN1 pkcs12Attribute = new ASN1 (0x30);
pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.friendlyName));
ASN1 attrValues = new ASN1 (0x31);
foreach (byte[] name in names) {
ASN1 attrValue = new ASN1 (0x1e);
attrValue.Value = name;
attrValues.Add (attrValue);
}
pkcs12Attribute.Add (attrValues);
bagAttributes.Add (pkcs12Attribute);
}
break;
case PKCS9.localKeyId:
ArrayList keys = (ArrayList)de.Value;
if (keys.Count > 0) {
ASN1 pkcs12Attribute = new ASN1 (0x30);
pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.localKeyId));
ASN1 attrValues = new ASN1 (0x31);
foreach (byte[] key in keys) {
ASN1 attrValue = new ASN1 (0x04);
attrValue.Value = key;
attrValues.Add (attrValue);
}
pkcs12Attribute.Add (attrValues);
bagAttributes.Add (pkcs12Attribute);
}
break;
default:
break;
}
}
if (bagAttributes.Count > 0) {
safeBag.Add (bagAttributes);
}
}
return safeBag;
}
private ASN1 CertificateSafeBag (X509Certificate x509, IDictionary attributes)
{
ASN1 encapsulatedCertificate = new ASN1 (0x04, x509.RawData);
PKCS7.ContentInfo ci = new PKCS7.ContentInfo ();
ci.ContentType = x509Certificate;
ci.Content.Add (encapsulatedCertificate);
ASN1 bagValue = new ASN1 (0xA0);
bagValue.Add (ci.ASN1);
ASN1 safeBag = new ASN1 (0x30);
safeBag.Add (ASN1Convert.FromOid (certBag));
safeBag.Add (bagValue);
if (attributes != null) {
ASN1 bagAttributes = new ASN1 (0x31);
IDictionaryEnumerator de = attributes.GetEnumerator ();
while (de.MoveNext ()) {
string oid = (string)de.Key;
switch (oid) {
case PKCS9.friendlyName:
ArrayList names = (ArrayList)de.Value;
if (names.Count > 0) {
ASN1 pkcs12Attribute = new ASN1 (0x30);
pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.friendlyName));
ASN1 attrValues = new ASN1 (0x31);
foreach (byte[] name in names) {
ASN1 attrValue = new ASN1 (0x1e);
attrValue.Value = name;
attrValues.Add (attrValue);
}
pkcs12Attribute.Add (attrValues);
bagAttributes.Add (pkcs12Attribute);
}
break;
case PKCS9.localKeyId:
ArrayList keys = (ArrayList)de.Value;
if (keys.Count > 0) {
ASN1 pkcs12Attribute = new ASN1 (0x30);
pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.localKeyId));
ASN1 attrValues = new ASN1 (0x31);
foreach (byte[] key in keys) {
ASN1 attrValue = new ASN1 (0x04);
attrValue.Value = key;
attrValues.Add (attrValue);
}
pkcs12Attribute.Add (attrValues);
bagAttributes.Add (pkcs12Attribute);
}
break;
default:
break;
}
}
if (bagAttributes.Count > 0) {
safeBag.Add (bagAttributes);
}
}
return safeBag;
}
private byte[] MAC (byte[] password, byte[] salt, int iterations, byte[] data)
{
PKCS12.DeriveBytes pd = new PKCS12.DeriveBytes ();
pd.HashName = "SHA1";
pd.Password = password;
pd.Salt = salt;
pd.IterationCount = iterations;
HMACSHA1 hmac = (HMACSHA1) HMACSHA1.Create ();
hmac.Key = pd.DeriveMAC (20);
return hmac.ComputeHash (data, 0, data.Length);
}
/*
* SafeContents ::= SEQUENCE OF SafeBag
*
* SafeBag ::= SEQUENCE {
* bagId BAG-TYPE.&id ({PKCS12BagSet}),
* bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),
* bagAttributes SET OF PKCS12Attribute OPTIONAL
* }
*/
public byte[] GetBytes ()
{
// TODO (incomplete)
ASN1 safeBagSequence = new ASN1 (0x30);
// Sync Safe Bag list since X509CertificateCollection may be updated
ArrayList scs = new ArrayList ();
foreach (SafeBag sb in _safeBags) {
if (sb.BagOID.Equals (certBag)) {
ASN1 safeBag = sb.ASN1;
ASN1 bagValue = safeBag [1];
PKCS7.ContentInfo cert = new PKCS7.ContentInfo (bagValue.Value);
scs.Add (new X509Certificate (cert.Content [0].Value));
}
}
ArrayList addcerts = new ArrayList ();
ArrayList removecerts = new ArrayList ();
foreach (X509Certificate c in Certificates) {
bool found = false;
foreach (X509Certificate lc in scs) {
if (Compare (c.RawData, lc.RawData)) {
found = true;
}
}
if (!found) {
addcerts.Add (c);
}
}
foreach (X509Certificate c in scs) {
bool found = false;
foreach (X509Certificate lc in Certificates) {
if (Compare (c.RawData, lc.RawData)) {
found = true;
}
}
if (!found) {
removecerts.Add (c);
}
}
foreach (X509Certificate c in removecerts) {
RemoveCertificate (c);
}
foreach (X509Certificate c in addcerts) {
AddCertificate (c);
}
// Sync done
if (_safeBags.Count > 0) {
ASN1 certsSafeBag = new ASN1 (0x30);
foreach (SafeBag sb in _safeBags) {
if (sb.BagOID.Equals (certBag)) {
certsSafeBag.Add (sb.ASN1);
}
}
if (certsSafeBag.Count > 0) {
byte[] certsSalt = new byte [8];
RNG.GetBytes (certsSalt);
ASN1 seqParams = new ASN1 (0x30);
seqParams.Add (new ASN1 (0x04, certsSalt));
seqParams.Add (ASN1Convert.FromInt32 (_iterations));
ASN1 seqPbe = new ASN1 (0x30);
seqPbe.Add (ASN1Convert.FromOid (pbeWithSHAAnd3KeyTripleDESCBC));
seqPbe.Add (seqParams);
byte[] encrypted = Encrypt (pbeWithSHAAnd3KeyTripleDESCBC, certsSalt, _iterations, certsSafeBag.GetBytes ());
ASN1 encryptedCerts = new ASN1 (0x80, encrypted);
ASN1 seq = new ASN1 (0x30);
seq.Add (ASN1Convert.FromOid (PKCS7.Oid.data));
seq.Add (seqPbe);
seq.Add (encryptedCerts);
ASN1 certsVersion = new ASN1 (0x02, new byte [1] { 0x00 });
ASN1 encData = new ASN1 (0x30);
encData.Add (certsVersion);
encData.Add (seq);
ASN1 certsContent = new ASN1 (0xA0);
certsContent.Add (encData);
PKCS7.ContentInfo bag = new PKCS7.ContentInfo (PKCS7.Oid.encryptedData);
bag.Content = certsContent;
safeBagSequence.Add (bag.ASN1);
}
}
if (_safeBags.Count > 0) {
ASN1 safeContents = new ASN1 (0x30);
foreach (SafeBag sb in _safeBags) {
if (sb.BagOID.Equals (keyBag) ||
sb.BagOID.Equals (pkcs8ShroudedKeyBag)) {
safeContents.Add (sb.ASN1);
}
}
if (safeContents.Count > 0) {
ASN1 content = new ASN1 (0xA0);
content.Add (new ASN1 (0x04, safeContents.GetBytes ()));
PKCS7.ContentInfo keyBag = new PKCS7.ContentInfo (PKCS7.Oid.data);
keyBag.Content = content;
safeBagSequence.Add (keyBag.ASN1);
}
}
ASN1 encapsulates = new ASN1 (0x04, safeBagSequence.GetBytes ());
ASN1 ci = new ASN1 (0xA0);
ci.Add (encapsulates);
PKCS7.ContentInfo authSafe = new PKCS7.ContentInfo (PKCS7.Oid.data);
authSafe.Content = ci;
ASN1 macData = new ASN1 (0x30);
if (_password != null) {
// only for password based encryption
byte[] salt = new byte [20];
RNG.GetBytes (salt);
byte[] macValue = MAC (_password, salt, _iterations, authSafe.Content [0].Value);
ASN1 oidSeq = new ASN1 (0x30);
oidSeq.Add (ASN1Convert.FromOid ("1.3.14.3.2.26")); // SHA1
oidSeq.Add (new ASN1 (0x05));
ASN1 mac = new ASN1 (0x30);
mac.Add (oidSeq);
mac.Add (new ASN1 (0x04, macValue));
macData.Add (mac);
macData.Add (new ASN1 (0x04, salt));
macData.Add (ASN1Convert.FromInt32 (_iterations));
}
ASN1 version = new ASN1 (0x02, new byte [1] { 0x03 });
ASN1 pfx = new ASN1 (0x30);
pfx.Add (version);
pfx.Add (authSafe.ASN1);
if (macData.Count > 0) {
// only for password based encryption
pfx.Add (macData);
}
return pfx.GetBytes ();
}
public void AddCertificate (X509Certificate cert)
{
AddCertificate (cert, null);
}
public void AddCertificate (X509Certificate cert, IDictionary attributes)
{
bool found = false;
for (int i = 0; !found && i < _safeBags.Count; i++) {
SafeBag sb = (SafeBag)_safeBags [i];
if (sb.BagOID.Equals (certBag)) {
ASN1 safeBag = sb.ASN1;
ASN1 bagValue = safeBag [1];
PKCS7.ContentInfo crt = new PKCS7.ContentInfo (bagValue.Value);
X509Certificate c = new X509Certificate (crt.Content [0].Value);
if (Compare (cert.RawData, c.RawData)) {
found = true;
}
}
}
if (!found) {
_safeBags.Add (new SafeBag (certBag, CertificateSafeBag (cert, attributes)));
_certsChanged = true;
}
}
public void RemoveCertificate (X509Certificate cert)
{
RemoveCertificate (cert, null);
}
public void RemoveCertificate (X509Certificate cert, IDictionary attrs)
{
int certIndex = -1;
for (int i = 0; certIndex == -1 && i < _safeBags.Count; i++) {
SafeBag sb = (SafeBag)_safeBags [i];
if (sb.BagOID.Equals (certBag)) {
ASN1 safeBag = sb.ASN1;
ASN1 bagValue = safeBag [1];
PKCS7.ContentInfo crt = new PKCS7.ContentInfo (bagValue.Value);
X509Certificate c = new X509Certificate (crt.Content [0].Value);
if (Compare (cert.RawData, c.RawData)) {
if (attrs != null) {
if (safeBag.Count == 3) {
ASN1 bagAttributes = safeBag [2];
int bagAttributesFound = 0;
for (int j = 0; j < bagAttributes.Count; j++) {
ASN1 pkcs12Attribute = bagAttributes [j];
ASN1 attrId = pkcs12Attribute [0];
string ao = ASN1Convert.ToOid (attrId);
ArrayList dattrValues = (ArrayList)attrs [ao];
if (dattrValues != null) {
ASN1 attrValues = pkcs12Attribute [1];
if (dattrValues.Count == attrValues.Count) {
int attrValuesFound = 0;
for (int k = 0; k < attrValues.Count; k++) {
ASN1 attrValue = attrValues [k];
byte[] value = (byte[])dattrValues [k];
if (Compare (value, attrValue.Value)) {
attrValuesFound += 1;
}
}
if (attrValuesFound == attrValues.Count) {
bagAttributesFound += 1;
}
}
}
}
if (bagAttributesFound == bagAttributes.Count) {
certIndex = i;
}
}
} else {
certIndex = i;
}
}
}
}
if (certIndex != -1) {
_safeBags.RemoveAt (certIndex);
_certsChanged = true;
}
}
private bool CompareAsymmetricAlgorithm (AsymmetricAlgorithm a1, AsymmetricAlgorithm a2)
{
// fast path
if (a1.KeySize != a2.KeySize)
return false;
// compare public keys - if they match we can assume the private match too
return (a1.ToXmlString (false) == a2.ToXmlString (false));
}
public void AddPkcs8ShroudedKeyBag (AsymmetricAlgorithm aa)
{
AddPkcs8ShroudedKeyBag (aa, null);
}
public void AddPkcs8ShroudedKeyBag (AsymmetricAlgorithm aa, IDictionary attributes)
{
bool found = false;
for (int i = 0; !found && i < _safeBags.Count; i++) {
SafeBag sb = (SafeBag)_safeBags [i];
if (sb.BagOID.Equals (pkcs8ShroudedKeyBag)) {
ASN1 bagValue = sb.ASN1 [1];
PKCS8.EncryptedPrivateKeyInfo epki = new PKCS8.EncryptedPrivateKeyInfo (bagValue.Value);
byte[] decrypted = Decrypt (epki.Algorithm, epki.Salt, epki.IterationCount, epki.EncryptedData);
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (decrypted);
byte[] privateKey = pki.PrivateKey;
AsymmetricAlgorithm saa = null;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
saa = PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p);
break;
case 0x30:
saa = PKCS8.PrivateKeyInfo.DecodeRSA (privateKey);
break;
default:
Array.Clear (decrypted, 0, decrypted.Length);
Array.Clear (privateKey, 0, privateKey.Length);
throw new CryptographicException ("Unknown private key format");
}
Array.Clear (decrypted, 0, decrypted.Length);
Array.Clear (privateKey, 0, privateKey.Length);
if (CompareAsymmetricAlgorithm (aa , saa)) {
found = true;
}
}
}
if (!found) {
_safeBags.Add (new SafeBag (pkcs8ShroudedKeyBag, Pkcs8ShroudedKeyBagSafeBag (aa, attributes)));
_keyBagsChanged = true;
}
}
public void RemovePkcs8ShroudedKeyBag (AsymmetricAlgorithm aa)
{
int aaIndex = -1;
for (int i = 0; aaIndex == -1 && i < _safeBags.Count; i++) {
SafeBag sb = (SafeBag)_safeBags [i];
if (sb.BagOID.Equals (pkcs8ShroudedKeyBag)) {
ASN1 bagValue = sb.ASN1 [1];
PKCS8.EncryptedPrivateKeyInfo epki = new PKCS8.EncryptedPrivateKeyInfo (bagValue.Value);
byte[] decrypted = Decrypt (epki.Algorithm, epki.Salt, epki.IterationCount, epki.EncryptedData);
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (decrypted);
byte[] privateKey = pki.PrivateKey;
AsymmetricAlgorithm saa = null;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
saa = PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p);
break;
case 0x30:
saa = PKCS8.PrivateKeyInfo.DecodeRSA (privateKey);
break;
default:
Array.Clear (decrypted, 0, decrypted.Length);
Array.Clear (privateKey, 0, privateKey.Length);
throw new CryptographicException ("Unknown private key format");
}
Array.Clear (decrypted, 0, decrypted.Length);
Array.Clear (privateKey, 0, privateKey.Length);
if (CompareAsymmetricAlgorithm (aa, saa)) {
aaIndex = i;
}
}
}
if (aaIndex != -1) {
_safeBags.RemoveAt (aaIndex);
_keyBagsChanged = true;
}
}
public void AddKeyBag (AsymmetricAlgorithm aa)
{
AddKeyBag (aa, null);
}
public void AddKeyBag (AsymmetricAlgorithm aa, IDictionary attributes)
{
bool found = false;
for (int i = 0; !found && i < _safeBags.Count; i++) {
SafeBag sb = (SafeBag)_safeBags [i];
if (sb.BagOID.Equals (keyBag)) {
ASN1 bagValue = sb.ASN1 [1];
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (bagValue.Value);
byte[] privateKey = pki.PrivateKey;
AsymmetricAlgorithm saa = null;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
saa = PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p);
break;
case 0x30:
saa = PKCS8.PrivateKeyInfo.DecodeRSA (privateKey);
break;
default:
Array.Clear (privateKey, 0, privateKey.Length);
throw new CryptographicException ("Unknown private key format");
}
Array.Clear (privateKey, 0, privateKey.Length);
if (CompareAsymmetricAlgorithm (aa, saa)) {
found = true;
}
}
}
if (!found) {
_safeBags.Add (new SafeBag (keyBag, KeyBagSafeBag (aa, attributes)));
_keyBagsChanged = true;
}
}
public void RemoveKeyBag (AsymmetricAlgorithm aa)
{
int aaIndex = -1;
for (int i = 0; aaIndex == -1 && i < _safeBags.Count; i++) {
SafeBag sb = (SafeBag)_safeBags [i];
if (sb.BagOID.Equals (keyBag)) {
ASN1 bagValue = sb.ASN1 [1];
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (bagValue.Value);
byte[] privateKey = pki.PrivateKey;
AsymmetricAlgorithm saa = null;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
saa = PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p);
break;
case 0x30:
saa = PKCS8.PrivateKeyInfo.DecodeRSA (privateKey);
break;
default:
Array.Clear (privateKey, 0, privateKey.Length);
throw new CryptographicException ("Unknown private key format");
}
Array.Clear (privateKey, 0, privateKey.Length);
if (CompareAsymmetricAlgorithm (aa, saa)) {
aaIndex = i;
}
}
}
if (aaIndex != -1) {
_safeBags.RemoveAt (aaIndex);
_keyBagsChanged = true;
}
}
public AsymmetricAlgorithm GetAsymmetricAlgorithm (IDictionary attrs)
{
foreach (SafeBag sb in _safeBags) {
if (sb.BagOID.Equals (keyBag) || sb.BagOID.Equals (pkcs8ShroudedKeyBag)) {
ASN1 safeBag = sb.ASN1;
if (safeBag.Count == 3) {
ASN1 bagAttributes = safeBag [2];
int bagAttributesFound = 0;
for (int i = 0; i < bagAttributes.Count; i++) {
ASN1 pkcs12Attribute = bagAttributes [i];
ASN1 attrId = pkcs12Attribute [0];
string ao = ASN1Convert.ToOid (attrId);
ArrayList dattrValues = (ArrayList)attrs [ao];
if (dattrValues != null) {
ASN1 attrValues = pkcs12Attribute [1];
if (dattrValues.Count == attrValues.Count) {
int attrValuesFound = 0;
for (int j = 0; j < attrValues.Count; j++) {
ASN1 attrValue = attrValues [j];
byte[] value = (byte[])dattrValues [j];
if (Compare (value, attrValue.Value)) {
attrValuesFound += 1;
}
}
if (attrValuesFound == attrValues.Count) {
bagAttributesFound += 1;
}
}
}
}
if (bagAttributesFound == bagAttributes.Count) {
ASN1 bagValue = safeBag [1];
AsymmetricAlgorithm aa = null;
if (sb.BagOID.Equals (keyBag)) {
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (bagValue.Value);
byte[] privateKey = pki.PrivateKey;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
aa = PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p);
break;
case 0x30:
aa = PKCS8.PrivateKeyInfo.DecodeRSA (privateKey);
break;
default:
break;
}
Array.Clear (privateKey, 0, privateKey.Length);
} else if (sb.BagOID.Equals (pkcs8ShroudedKeyBag)) {
PKCS8.EncryptedPrivateKeyInfo epki = new PKCS8.EncryptedPrivateKeyInfo (bagValue.Value);
byte[] decrypted = Decrypt (epki.Algorithm, epki.Salt, epki.IterationCount, epki.EncryptedData);
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (decrypted);
byte[] privateKey = pki.PrivateKey;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
aa = PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p);
break;
case 0x30:
aa = PKCS8.PrivateKeyInfo.DecodeRSA (privateKey);
break;
default:
break;
}
Array.Clear (privateKey, 0, privateKey.Length);
Array.Clear (decrypted, 0, decrypted.Length);
}
return aa;
}
}
}
}
return null;
}
public X509Certificate GetCertificate (IDictionary attrs)
{
foreach (SafeBag sb in _safeBags) {
if (sb.BagOID.Equals (certBag)) {
ASN1 safeBag = sb.ASN1;
if (safeBag.Count == 3) {
ASN1 bagAttributes = safeBag [2];
int bagAttributesFound = 0;
for (int i = 0; i < bagAttributes.Count; i++) {
ASN1 pkcs12Attribute = bagAttributes [i];
ASN1 attrId = pkcs12Attribute [0];
string ao = ASN1Convert.ToOid (attrId);
ArrayList dattrValues = (ArrayList)attrs [ao];
if (dattrValues != null) {
ASN1 attrValues = pkcs12Attribute [1];
if (dattrValues.Count == attrValues.Count) {
int attrValuesFound = 0;
for (int j = 0; j < attrValues.Count; j++) {
ASN1 attrValue = attrValues [j];
byte[] value = (byte[])dattrValues [j];
if (Compare (value, attrValue.Value)) {
attrValuesFound += 1;
}
}
if (attrValuesFound == attrValues.Count) {
bagAttributesFound += 1;
}
}
}
}
if (bagAttributesFound == bagAttributes.Count) {
ASN1 bagValue = safeBag [1];
PKCS7.ContentInfo crt = new PKCS7.ContentInfo (bagValue.Value);
return new X509Certificate (crt.Content [0].Value);
}
}
}
}
return null;
}
public IDictionary GetAttributes (AsymmetricAlgorithm aa)
{
IDictionary result = new Hashtable ();
foreach (SafeBag sb in _safeBags) {
if (sb.BagOID.Equals (keyBag) || sb.BagOID.Equals (pkcs8ShroudedKeyBag)) {
ASN1 safeBag = sb.ASN1;
ASN1 bagValue = safeBag [1];
AsymmetricAlgorithm saa = null;
if (sb.BagOID.Equals (keyBag)) {
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (bagValue.Value);
byte[] privateKey = pki.PrivateKey;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
saa = PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p);
break;
case 0x30:
saa = PKCS8.PrivateKeyInfo.DecodeRSA (privateKey);
break;
default:
break;
}
Array.Clear (privateKey, 0, privateKey.Length);
} else if (sb.BagOID.Equals (pkcs8ShroudedKeyBag)) {
PKCS8.EncryptedPrivateKeyInfo epki = new PKCS8.EncryptedPrivateKeyInfo (bagValue.Value);
byte[] decrypted = Decrypt (epki.Algorithm, epki.Salt, epki.IterationCount, epki.EncryptedData);
PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (decrypted);
byte[] privateKey = pki.PrivateKey;
switch (privateKey [0]) {
case 0x02:
DSAParameters p = new DSAParameters (); // FIXME
saa = PKCS8.PrivateKeyInfo.DecodeDSA (privateKey, p);
break;
case 0x30:
saa = PKCS8.PrivateKeyInfo.DecodeRSA (privateKey);
break;
default:
break;
}
Array.Clear (privateKey, 0, privateKey.Length);
Array.Clear (decrypted, 0, decrypted.Length);
}
if (saa != null && CompareAsymmetricAlgorithm (saa, aa)) {
if (safeBag.Count == 3) {
ASN1 bagAttributes = safeBag [2];
for (int i = 0; i < bagAttributes.Count; i++) {
ASN1 pkcs12Attribute = bagAttributes [i];
ASN1 attrId = pkcs12Attribute [0];
string aOid = ASN1Convert.ToOid (attrId);
ArrayList aValues = new ArrayList ();
ASN1 attrValues = pkcs12Attribute [1];
for (int j = 0; j < attrValues.Count; j++) {
ASN1 attrValue = attrValues [j];
aValues.Add (attrValue.Value);
}
result.Add (aOid, aValues);
}
}
}
}
}
return result;
}
public IDictionary GetAttributes (X509Certificate cert)
{
IDictionary result = new Hashtable ();
foreach (SafeBag sb in _safeBags) {
if (sb.BagOID.Equals (certBag)) {
ASN1 safeBag = sb.ASN1;
ASN1 bagValue = safeBag [1];
PKCS7.ContentInfo crt = new PKCS7.ContentInfo (bagValue.Value);
X509Certificate xc = new X509Certificate (crt.Content [0].Value);
if (Compare (cert.RawData, xc.RawData)) {
if (safeBag.Count == 3) {
ASN1 bagAttributes = safeBag [2];
for (int i = 0; i < bagAttributes.Count; i++) {
ASN1 pkcs12Attribute = bagAttributes [i];
ASN1 attrId = pkcs12Attribute [0];
string aOid = ASN1Convert.ToOid (attrId);
ArrayList aValues = new ArrayList ();
ASN1 attrValues = pkcs12Attribute [1];
for (int j = 0; j < attrValues.Count; j++) {
ASN1 attrValue = attrValues [j];
aValues.Add (attrValue.Value);
}
result.Add (aOid, aValues);
}
}
}
}
}
return result;
}
public void SaveToFile (string filename)
{
if (filename == null)
throw new ArgumentNullException ("filename");
using (FileStream fs = File.OpenWrite (filename)) {
byte[] data = GetBytes ();
fs.Write (data, 0, data.Length);
fs.Flush ();
fs.Close ();
}
}
public object Clone ()
{
PKCS12 clone = null;
if (_password != null) {
clone = new PKCS12 (GetBytes (), Encoding.BigEndianUnicode.GetString (_password));
} else {
clone = new PKCS12 (GetBytes ());
}
clone.IterationCount = this.IterationCount;
return clone;
}
// static
public const int CryptoApiPasswordLimit = 32;
static private int password_max_length = Int32.MaxValue;
// static properties
// MS CryptoAPI limits the password to a maximum of 31 characters
// other implementations, like OpenSSL, have no such limitation.
// Setting a maximum value will truncate the password length to
// ensure compatibility with MS's PFXImportCertStore API.
static public int MaximumPasswordLength {
get { return password_max_length; }
set {
if (value < CryptoApiPasswordLimit) {
string msg = Locale.GetText ("Maximum password length cannot be less than {0}.", CryptoApiPasswordLimit);
throw new ArgumentOutOfRangeException (msg);
}
password_max_length = value;
}
}
// static methods
static private byte[] LoadFile (string filename)
{
byte[] data = null;
using (FileStream fs = File.OpenRead (filename)) {
data = new byte [fs.Length];
fs.Read (data, 0, data.Length);
fs.Close ();
}
return data;
}
static public PKCS12 LoadFromFile (string filename)
{
if (filename == null)
throw new ArgumentNullException ("filename");
return new PKCS12 (LoadFile (filename));
}
static public PKCS12 LoadFromFile (string filename, string password)
{
if (filename == null)
throw new ArgumentNullException ("filename");
return new PKCS12 (LoadFile (filename), password);
}
}
}
|