暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Util.cs 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.IO;
  3. namespace LCLib.Asn1Processor
  4. {
  5. /// <summary>
  6. /// Summary description for Util.
  7. /// </summary>
  8. internal class Asn1Util
  9. {
  10. public static int BytePrecision(ulong value)
  11. {
  12. int i;
  13. for (i = sizeof(ulong); i > 0; --i)
  14. if ((value >> (i - 1) * 8) != 0)
  15. break;
  16. return i;
  17. }
  18. public static int DERLengthEncode(Stream xdata, ulong length)
  19. {
  20. int i = 0;
  21. if (length <= 0x7f)
  22. {
  23. xdata.WriteByte((byte)length);
  24. i++;
  25. }
  26. else
  27. {
  28. xdata.WriteByte((byte)(BytePrecision(length) | 0x80));
  29. i++;
  30. for (int j = BytePrecision((ulong)length); j > 0; --j)
  31. {
  32. xdata.WriteByte((byte)(length >> (j - 1) * 8));
  33. i++;
  34. }
  35. }
  36. return i;
  37. }
  38. public static long DerLengthDecode(Stream bt)
  39. {
  40. long length = 0;
  41. byte b;
  42. b = (byte)bt.ReadByte();
  43. if ((b & 0x80) == 0)
  44. {
  45. length = b;
  46. }
  47. else
  48. {
  49. long lengthBytes = b & 0x7f;
  50. if (lengthBytes == 0)
  51. {
  52. throw new Exception("Indefinite length.");
  53. }
  54. length = 0;
  55. while (lengthBytes-- > 0)
  56. {
  57. if ((length >> (8 * (sizeof(long) - 1))) > 0)
  58. throw new Exception("Length overflow.");
  59. b = (byte)bt.ReadByte();
  60. length = (length << 8) | b;
  61. }
  62. }
  63. return length;
  64. }
  65. private Asn1Util()
  66. {
  67. }
  68. }
  69. }