NMBStringCoder.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package de.tudarmstadt.informatik.hostage.protocol.SMBUtils;
  2. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  3. public class NMBStringCoder {
  4. public static String decodeNBNSName(byte[] name) {
  5. byte a_ascii = (byte) 'A';
  6. byte[] reducedA = new byte[name.length];
  7. for (int i = 0; i < name.length; i++) {
  8. reducedA[i] = (byte)(name[i] - a_ascii);
  9. }
  10. byte[] converted = new byte[reducedA.length / 2];
  11. for (int i = 0, j = 0; i < name.length && j < converted.length; i+=2, j++) {
  12. byte b1 = (byte) (reducedA[i]<<4);
  13. byte b2 = reducedA[i+1];
  14. converted[j] = (byte) (b1 | b2);
  15. }
  16. return new String(converted);
  17. }
  18. public static byte[] encodeNBNSName(byte[] name) {
  19. byte a_ascii = (byte) 'A';
  20. byte[] bytes = name;
  21. byte[] converted = new byte[bytes.length * 2];
  22. for (int i = 0, j = 0; i < bytes.length && j < converted.length; i++, j+=2) {
  23. converted[j] = (byte)(bytes[i]>>4);
  24. converted[j+1] = (byte)(bytes[i] & 0x0F);
  25. }
  26. byte[] addedA = new byte[converted.length];
  27. for (int i = 0; i < converted.length; i++) {
  28. addedA[i] = (byte) (converted[i] + a_ascii);
  29. }
  30. return addedA;
  31. }
  32. public static byte[] wrapNBNSName(byte[] name, int service) {
  33. byte[] nameStart = {0x20};
  34. byte[] namePadding = null;
  35. if (name.length < 32) {
  36. int paddingLen = 32 - name.length;
  37. namePadding = new byte[paddingLen];
  38. for (int i = 0; i < namePadding.length; i+=2) {
  39. if (i == namePadding.length-2) {
  40. byte[] serviceBytes = NBNS.getServiceBytes(service);
  41. namePadding[i] = serviceBytes[0];
  42. namePadding[i+1] = serviceBytes[1];
  43. } else {
  44. namePadding[i] = 0x43;
  45. namePadding[i+1] = 0x041;
  46. }
  47. }
  48. }
  49. byte[] nameEnd = {0x00};
  50. return HelperUtils.concat(nameStart, name, namePadding, nameEnd);
  51. }
  52. }