asn_1.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. ASN.1 routines, implementation for libdvben50221
  3. an implementation for the High Level Common Interface
  4. Copyright (C) 2004, 2005 Manu Abraham <abraham.manu@gmail.com>
  5. Copyright (C) 2006 Andrew de Quincey (adq_dvb@lidskialf.net)
  6. This library is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU Lesser General Public License as
  8. published by the Free Software Foundation; either version 2.1 of
  9. the License, or (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU Lesser General Public License for more details.
  14. You should have received a copy of the GNU Lesser General Public
  15. License along with this library; if not, write to the Free Software
  16. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. */
  18. #include <stdio.h>
  19. #include "asn_1.h"
  20. int asn_1_decode(uint16_t * length, uint8_t * asn_1_array,
  21. uint32_t asn_1_array_len)
  22. {
  23. uint8_t length_field;
  24. if (asn_1_array_len < 1)
  25. return -1;
  26. length_field = asn_1_array[0];
  27. if (length_field < 0x80) {
  28. // there is only one word
  29. *length = length_field & 0x7f;
  30. return 1;
  31. } else if (length_field == 0x81) {
  32. if (asn_1_array_len < 2)
  33. return -1;
  34. *length = asn_1_array[1];
  35. return 2;
  36. } else if (length_field == 0x82) {
  37. if (asn_1_array_len < 3)
  38. return -1;
  39. *length = (asn_1_array[1] << 8) | asn_1_array[2];
  40. return 3;
  41. }
  42. return -1;
  43. }
  44. int asn_1_encode(uint16_t length, uint8_t * asn_1_array,
  45. uint32_t asn_1_array_len)
  46. {
  47. if (length < 0x80) {
  48. if (asn_1_array_len < 1)
  49. return -1;
  50. asn_1_array[0] = length & 0x7f;
  51. return 1;
  52. } else if (length < 0x100) {
  53. if (asn_1_array_len < 2)
  54. return -1;
  55. asn_1_array[0] = 0x81;
  56. asn_1_array[1] = length;
  57. return 2;
  58. } else {
  59. if (asn_1_array_len < 3)
  60. return -1;
  61. asn_1_array[0] = 0x82;
  62. asn_1_array[1] = length >> 8;
  63. asn_1_array[2] = length;
  64. return 3;
  65. }
  66. // never reached
  67. }