NMBStringCoder.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package de.tudarmstadt.informatik.hostage.protocol.smbutils;
  2. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  3. /**
  4. * Used to encode and decode a String into a byte array so that they can be used in NetBIOS.
  5. * @author Wulf Pfeiffer
  6. */
  7. public class NMBStringCoder {
  8. /**
  9. * Decodes a netbios name as byte array to its proper String value.
  10. * @param name bytes.
  11. * @return String.
  12. */
  13. public static String decodeNBNSName(byte[] name) {
  14. byte a_ascii = (byte) 'A';
  15. byte[] reducedA = new byte[name.length];
  16. for (int i = 0; i < name.length; i++) {
  17. reducedA[i] = (byte) (name[i] - a_ascii);
  18. }
  19. byte[] converted = new byte[reducedA.length / 2];
  20. for (int i = 0, j = 0; i < name.length && j < converted.length; i += 2, j++) {
  21. byte b1 = (byte) (reducedA[i] << 4);
  22. byte b2 = reducedA[i + 1];
  23. converted[j] = (byte) (b1 | b2);
  24. }
  25. return new String(converted);
  26. }
  27. /**
  28. * Encodes a String into its netbios name as byte array.
  29. * @param name.
  30. * @return netbios name.
  31. */
  32. public static byte[] encodeNBNSName(byte[] name) {
  33. byte a_ascii = (byte) 'A';
  34. byte[] bytes = name;
  35. byte[] converted = new byte[bytes.length * 2];
  36. for (int i = 0, j = 0; i < bytes.length && j < converted.length; i++, j += 2) {
  37. converted[j] = (byte) (bytes[i] >> 4);
  38. converted[j + 1] = (byte) (bytes[i] & 0x0F);
  39. }
  40. byte[] addedA = new byte[converted.length];
  41. for (int i = 0; i < converted.length; i++) {
  42. addedA[i] = (byte) (converted[i] + a_ascii);
  43. }
  44. return addedA;
  45. }
  46. /**
  47. * Wraps a NetBIOS name with the required start and end bytes and some more informations.
  48. * @param name netbios name.
  49. * @param service NBNDSService.
  50. * @return wrapped content.
  51. */
  52. public static byte[] wrapNBNSName(byte[] name, int service) {
  53. byte[] nameStart = { 0x20 };
  54. byte[] namePadding = null;
  55. if (name.length < 32) {
  56. int paddingLen = 32 - name.length;
  57. namePadding = new byte[paddingLen];
  58. for (int i = 0; i < namePadding.length; i += 2) {
  59. if (i == namePadding.length - 2) {
  60. byte[] serviceBytes = NBNSService.getServiceBytes(service);
  61. namePadding[i] = serviceBytes[0];
  62. namePadding[i + 1] = serviceBytes[1];
  63. } else {
  64. namePadding[i] = 0x43;
  65. namePadding[i + 1] = 0x041;
  66. }
  67. }
  68. }
  69. byte[] nameEnd = { 0x00 };
  70. return HelperUtils.concat(nameStart, name, namePadding, nameEnd);
  71. }
  72. }