1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.nfc.tech;
import android.nfc.ErrorCodes;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.os.RemoteException;
import android.util.Log;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* Provides access to MIFARE Classic properties and I/O operations on a {@link Tag}.
*
* <p>Acquire a {@link MifareClassic} object using {@link #get}.
*
* <p>MIFARE Classic is also known as MIFARE Standard.
* <p>MIFARE Classic tags are divided into sectors, and each sector is sub-divided into
* blocks. Block size is always 16 bytes ({@link #BLOCK_SIZE}. Sector size varies.
* <ul>
* <li>MIFARE Classic Mini are 320 bytes ({@link #SIZE_MINI}), with 5 sectors each of 4 blocks.
* <li>MIFARE Classic 1k are 1024 bytes ({@link #SIZE_1K}), with 16 sectors each of 4 blocks.
* <li>MIFARE Classic 2k are 2048 bytes ({@link #SIZE_2K}), with 32 sectors each of 4 blocks.
* <li>MIFARE Classic 4k are 4096 bytes ({@link #SIZE_4K}). The first 32 sectors contain 4 blocks
* and the last 8 sectors contain 16 blocks.
* </ul>
*
* <p>MIFARE Classic tags require authentication on a per-sector basis before any
* other I/O operations on that sector can be performed. There are two keys per sector,
* and ACL bits determine what I/O operations are allowed on that sector after
* authenticating with a key. {@see #authenticateSectorWithKeyA} and
* {@see #authenticateSectorWithKeyB}.
*
* <p>Three well-known authentication keys are defined in this class:
* {@link #KEY_DEFAULT}, {@link #KEY_MIFARE_APPLICATION_DIRECTORY},
* {@link #KEY_NFC_FORUM}.
* <ul>
* <li>{@link #KEY_DEFAULT} is the default factory key for MIFARE Classic.
* <li>{@link #KEY_MIFARE_APPLICATION_DIRECTORY} is the well-known key for
* MIFARE Classic cards that have been formatted according to the
* MIFARE Application Directory (MAD) specification.
* <li>{@link #KEY_NFC_FORUM} is the well-known key for MIFARE Classic cards that
* have been formatted according to the NXP specification for NDEF on MIFARE Classic.
*
* <p>Implementation of this class on a Android NFC device is optional.
* If it is not implemented, then
* {@link MifareClassic} will never be enumerated in {@link Tag#getTechList}.
* If it is enumerated, then all {@link MifareClassic} I/O operations will be supported,
* and {@link Ndef#MIFARE_CLASSIC} NDEF tags will also be supported. In either case,
* {@link NfcA} will also be enumerated on the tag, because all MIFARE Classic tags are also
* {@link NfcA}.
*
* <p class="note"><strong>Note:</strong> Methods that perform I/O operations
* require the {@link android.Manifest.permission#NFC} permission.
*/
public final class MifareClassic extends BasicTagTechnology {
private static final String TAG = "NFC";
/**
* The default factory key.
*/
public static final byte[] KEY_DEFAULT =
{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF};
/**
* The well-known key for tags formatted according to the
* MIFARE Application Directory (MAD) specification.
*/
public static final byte[] KEY_MIFARE_APPLICATION_DIRECTORY =
{(byte)0xA0,(byte)0xA1,(byte)0xA2,(byte)0xA3,(byte)0xA4,(byte)0xA5};
/**
* The well-known key for tags formatted according to the
* NDEF on MIFARE Classic specification.
*/
public static final byte[] KEY_NFC_FORUM =
{(byte)0xD3,(byte)0xF7,(byte)0xD3,(byte)0xF7,(byte)0xD3,(byte)0xF7};
/** A MIFARE Classic compatible card of unknown type */
public static final int TYPE_UNKNOWN = -1;
/** A MIFARE Classic tag */
public static final int TYPE_CLASSIC = 0;
/** A MIFARE Plus tag */
public static final int TYPE_PLUS = 1;
/** A MIFARE Pro tag */
public static final int TYPE_PRO = 2;
/** Tag contains 16 sectors, each with 4 blocks. */
public static final int SIZE_1K = 1024;
/** Tag contains 32 sectors, each with 4 blocks. */
public static final int SIZE_2K = 2048;
/**
* Tag contains 40 sectors. The first 32 sectors contain 4 blocks and the last 8 sectors
* contain 16 blocks.
*/
public static final int SIZE_4K = 4096;
/** Tag contains 5 sectors, each with 4 blocks. */
public static final int SIZE_MINI = 320;
/** Size of a MIFARE Classic block (in bytes) */
public static final int BLOCK_SIZE = 16;
private static final int MAX_BLOCK_COUNT = 256;
private static final int MAX_SECTOR_COUNT = 40;
private boolean mIsEmulated;
private int mType;
private int mSize;
/**
* Get an instance of {@link MifareClassic} for the given tag.
* <p>Does not cause any RF activity and does not block.
* <p>Returns null if {@link MifareClassic} was not enumerated in {@link Tag#getTechList}.
* This indicates the tag is not MIFARE Classic compatible, or this Android
* device does not support MIFARE Classic.
*
* @param tag an MIFARE Classic compatible tag
* @return MIFARE Classic object
*/
public static MifareClassic get(Tag tag) {
if (!tag.hasTech(TagTechnology.MIFARE_CLASSIC)) return null;
try {
return new MifareClassic(tag);
} catch (RemoteException e) {
return null;
}
}
/** @hide */
public MifareClassic(Tag tag) throws RemoteException {
super(tag, TagTechnology.MIFARE_CLASSIC);
NfcA a = NfcA.get(tag); // MIFARE Classic is always based on NFC a
mIsEmulated = false;
switch (a.getSak()) {
case 0x01:
case 0x08:
mType = TYPE_CLASSIC;
mSize = SIZE_1K;
break;
case 0x09:
mType = TYPE_CLASSIC;
mSize = SIZE_MINI;
break;
case 0x10:
mType = TYPE_PLUS;
mSize = SIZE_2K;
// SecLevel = SL2
break;
case 0x11:
mType = TYPE_PLUS;
mSize = SIZE_4K;
// Seclevel = SL2
break;
case 0x18:
mType = TYPE_CLASSIC;
mSize = SIZE_4K;
break;
case 0x28:
mType = TYPE_CLASSIC;
mSize = SIZE_1K;
mIsEmulated = true;
break;
case 0x38:
mType = TYPE_CLASSIC;
mSize = SIZE_4K;
mIsEmulated = true;
break;
case 0x88:
mType = TYPE_CLASSIC;
mSize = SIZE_1K;
// NXP-tag: false
break;
case 0x98:
case 0xB8:
mType = TYPE_PRO;
mSize = SIZE_4K;
break;
default:
// Stack incorrectly reported a MifareClassic. We cannot handle this
// gracefully - we have no idea of the memory layout. Bail.
throw new RuntimeException(
"Tag incorrectly enumerated as MIFARE Classic, SAK = " + a.getSak());
}
}
/**
* Return the type of this MIFARE Classic compatible tag.
* <p>One of {@link #TYPE_UNKNOWN}, {@link #TYPE_CLASSIC}, {@link #TYPE_PLUS} or
* {@link #TYPE_PRO}.
* <p>Does not cause any RF activity and does not block.
*
* @return type
*/
public int getType() {
return mType;
}
/**
* Return the size of the tag in bytes
* <p>One of {@link #SIZE_MINI}, {@link #SIZE_1K}, {@link #SIZE_2K}, {@link #SIZE_4K}.
* These constants are equal to their respective size in bytes.
* <p>Does not cause any RF activity and does not block.
* @return size in bytes
*/
public int getSize() {
return mSize;
}
/**
* Return true if the tag is emulated, determined at discovery time.
* These are actually smart-cards that emulate a MIFARE Classic interface.
* They can be treated identically to a MIFARE Classic tag.
* @hide
*/
public boolean isEmulated() {
return mIsEmulated;
}
/**
* Return the number of MIFARE Classic sectors.
* <p>Does not cause any RF activity and does not block.
* @return number of sectors
*/
public int getSectorCount() {
switch (mSize) {
case SIZE_1K:
return 16;
case SIZE_2K:
return 32;
case SIZE_4K:
return 40;
case SIZE_MINI:
return 5;
default:
return 0;
}
}
/**
* Return the total number of MIFARE Classic blocks.
* <p>Does not cause any RF activity and does not block.
* @return total number of blocks
*/
public int getBlockCount() {
return mSize / BLOCK_SIZE;
}
/**
* Return the number of blocks in the given sector.
* <p>Does not cause any RF activity and does not block.
*
* @param sectorIndex index of sector, starting from 0
* @return number of blocks in the sector
*/
public int getBlockCountInSector(int sectorIndex) {
validateSector(sectorIndex);
if (sectorIndex < 32) {
return 4;
} else {
return 16;
}
}
/**
* Return the sector that contains a given block.
* <p>Does not cause any RF activity and does not block.
*
* @param blockIndex index of block to lookup, starting from 0
* @return sector index that contains the block
*/
public int blockToSector(int blockIndex) {
validateBlock(blockIndex);
if (blockIndex < 32 * 4) {
return blockIndex / 4;
} else {
return 32 + (blockIndex - 32 * 4) / 16;
}
}
/**
* Return the first block of a given sector.
* <p>Does not cause any RF activity and does not block.
*
* @param sectorIndex index of sector to lookup, starting from 0
* @return block index of first block in sector
*/
public int sectorToBlock(int sectorIndex) {
if (sectorIndex < 32) {
return sectorIndex * 4;
} else {
return 32 * 4 + (sectorIndex - 32) * 16;
}
}
/**
* Authenticate a sector with key A.
*
* <p>Successful authentication of a sector with key A enables other
* I/O operations on that sector. The set of operations granted by key A
* key depends on the ACL bits set in that sector. For more information
* see the MIFARE Classic specification on <a href="http://www.nxp.com">http://www.nxp.com</a>.
*
* <p>A failed authentication attempt causes an implicit reconnection to the
* tag, so authentication to other sectors will be lost.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param sectorIndex index of sector to authenticate, starting from 0
* @param key 6-byte authentication key
* @return true on success, false on authentication failure
* @throws TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
*/
public boolean authenticateSectorWithKeyA(int sectorIndex, byte[] key) throws IOException {
return authenticate(sectorIndex, key, true);
}
/**
* Authenticate a sector with key B.
*
* <p>Successful authentication of a sector with key B enables other
* I/O operations on that sector. The set of operations granted by key B
* depends on the ACL bits set in that sector. For more information
* see the MIFARE Classic specification on <a href="http://www.nxp.com">http://www.nxp.com</a>.
*
* <p>A failed authentication attempt causes an implicit reconnection to the
* tag, so authentication to other sectors will be lost.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param sectorIndex index of sector to authenticate, starting from 0
* @param key 6-byte authentication key
* @return true on success, false on authentication failure
* @throws TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
*/
public boolean authenticateSectorWithKeyB(int sectorIndex, byte[] key) throws IOException {
return authenticate(sectorIndex, key, false);
}
private boolean authenticate(int sector, byte[] key, boolean keyA) throws IOException {
validateSector(sector);
checkConnected();
byte[] cmd = new byte[12];
// First byte is the command
if (keyA) {
cmd[0] = 0x60; // phHal_eMifareAuthentA
} else {
cmd[0] = 0x61; // phHal_eMifareAuthentB
}
// Second byte is block address
// Authenticate command takes a block address. Authenticating a block
// of a sector will authenticate the entire sector.
cmd[1] = (byte) sectorToBlock(sector);
// Next 4 bytes are last 4 bytes of UID
byte[] uid = getTag().getId();
System.arraycopy(uid, uid.length - 4, cmd, 2, 4);
// Next 6 bytes are key
System.arraycopy(key, 0, cmd, 6, 6);
try {
if (transceive(cmd, false) != null) {
return true;
}
} catch (TagLostException e) {
throw e;
} catch (IOException e) {
// No need to deal with, will return false anyway
}
return false;
}
/**
* Read 16-byte block.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param blockIndex index of block to read, starting from 0
* @return 16 byte block
* @throws TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
*/
public byte[] readBlock(int blockIndex) throws IOException {
validateBlock(blockIndex);
checkConnected();
byte[] cmd = { 0x30, (byte) blockIndex };
return transceive(cmd, false);
}
/**
* Write 16-byte block.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param blockIndex index of block to write, starting from 0
* @param data 16 bytes of data to write
* @throws TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
*/
public void writeBlock(int blockIndex, byte[] data) throws IOException {
validateBlock(blockIndex);
checkConnected();
if (data.length != 16) {
throw new IllegalArgumentException("must write 16-bytes");
}
byte[] cmd = new byte[data.length + 2];
cmd[0] = (byte) 0xA0; // MF write command
cmd[1] = (byte) blockIndex;
System.arraycopy(data, 0, cmd, 2, data.length);
transceive(cmd, false);
}
/**
* Increment a value block, storing the result in the temporary block on the tag.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param blockIndex index of block to increment, starting from 0
* @param value non-negative to increment by
* @throws TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
*/
public void increment(int blockIndex, int value) throws IOException {
validateBlock(blockIndex);
validateValueOperand(value);
checkConnected();
ByteBuffer cmd = ByteBuffer.allocate(6);
cmd.order(ByteOrder.LITTLE_ENDIAN);
cmd.put( (byte) 0xC1 );
cmd.put( (byte) blockIndex );
cmd.putInt(value);
transceive(cmd.array(), false);
}
/**
* Decrement a value block, storing the result in the temporary block on the tag.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param blockIndex index of block to decrement, starting from 0
* @param value non-negative to decrement by
* @throws TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
*/
public void decrement(int blockIndex, int value) throws IOException {
validateBlock(blockIndex);
validateValueOperand(value);
checkConnected();
ByteBuffer cmd = ByteBuffer.allocate(6);
cmd.order(ByteOrder.LITTLE_ENDIAN);
cmd.put( (byte) 0xC0 );
cmd.put( (byte) blockIndex );
cmd.putInt(value);
transceive(cmd.array(), false);
}
/**
* Copy from the temporary block to a value block.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param blockIndex index of block to copy to
* @throws TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
*/
public void transfer(int blockIndex) throws IOException {
validateBlock(blockIndex);
checkConnected();
byte[] cmd = { (byte) 0xB0, (byte) blockIndex };
transceive(cmd, false);
}
/**
* Copy from a value block to the temporary block.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param blockIndex index of block to copy from
* @throws TagLostException if the tag leaves the field
* @throws IOException if there is an I/O failure, or the operation is canceled
*/
public void restore(int blockIndex) throws IOException {
validateBlock(blockIndex);
checkConnected();
byte[] cmd = { (byte) 0xC2, (byte) blockIndex };
transceive(cmd, false);
}
/**
* Send raw NfcA data to a tag and receive the response.
*
* <p>This is equivalent to connecting to this tag via {@link NfcA}
* and calling {@link NfcA#transceive}. Note that all MIFARE Classic
* tags are based on {@link NfcA} technology.
*
* <p>Use {@link #getMaxTransceiveLength} to retrieve the maximum number of bytes
* that can be sent with {@link #transceive}.
*
* <p>This is an I/O operation and will block until complete. It must
* not be called from the main application thread. A blocked call will be canceled with
* {@link IOException} if {@link #close} is called from another thread.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @see NfcA#transceive
*/
public byte[] transceive(byte[] data) throws IOException {
return transceive(data, true);
}
/**
* Return the maximum number of bytes that can be sent with {@link #transceive}.
* @return the maximum number of bytes that can be sent with {@link #transceive}.
*/
public int getMaxTransceiveLength() {
return getMaxTransceiveLengthInternal();
}
/**
* Set the {@link #transceive} timeout in milliseconds.
*
* <p>The timeout only applies to {@link #transceive} on this object,
* and is reset to a default value when {@link #close} is called.
*
* <p>Setting a longer timeout may be useful when performing
* transactions that require a long processing time on the tag
* such as key generation.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @param timeout timeout value in milliseconds
*/
public void setTimeout(int timeout) {
try {
int err = mTag.getTagService().setTimeout(TagTechnology.MIFARE_CLASSIC, timeout);
if (err != ErrorCodes.SUCCESS) {
throw new IllegalArgumentException("The supplied timeout is not valid");
}
} catch (RemoteException e) {
Log.e(TAG, "NFC service dead", e);
}
}
/**
* Get the current {@link #transceive} timeout in milliseconds.
*
* <p class="note">Requires the {@link android.Manifest.permission#NFC} permission.
*
* @return timeout value in milliseconds
*/
public int getTimeout() {
try {
return mTag.getTagService().getTimeout(TagTechnology.MIFARE_CLASSIC);
} catch (RemoteException e) {
Log.e(TAG, "NFC service dead", e);
return 0;
}
}
private static void validateSector(int sector) {
// Do not be too strict on upper bounds checking, since some cards
// have more addressable memory than they report. For example,
// MIFARE Plus 2k cards will appear as MIFARE Classic 1k cards when in
// MIFARE Classic compatibility mode.
// Note that issuing a command to an out-of-bounds block is safe - the
// tag should report error causing IOException. This validation is a
// helper to guard against obvious programming mistakes.
if (sector < 0 || sector >= MAX_SECTOR_COUNT) {
throw new IndexOutOfBoundsException("sector out of bounds: " + sector);
}
}
private static void validateBlock(int block) {
// Just looking for obvious out of bounds...
if (block < 0 || block >= MAX_BLOCK_COUNT) {
throw new IndexOutOfBoundsException("block out of bounds: " + block);
}
}
private static void validateValueOperand(int value) {
if (value < 0) {
throw new IllegalArgumentException("value operand negative");
}
}
}
|