private void initAuthUserInfo(HttpURLConnection conn, String userInfo) {
    String user;
    String password;
    if (userInfo != null) { // get the user and password
      // System.out.println("UserInfo= " + userInfo );
      int delimiter = userInfo.indexOf(':');
      if (delimiter == -1) {
        user = ParseUtil.decode(userInfo);
        password = null;
      } else {
        user = ParseUtil.decode(userInfo.substring(0, delimiter++));
        password = ParseUtil.decode(userInfo.substring(delimiter));
      }

      String plain = user + ":";
      byte[] nameBytes = plain.getBytes();
      byte[] passwdBytes = password.getBytes();

      // concatenate user name and password bytes and encode them
      byte[] concat = new byte[nameBytes.length + passwdBytes.length];

      System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
      System.arraycopy(passwdBytes, 0, concat, nameBytes.length, passwdBytes.length);
      String auth = "Basic " + new String(Base64.encode(concat));
      conn.setRequestProperty("Authorization", auth);
      if (dL > 0) d("Adding auth " + auth);
    }
  }
  /**
   * Returns the result of applying XOR on this attribute's address, using the specified transaction
   * ID when converting IPv6 addresses.
   *
   * @param transactionID the transaction ID to use in case this attribute is encapsulating an IPv6
   *     address.
   * @return the XOR-ed address.
   */
  public TransportAddress getAddress(byte[] transactionID) {
    byte[] xorMask = new byte[16];

    System.arraycopy(Message.MAGIC_COOKIE, 0, xorMask, 0, 4);
    System.arraycopy(transactionID, 0, xorMask, 4, 12);

    return applyXor(xorMask);
  }
  /**
   * Applies a XOR mask to the specified address and then sets it as the value transported by this
   * attribute.
   *
   * @param address the address that we should xor and then record in this attribute.
   * @param transactionID the transaction identifier that we should use when creating the XOR mask.
   */
  public void setAddress(TransportAddress address, byte[] transactionID) {
    byte[] xorMask = new byte[16];

    System.arraycopy(Message.MAGIC_COOKIE, 0, xorMask, 0, 4);
    System.arraycopy(transactionID, 0, xorMask, 4, 12);

    TransportAddress xorAddress = applyXor(address, xorMask);

    super.setAddress(xorAddress);
  }
 private byte[] getChars(int chars) {
   try {
     lock.getBusyFlag();
     byte c[] = new byte[chars];
     System.arraycopy(result, 0, c, 0, chars);
     reslen -= chars;
     System.arraycopy(result, chars, result, 0, reslen);
     full.cvSignal();
     return c;
   } finally {
     lock.freeBusyFlag();
   }
 }
示例#5
0
  public static ClassLoader extendClassLoader(ClassLoader root, ClassLoader classLoader, URL url) {
    // URL classloader doesn't seem to delegate to parent classloader properly
    // so if you get a chain of them then it fails to find things. Here we
    // make sure that all of our added URLs end up within a single URLClassloader
    // with its parent being the one that loaded this class itself

    if (classLoader instanceof URLClassLoader) {

      URL[] old = ((URLClassLoader) classLoader).getURLs();

      URL[] new_urls = new URL[old.length + 1];

      System.arraycopy(old, 0, new_urls, 1, old.length);

      new_urls[0] = url;

      classLoader =
          new URLClassLoader(new_urls, classLoader == root ? classLoader : classLoader.getParent());
    } else {

      classLoader = new URLClassLoader(new URL[] {url}, classLoader);
    }

    return (classLoader);
  }
示例#6
0
 /**
  * @param data Guaranteed to be non null
  * @param offset
  * @param length
  */
 public void send(byte[] data, int offset, int length) throws Exception {
   if (sender != null) {
     byte[] copy = new byte[length];
     System.arraycopy(data, offset, copy, 0, length);
     sender.addToQueue(new Buffer(copy, 0, length));
   } else _send(data, offset, length, true, true);
 }
示例#7
0
  /**
   * Returns a clone of this SnmpContextv3.
   *
   * @exception CloneNotSupportedException Thrown when the constructor generates an IOException
   */
  public Object clone() throws CloneNotSupportedException {
    SnmpContextv3 clContext = null;
    try {
      clContext = new SnmpContextv3(hostAddr, hostPort, typeSocket);
      clContext.setUserName(new String(userName));
      clContext.setUseAuthentication(useAuthentication);
      if (userAuthenticationPassword != null) {
        clContext.setUserAuthenticationPassword(new String(userAuthenticationPassword));
      }
      clContext.setAuthenticationProtocol(authenticationProtocol);
      /*
      clContext.setUsePrivacy(usePrivacy);
      if (userPrivacyPassword != null)
      {
          clContext.setUserPrivacyPassword(new String(userPrivacyPassword));
      }
      */

      clContext.setContextName(new String(contextName));

      int l = contextEngineId.length;
      byte[] newContextEngineId = new byte[l];
      System.arraycopy(contextEngineId, 0, newContextEngineId, 0, l);
      clContext.setContextEngineId(newContextEngineId);
    } catch (java.io.IOException exc) {
      throw new CloneNotSupportedException("IOException " + exc.getMessage());
    }
    return clContext;
  }
  /**
   * Open FBS file identified by {@link #fbsURL}. The stream is positioned at the entry point
   * described by <code>entryPoint</code>.
   *
   * @param entryPoint entry point information.
   * @return a newly created FBS input stream on success, <code>null</code> if any error occured and
   *     the FBS stream is not opened.
   * @throws java.io.IOException if an I/O exception occurs.
   */
  private FbsInputStream openFbsFile(FbsEntryPoint entry) throws IOException {

    System.err.println("Entering FBS at " + entry.timestamp + " ms");

    // Make sure the protocol is HTTP.
    if (!fbkURL.getProtocol().equalsIgnoreCase("http")
        || !fbsURL.getProtocol().equalsIgnoreCase("http")) {
      System.err.println("Indexed access requires HTTP protocol in URLs");
      return null;
    }

    // Seek to the keyframe.
    InputStream is = openHttpByteRange(fbkURL, entry.key_fpos, entry.key_size);
    if (is == null) {
      return null;
    }

    // Load keyframe data from the .fbk file, prepend RFB initialization data.
    DataInputStream data = new DataInputStream(is);
    byte[] keyData = new byte[rfbInitData.length + (int) entry.key_size];
    System.arraycopy(rfbInitData, 0, keyData, 0, rfbInitData.length);
    data.readFully(keyData, rfbInitData.length, (int) entry.key_size);
    data.close();

    // Open the FBS stream.
    is = openHttpByteRange(fbsURL, entry.fbs_fpos, -1);
    if (is == null) {
      return null;
    }
    return new FbsInputStream(is, entry.timestamp, keyData, entry.fbs_skip);
  }
示例#9
0
  public static File[] getSystemLibs() {
    File javaHome = new File(System.getProperty("java.home"));
    File libDir = new File(javaHome, "lib");
    File extDir = new File(libDir, "ext");
    File osxDir = new File(javaHome.getParentFile(), "Classes");

    File[][] libsArray =
        new File[][] {
          getLibraryFiles(libDir), getLibraryFiles(osxDir), getLibraryFiles(extDir),
        };

    int nLibs = 0;
    for (int i = 0; i < libsArray.length; i++) {
      if (libsArray[i] != null) {
        nLibs += libsArray[i].length;
      }
    }

    File[] libs = new File[nLibs];
    int destPos = 0;
    for (int i = 0; i < libsArray.length; i++) {
      if (libsArray[i] != null) {
        System.arraycopy(libsArray[i], 0, libs, destPos, libsArray[i].length);
        destPos += libsArray[i].length;
      }
    }
    return libs;
  }
示例#10
0
  /**
   * Gets a <tt>MultiplexedDatagramSocket</tt> which filters <tt>DatagramPacket</tt>s away from this
   * <tt>DatagramSocket</tt> using a specific <tt>DatagramPacketFilter</tt>. If such a
   * <tt>MultiplexedDatagramSocket</tt> does not exist in this instance, it is created.
   *
   * @param filter the <tt>DatagramPacketFilter</tt> to get a <tt>MultiplexedDatagramSocket</tt> for
   * @return a <tt>MultiplexedDatagramSocket</tt> which filters <tt>DatagramPacket</tt>s away from
   *     this <tt>DatagramSocket</tt> using the specified <tt>filter</tt>
   * @throws SocketException if creating the <tt>MultiplexedDatagramSocket</tt> for the specified
   *     <tt>filter</tt> fails
   */
  public MultiplexedDatagramSocket getSocket(DatagramPacketFilter filter) throws SocketException {
    if (filter == null) throw new NullPointerException("filter");

    synchronized (socketsSyncRoot) {
      /*
       * If a socket for the specified filter exists already, do not
       * create a new one and return the existing.
       */
      for (MultiplexedDatagramSocket socket : sockets)
        if (filter.equals(socket.getFilter())) return socket;

      // Create a new socket for the specified filter.
      MultiplexedDatagramSocket socket = new MultiplexedDatagramSocket(this, filter);

      // Remember the new socket.
      int socketCount = sockets.length;

      if (socketCount == 0) sockets = new MultiplexedDatagramSocket[] {socket};
      else {
        MultiplexedDatagramSocket[] newSockets = new MultiplexedDatagramSocket[socketCount + 1];

        System.arraycopy(sockets, 0, newSockets, 0, socketCount);
        newSockets[socketCount] = socket;
        sockets = newSockets;
      }

      return socket;
    }
  }
示例#11
0
  /**
   * Copies the properties of a specific <tt>DatagramPacket</tt> to another <tt>DatagramPacket</tt>.
   * The property values are not cloned.
   *
   * @param src the <tt>DatagramPacket</tt> which is to have its properties copied to <tt>dest</tt>
   * @param dest the <tt>DatagramPacket</tt> which is to have its properties set to the value of the
   *     respective properties of <tt>src</tt>
   */
  public static void copy(DatagramPacket src, DatagramPacket dest) {
    synchronized (dest) {
      dest.setAddress(src.getAddress());
      dest.setPort(src.getPort());

      byte[] srcData = src.getData();

      if (srcData == null) dest.setLength(0);
      else {
        byte[] destData = dest.getData();

        if (destData == null) dest.setLength(0);
        else {
          int destOffset = dest.getOffset();
          int destLength = destData.length - destOffset;
          int srcLength = src.getLength();

          if (destLength >= srcLength) destLength = srcLength;
          else if (logger.isLoggable(Level.WARNING)) {
            logger.log(Level.WARNING, "Truncating received DatagramPacket data!");
          }
          System.arraycopy(srcData, src.getOffset(), destData, destOffset, destLength);
          dest.setLength(destLength);
        }
      }
    }
  }
  public void run() {
    runs = true;

    // notification about starting the input process
    stream.postEvent(new ServerEvent(this, stream, ServerEvent.INPUT_START));

    changeState(new HeaderDetectionState(this, stream));

    byte[] buffer = new byte[65535];
    int offset = 0;
    int length = 0;
    while (runs && stream.running()) {

      try {

        // starting time of the transfer
        long transferStart = new Date().getTime();

        // reading data
        int red = input.read(buffer, offset, buffer.length - offset);

        // notification about the transfer
        stream.postEvent(
            new TransferEvent(
                this,
                stream,
                TransferEvent.STREAM_INPUT,
                red,
                new Date().getTime() - transferStart));

        if (red == -1) runs = false;
        length += red;

        int newOffset = currentState.processData(buffer, 0, length);
        if (newOffset < offset + length) {
          length = length - newOffset;
          System.arraycopy(buffer, newOffset, buffer, 0, length);
          offset = length;
        } else {
          length = 0;
          offset = 0;
        }

      } catch (SocketTimeoutException e) {
        continue;
      } catch (Exception e) {
        e.printStackTrace();
        runs = false;
      }
    }

    try {
      input.close();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    // notification about ending the input process
    stream.postEvent(new ServerEvent(this, stream, ServerEvent.INPUT_STOP));
  }
示例#13
0
  public static void bootFromURIWithDT(
      ARMv5 cpu, RAM ramMain, String dtree, String kimage, String initrd, String cmdline) {
    byte[] cmdlb = cmdline.getBytes();
    // +1: need null char at the end of line
    byte[] cmdalign = new byte[(cmdlb.length + 1 + 3) & ~0x3];
    System.arraycopy(cmdlb, 0, cmdalign, 0, cmdlb.length);

    final int addrRAM = 0x00000000;
    final int addrDT = addrRAM + 0x800000;
    int sizeDT = 0;
    final int addrImage = addrRAM + 0x008000;
    int sizeImage = 0;
    final int addrInitrd = addrRAM + 0x00810000;
    int sizeInitrd = 0;
    boolean initrdExist = !initrd.equals("");

    // tentative boot loader for ARM Linux with Device Tree
    try {
      // load Device Tree Blob
      sizeDT = loadURIResource(new URI(dtree), cpu, addrDT);
      // load Image file
      sizeImage = loadURIResource(new URI(kimage), cpu, addrImage);
      // load Initrd/InitramFS file
      if (initrdExist) {
        sizeInitrd = loadURIResource(new URI(initrd), cpu, addrInitrd);
      }
    } catch (URISyntaxException e) {
      e.printStackTrace(System.err);
      return;
    }

    // report address mapping
    System.out.printf(
        "Address mapping:\n"
            + "  RAM       : 0x%08x\n"
            + "  DeviceTree: 0x%08x - 0x%08x\n"
            + "  Kernel    : 0x%08x - 0x%08x\n"
            + "  InitramFS : 0x%08x - 0x%08x\n",
        addrRAM,
        addrDT,
        addrDT + sizeDT - 1,
        addrImage,
        addrImage + sizeImage - 1,
        addrInitrd,
        addrInitrd + sizeInitrd - 1);

    // r0: 0
    cpu.setReg(0, 0);

    // r1: Do not care.
    cpu.setReg(1, 0);

    // r2: Device tree blob pointer.
    cpu.setReg(2, addrDT);

    // pc: entry of stext
    cpu.setPC(addrImage);
    cpu.setJumped(false);
  }
示例#14
0
  private byte[] merge(Hashtable msght) {
    int s = msght.size();
    // System.out.println("--------------------s="+s);
    byte[] tmpb = (byte[]) msght.get("" + s + "_" + (s - 1));

    int tmpi = tmpb.length;
    // System.out.println("-----------------1tmpi="+tmpi);
    int len = (s - 1) * MAX_PACKET_LENGTH + tmpi;
    byte[] tmpbuf = new byte[len];
    // System.out.println("-----------------1---");
    System.arraycopy(tmpb, 0, tmpbuf, (s - 1) * MAX_PACKET_LENGTH, tmpi);
    for (int i = 0; i < (s - 1); i++) {
      tmpb = (byte[]) msght.get("" + s + "_" + i);
      System.arraycopy(tmpb, 0, tmpbuf, i * MAX_PACKET_LENGTH, MAX_PACKET_LENGTH);
    }
    return tmpbuf;
  }
示例#15
0
  /**
   * Closes a specific <tt>MultiplexedDatagramSocket</tt> which filters <tt>DatagramPacket</tt>s
   * away from this <tt>DatagramSocket</tt>.
   *
   * @param multiplexed the <tt>MultiplexedDatagramSocket</tt> to close
   */
  void close(MultiplexedDatagramSocket multiplexed) {
    synchronized (socketsSyncRoot) {
      int socketCount = sockets.length;

      for (int i = 0; i < socketCount; i++)
        if (sockets[i].equals(multiplexed)) {
          if (socketCount == 1) sockets = NO_SOCKETS;
          else {
            MultiplexedDatagramSocket[] newSockets = new MultiplexedDatagramSocket[socketCount - 1];

            System.arraycopy(sockets, 0, newSockets, 0, i);
            System.arraycopy(sockets, i + 1, newSockets, i, newSockets.length - i);
            sockets = newSockets;
          }
          break;
        }
    }
  }
示例#16
0
  /**
   * Copies the content of the most recently received packet into <tt>data</tt>.
   *
   * @param buffer an optional <tt>Buffer</tt> instance associated with the specified <tt>data</tt>,
   *     <tt>offset</tt> and <tt>length</tt> and provided to the method in case the implementation
   *     would like to provide additional <tt>Buffer</tt> properties such as <tt>flags</tt>
   * @param data the <tt>byte[]</tt> that we'd like to copy the content of the packet to.
   * @param offset the position where we are supposed to start writing in <tt>data</tt>.
   * @param length the number of <tt>byte</tt>s available for writing in <tt>data</tt>.
   * @return the number of bytes read
   * @throws IOException if <tt>length</tt> is less than the size of the packet.
   */
  protected int read(Buffer buffer, byte[] data, int offset, int length) throws IOException {
    if (data == null) throw new NullPointerException("data");

    if (ioError) return -1;

    RawPacket pkt;

    synchronized (pktSyncRoot) {
      pkt = this.pkt;
      this.pkt = null;
    }

    int pktLength;

    if (pkt == null) {
      pktLength = 0;
    } else {
      // By default, pkt will be returned to the pool after it was read.
      boolean poolPkt = true;

      try {
        pktLength = pkt.getLength();
        if (length < pktLength) {
          /*
           * If pkt is still the latest RawPacket made available to
           * reading, reinstate it for the next invocation of read;
           * otherwise, return it to the pool.
           */
          poolPkt = false;
          throw new IOException("Input buffer not big enough for " + pktLength);
        } else {
          byte[] pktBuffer = pkt.getBuffer();

          if (pktBuffer == null) {
            throw new NullPointerException(
                "pkt.buffer null, pkt.length " + pktLength + ", pkt.offset " + pkt.getOffset());
          } else {
            System.arraycopy(pkt.getBuffer(), pkt.getOffset(), data, offset, pktLength);
            if (buffer != null) buffer.setFlags(pkt.getFlags());
          }
        }
      } finally {
        if (!poolPkt) {
          synchronized (pktSyncRoot) {
            if (this.pkt == null) this.pkt = pkt;
            else poolPkt = true;
          }
        }
        if (poolPkt) {
          // Return pkt to the pool because it was successfully read.
          poolRawPacket(pkt);
        }
      }
    }

    return pktLength;
  }
示例#17
0
  /**
   * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件
   *
   * @param task
   * @return "ok" if download success (else return errmessage);
   */
  static String download(DownloadTask task) {
    if (!openedStatus && show) openStatus();

    URL url;
    HttpURLConnection conn;
    try {
      url = new URL(task.getOrigin());
      conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/"
              + Math.random());
      if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求
        conn.setRequestProperty(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
        // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229;
        // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800");
        conn.setRequestProperty(
            "Cookie",
            "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800");
        conn.setRequestProperty("Host", "www.imgjav.com");
      }
      Path directory = Paths.get(task.getDest()).getParent();
      if (!Files.exists(directory)) Files.createDirectories(directory);
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    try (InputStream is = conn.getInputStream();
        BufferedInputStream in = new BufferedInputStream(is);
        FileOutputStream fos = new FileOutputStream(task.getDest());
        OutputStream out = new BufferedOutputStream(fos); ) {
      int length = conn.getContentLength();
      if (length < 1) throw new IOException("length<1");
      byte[] binary = new byte[length];
      byte[] buff = new byte[65536];
      int len;
      int index = 0;
      while ((len = in.read(buff)) != -1) {
        System.arraycopy(buff, 0, binary, index, len);
        index += len;
        allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了
        task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%");
      }
      out.write(binary);
    } catch (IOException e) {
      e.printStackTrace();
      return e.getMessage();
    }
    return "ok";
  }
  public void respond(DatagramPacket packet) {

    byte[] data = new byte[packet.getLength()];
    System.arraycopy(packet.getData(), 0, data, 0, packet.getLength());
    try {
      String s = new String(data, "8859_1");
      System.out.println(packet.getAddress() + " at port " + packet.getPort() + " says " + s);
    } catch (java.io.UnsupportedEncodingException ex) {
      // This shouldn't happen
    }
  }
示例#19
0
 /**
  * @param data Guaranteed to be non null
  * @param offset
  * @param length
  */
 private void send(byte[] data, int offset, int length) throws Exception {
   if (isSenderUsed()) {
     // we need to copy the byte[] buffer here because the original buffer might get
     // changed meanwhile
     byte[] tmp = new byte[length];
     System.arraycopy(data, offset, tmp, 0, length);
     sender.addToQueue(tmp);
   } else {
     _send(data, offset, length, true);
   }
 }
 private byte getChar() {
   try {
     lock.getBusyFlag();
     byte c = result[0];
     System.arraycopy(result, 1, result, 0, --reslen);
     full.cvSignal();
     return c;
   } finally {
     lock.freeBusyFlag();
   }
 }
示例#21
0
  protected static Object[] extractMockArguments(Object[] args) {
    int i = 7;

    if (args.length > i) {
      Object[] mockArgs = new Object[args.length - i];
      System.arraycopy(args, i, mockArgs, 0, mockArgs.length);
      return mockArgs;
    }

    return EMPTY_ARGS;
  }
  public String sendDetails(String password, byte[] phash, String transactionID, byte[] spdata)
      throws RemoteException, NotBoundException, NoSuchAlgorithmException, NoSuchPaddingException,
          InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] cipherData = cipher.doFinal(spdata);
    String x = new String(cipherData);
    String sp[] = new String[10];
    StringTokenizer st = new StringTokenizer(x.toString(), "|");
    int count = 0;
    StringBuilder message = new StringBuilder();
    while (st.hasMoreTokens()) {
      sp[count] = st.nextToken();
      count++;
    }

    String decodemessgae = new String();
    if (securePassword.equals(sp[1]) && serviceProviderId.equals(sp[0].toString().trim())) {
      System.out.println("hellosubba");
      if (transactionID.equals(transactionDetails[0].toString())) {
        int qrData[] = new int[16];

        for (int i = 0; i < password.length(); i++) {
          message.append(password.charAt(i) ^ bioTemplate.charAt(i));
        }
        for (int i = 0; i < message.length(); i++) {
          if (message.charAt(i) == '1') {
            decodemessgae += '0';
          } else decodemessgae += '1';
        }
        int start = 56, end = 63;
        for (int i = 0; i < 16; i++) {
          qrData[i] = Integer.parseInt(decodemessgae.substring(start, end), 2);
          start += 64;
          end += 64;
        }
        RsDecode dec = new RsDecode(16);
        int r = dec.decode(qrData);
        System.out.println("r=" + r);
        System.out.println("qrData=" + java.util.Arrays.toString(qrData));

        int[] MM = new int[qrData.length + 16];
        System.arraycopy(qrData, 0, MM, 0, qrData.length);
        RsEncode enc = new RsEncode(16);
        enc.encode(MM);
        System.out.println("qrData=" + java.util.Arrays.toString(MM));
      }
    } else {
      message.append("unkonw third party user");
    }
    return message.toString();
  }
 public static byte[] stringToArray(String s) {
   byte[] out = null;
   if (s == null) {
     out = new byte[4];
     integerToArray(-1, out, 0);
   } else {
     byte[] sb = s.getBytes();
     out = new byte[sb.length + 4];
     integerToArray(sb.length, out, 0);
     System.arraycopy(sb, 0, out, 4, sb.length);
   }
   return out;
 }
示例#24
0
  public Pdu processIncomingTrap(byte[] message) throws DecodingException, IOException {
    int l = message.length;
    byte[] copyOfMessage = new byte[l];
    System.arraycopy(message, 0, copyOfMessage, 0, l);

    AsnDecoder rpdu = new AsnDecoder();
    ByteArrayInputStream in = new ByteArrayInputStream(message);
    AsnSequence asnTopSeq = rpdu.DecodeSNMPv3(in);
    AsnPduSequence pduSeq = rpdu.processSNMPv3(this, asnTopSeq, copyOfMessage);

    TrapPduv2 trapPdu = new uk.co.westhawk.snmp.pdu.OneTrapPduv2(this);
    trapPdu.fillin(pduSeq);
    return trapPdu;
  }
示例#25
0
  public byte[] decryptCards(final String password, final byte[] ciphertext) throws Exception {
    final MessageDigest shaDigest = MessageDigest.getInstance("SHA-1");
    byte[] pw1 = password.getBytes("UTF-8");

    byte[] keyHash1 = shaDigest.digest(pw1);
    keyHash1 = shaDigest.digest(keyHash1);
    byte[] pw2 = new byte[keyHash1.length + pw1.length];
    System.arraycopy(keyHash1, 0, pw2, 0, keyHash1.length);
    System.arraycopy(pw1, 0, pw2, keyHash1.length, pw1.length);
    byte[] keyHash2 = shaDigest.digest(pw2);
    keyHash2 = shaDigest.digest(keyHash2);

    byte[] key = new byte[16];
    System.arraycopy(keyHash1, 0, key, 0, key.length);
    byte[] iv = new byte[16];
    System.arraycopy(keyHash1, 16, iv, 0, 4);
    System.arraycopy(keyHash2, 0, iv, 4, 12);

    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));

    return cipher.doFinal(ciphertext);
  }
 /** Object: size = variable */
 public static byte[] objectToArray(Object s) {
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     ObjectOutputStream oos = new ObjectOutputStream(baos);
     oos.writeObject(s);
     oos.close();
     baos.close();
     byte[] sb = baos.toByteArray();
     byte[] out = new byte[sb.length + 4];
     integerToArray(sb.length, out, 0);
     System.arraycopy(sb, 0, out, 4, sb.length);
     return out;
   } catch (IOException e) {
     e.printStackTrace();
     throw new RuntimeException("unable to serialize packet", e);
   }
 }
  /**
   * Concat arrays in one.
   *
   * @param arrays Arrays.
   * @return Summary array.
   */
  public static int[] concat(int[]... arrays) {
    assert arrays != null;
    assert arrays.length > 1;

    int len = 0;

    for (int[] a : arrays) len += a.length;

    int[] r = Arrays.copyOf(arrays[0], len);

    for (int i = 1, shift = 0; i < arrays.length; i++) {
      shift += arrays[i - 1].length;
      System.arraycopy(arrays[i], 0, r, shift, arrays[i].length);
    }

    return r;
  }
示例#28
0
  /**
   * Adds a <tt>DatagramPacketFilter</tt> which allows dropping <tt>DatagramPacket</tt>s before they
   * are converted into <tt>RawPacket</tt>s.
   *
   * @param datagramPacketFilter the <tt>DatagramPacketFilter</tt> which allows dropping
   *     <tt>DatagramPacket</tt>s before they are converted into <tt>RawPacket</tt>s
   */
  public synchronized void addDatagramPacketFilter(DatagramPacketFilter datagramPacketFilter) {
    if (datagramPacketFilter == null) throw new NullPointerException("datagramPacketFilter");

    if (datagramPacketFilters == null) {
      datagramPacketFilters = new DatagramPacketFilter[] {datagramPacketFilter};
    } else {
      final int length = datagramPacketFilters.length;

      for (int i = 0; i < length; i++)
        if (datagramPacketFilter.equals(datagramPacketFilters[i])) return;

      DatagramPacketFilter[] newDatagramPacketFilters = new DatagramPacketFilter[length + 1];

      System.arraycopy(datagramPacketFilters, 0, newDatagramPacketFilters, 0, length);
      newDatagramPacketFilters[length] = datagramPacketFilter;
      datagramPacketFilters = newDatagramPacketFilters;
    }
  }
示例#29
0
  /**
   * Compute the hash an IP address. The hash is the first 8 bytes of the SHA digest of the IP
   * address.
   */
  private static byte[] computeAddressHash() {

    /*
     * Get the local host's IP address.
     */
    byte[] addr =
        (byte[])
            java.security.AccessController.doPrivileged(
                new PrivilegedAction() {
                  public Object run() {
                    try {
                      return InetAddress.getLocalHost().getAddress();
                    } catch (Exception e) {
                    }
                    return new byte[] {0, 0, 0, 0};
                  }
                });

    byte[] addrHash;
    final int ADDR_HASH_LENGTH = 8;

    try {
      /*
       * Calculate message digest of IP address using SHA.
       */
      MessageDigest md = MessageDigest.getInstance("SHA");
      ByteArrayOutputStream sink = new ByteArrayOutputStream(64);
      DataOutputStream out = new DataOutputStream(new DigestOutputStream(sink, md));
      out.write(addr, 0, addr.length);
      out.flush();

      byte digest[] = md.digest();
      int hashlength = Math.min(ADDR_HASH_LENGTH, digest.length);
      addrHash = new byte[hashlength];
      System.arraycopy(digest, 0, addrHash, 0, hashlength);

    } catch (IOException ignore) {
      /* can't happen, but be deterministic anyway. */
      addrHash = new byte[0];
    } catch (NoSuchAlgorithmException complain) {
      throw new InternalError(complain.toString());
    }
    return addrHash;
  }
示例#30
0
 static byte[] sendReq(byte abyte0[], int i, String s, int j) throws Exception {
   DatagramSocket datagramsocket = new DatagramSocket(i);
   try {
     datagramsocket.setSoTimeout(30000);
     datagramsocket.send(new DatagramPacket(abyte0, abyte0.length, InetAddress.getByName(s), j));
     byte abyte1[] = new byte[512];
     DatagramPacket datagrampacket = new DatagramPacket(abyte1, abyte1.length);
     datagramsocket.receive(datagrampacket);
     byte abyte2[] = new byte[datagrampacket.getLength()];
     System.arraycopy(datagrampacket.getData(), 0, abyte2, 0, datagrampacket.getLength());
     datagramsocket.close();
     return abyte2;
   } catch (Exception exception) {
     try {
       datagramsocket.close();
     } catch (Exception exception1) {
     }
     throw exception;
   }
 }