Pkcs12Utilities.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
  8. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
  9. {
  10. /**
  11. * Utility class for reencoding PKCS#12 files to definite length.
  12. */
  13. public class Pkcs12Utilities
  14. {
  15. /**
  16. * Just re-encode the outer layer of the PKCS#12 file to definite length encoding.
  17. *
  18. * @param berPKCS12File - original PKCS#12 file
  19. * @return a byte array representing the DER encoding of the PFX structure
  20. * @throws IOException
  21. */
  22. public static byte[] ConvertToDefiniteLength(
  23. byte[] berPkcs12File)
  24. {
  25. Pfx pfx = Pfx.GetInstance(berPkcs12File);
  26. return pfx.GetEncoded(Asn1Encodable.Der);
  27. }
  28. /**
  29. * Re-encode the PKCS#12 structure to definite length encoding at the inner layer
  30. * as well, recomputing the MAC accordingly.
  31. *
  32. * @param berPKCS12File - original PKCS12 file.
  33. * @param provider - provider to use for MAC calculation.
  34. * @return a byte array representing the DER encoding of the PFX structure.
  35. * @throws IOException on parsing, encoding errors.
  36. */
  37. public static byte[] ConvertToDefiniteLength(
  38. byte[] berPkcs12File,
  39. char[] passwd)
  40. {
  41. Pfx pfx = Pfx.GetInstance(berPkcs12File);
  42. ContentInfo info = pfx.AuthSafe;
  43. Asn1OctetString content = Asn1OctetString.GetInstance(info.Content);
  44. Asn1Object obj = Asn1Object.FromByteArray(content.GetOctets());
  45. info = new ContentInfo(info.ContentType, new DerOctetString(obj.GetEncoded(Asn1Encodable.Der)));
  46. MacData mData = pfx.MacData;
  47. try
  48. {
  49. int itCount = mData.IterationCount.IntValue;
  50. byte[] data = Asn1OctetString.GetInstance(info.Content).GetOctets();
  51. byte[] res = Pkcs12Store.CalculatePbeMac(
  52. mData.Mac.AlgorithmID.Algorithm, mData.GetSalt(), itCount, passwd, false, data);
  53. AlgorithmIdentifier algId = new AlgorithmIdentifier(
  54. mData.Mac.AlgorithmID.Algorithm, DerNull.Instance);
  55. DigestInfo dInfo = new DigestInfo(algId, res);
  56. mData = new MacData(dInfo, mData.GetSalt(), itCount);
  57. }
  58. catch (Exception e)
  59. {
  60. throw new IOException("error constructing MAC: " + e.ToString());
  61. }
  62. pfx = new Pfx(info, mData);
  63. return pfx.GetEncoded(Asn1Encodable.Der);
  64. }
  65. }
  66. }
  67. #pragma warning restore
  68. #endif