Exemplo n.º 1
0
  /**
   * Read all blocks from the Mifare tag and return the data in a Tag object.
   *
   * @return A Tag object containing the data of the Mifare tag.
   * @throws IOException
   */
  public Tag read() throws IOException {

    int sectors = mTag.getSectorCount();
    Tag t = new Tag(TagType.getType(sectors));

    if (t.getSectorCount() > mKeys.getSectorCount()) throw new IOException("Too few keys");

    mTag.connect();

    try {

      for (int s = 0; s < sectors; ++s) {

        byte[] aKey = mKeys.getKeyA(s);
        byte[] bKey = mKeys.getKeyB(s);

        // Authenticate for each sector (try A key, then B key)
        if (!mTag.authenticateSectorWithKeyA(s, aKey) && !mTag.authenticateSectorWithKeyB(s, bKey))
          throw new IOException("Auth error");

        // Read every block of the sector
        int blockOffset = mTag.sectorToBlock(s);
        int lastBlock = blockOffset + mTag.getBlockCountInSector(s);
        for (int b = blockOffset; b < lastBlock; ++b) {
          byte[] readBuffer = mTag.readBlock(b);

          // Manually transfer key data to tag since it is usually not
          // readable
          if (b == lastBlock - 1) {
            for (int i = 0; i < Tag.KEY_SIZE; ++i) {
              readBuffer[i] = aKey[i];
              readBuffer[Tag.BLOCK_SIZE - Tag.KEY_SIZE + i] = bKey[i];
            }
          }

          t.setBlock(b, readBuffer);
          if (mProgressListener != null)
            mProgressListener.publishProgress((100 * b) / t.getBlockCount());
        }
      }

      return t;

    } finally {
      mTag.close();
    }
  }