├── .idea
├── .name
├── vcs.xml
├── misc.xml
├── dictionaries
│ └── pio.xml
├── runConfigurations.xml
├── gradle.xml
├── jarRepositories.xml
└── codeStyles
│ └── Project.xml
├── log
├── consumer-rules.pro
├── .gitignore
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── piotrekwitkowski
│ │ │ └── log
│ │ │ └── Log.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── piotrekwitkowski
│ │ │ └── log
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── piotrekwitkowski
│ │ └── log
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── nfc
├── consumer-rules.pro
├── .gitignore
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── piotrekwitkowski
│ │ │ │ └── nfc
│ │ │ │ ├── se
│ │ │ │ ├── NoSuchKeyException.java
│ │ │ │ ├── AuthenticationException.java
│ │ │ │ ├── states
│ │ │ │ │ ├── CommandDataLengthException.java
│ │ │ │ │ ├── State.java
│ │ │ │ │ ├── ApplicationNotFoundException.java
│ │ │ │ │ ├── CommandResult.java
│ │ │ │ │ ├── InitialState.java
│ │ │ │ │ ├── ApplicationAuthenticatedState.java
│ │ │ │ │ └── ApplicationSelectedState.java
│ │ │ │ ├── Command.java
│ │ │ │ ├── Emulation.java
│ │ │ │ ├── AuthenticationResponse.java
│ │ │ │ ├── Application.java
│ │ │ │ ├── SecureElement.java
│ │ │ │ └── Authentication.java
│ │ │ │ ├── desfire
│ │ │ │ ├── InvalidParameterException.java
│ │ │ │ ├── Commands.java
│ │ │ │ ├── AESKey.java
│ │ │ │ ├── ResponseCodes.java
│ │ │ │ ├── File.java
│ │ │ │ └── AID.java
│ │ │ │ ├── Iso7816.java
│ │ │ │ └── ByteUtils.java
│ │ ├── AndroidManifest.xml
│ │ └── res
│ │ │ └── values
│ │ │ └── strings.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── piotrekwitkowski
│ │ │ └── nfc
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── piotrekwitkowski
│ │ └── nfc
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── LibraryHCE
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── drawable-hdpi
│ │ │ │ └── ic_stat_name.png
│ │ │ ├── drawable-mdpi
│ │ │ │ └── ic_stat_name.png
│ │ │ ├── drawable-xhdpi
│ │ │ │ └── ic_stat_name.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── drawable-xxhdpi
│ │ │ │ └── ic_stat_name.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── xml
│ │ │ │ └── hceservice.xml
│ │ │ ├── drawable-anydpi-v24
│ │ │ │ └── ic_stat_name.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── piotrekwitkowski
│ │ │ │ └── libraryhce
│ │ │ │ ├── application
│ │ │ │ ├── LibraryFile0.java
│ │ │ │ ├── LibraryAID.java
│ │ │ │ ├── LibraryAESKey0.java
│ │ │ │ └── LibraryApplication.java
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── NotificationService.java
│ │ │ │ └── HCEService.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── piotrekwitkowski
│ │ │ └── libraryhce
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── piotrekwitkowski
│ │ └── libraryhce
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── LibraryReader
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── piotrekwitkowski
│ │ │ │ └── libraryreader
│ │ │ │ ├── StudentIdException.java
│ │ │ │ ├── DESFireReaderException.java
│ │ │ │ ├── Response.java
│ │ │ │ ├── HCE.java
│ │ │ │ ├── LibraryReader.java
│ │ │ │ ├── IsoDep.java
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── StudentId.java
│ │ │ │ └── DESFireReader.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── piotrekwitkowski
│ │ │ └── libraryreader
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── piotrekwitkowski
│ │ └── libraryreader
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── settings.gradle
├── .gitignore
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/.idea/.name:
--------------------------------------------------------------------------------
1 | Library NFC
--------------------------------------------------------------------------------
/log/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/nfc/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/log/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/nfc/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/LibraryHCE/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/LibraryReader/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/log/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Library Reader
3 |
4 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name='Library NFC'
2 | include ':LibraryReader'
3 | include ':nfc'
4 | include ':log'
5 | include ':LibraryHCE'
6 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/drawable-hdpi/ic_stat_name.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/drawable-hdpi/ic_stat_name.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/drawable-mdpi/ic_stat_name.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/drawable-mdpi/ic_stat_name.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/drawable-xhdpi/ic_stat_name.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/drawable-xhdpi/ic_stat_name.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/drawable-xxhdpi/ic_stat_name.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/drawable-xxhdpi/ic_stat_name.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/NoSuchKeyException.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se;
2 |
3 | public class NoSuchKeyException extends Exception {
4 | }
5 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryHCE/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/AuthenticationException.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se;
2 |
3 | public class AuthenticationException extends Exception {
4 | }
5 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/piotrekwitkowski/LibraryNFC/HEAD/LibraryReader/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/states/CommandDataLengthException.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se.states;
2 |
3 | class CommandDataLengthException extends Exception {
4 | }
5 |
--------------------------------------------------------------------------------
/nfc/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #6200EE
4 | #3700B3
5 | #03DAC5
6 |
7 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/StudentIdException.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | class StudentIdException extends Exception {
4 | StudentIdException(String message) {
5 | super(message);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #6200EE
4 | #3700B3
5 | #03DAC5
6 |
7 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/states/State.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se.states;
2 |
3 | import com.piotrekwitkowski.nfc.se.Command;
4 |
5 | public abstract class State {
6 | public abstract CommandResult processCommand(Command c);
7 | }
8 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Library HCE
3 | Library HCE Service
4 | Library HCE AID group
5 |
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/DESFireReaderException.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | class DESFireReaderException extends Exception {
4 | DESFireReaderException(String message) {
5 | super(message);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Jul 03 00:10:37 CEST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/nfc/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | A0000002471001
6 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/java/com/piotrekwitkowski/libraryhce/application/LibraryFile0.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryhce.application;
2 |
3 | import com.piotrekwitkowski.nfc.desfire.File;
4 |
5 | class LibraryFile0 extends File {
6 | LibraryFile0() {
7 | super("0035383536383600000048554853303538353638363000000000000000000000");
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/desfire/InvalidParameterException.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.desfire;
2 |
3 | // https://youtrack.jetbrains.com/issue/IDEA-209050
4 | @SuppressWarnings("WeakerAccess")
5 | public class InvalidParameterException extends Exception {
6 | public InvalidParameterException(String message) {
7 | super(message);
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/desfire/Commands.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.desfire;
2 |
3 | public class Commands {
4 | public static final byte SELECT_APPLICATION = (byte) 0x5A;
5 | public static final byte AUTHENTICATE_AES = (byte) 0xAA;
6 | public static final byte ADDITIONAL_FRAME = (byte) 0xAF;
7 | public static final byte READ_DATA = (byte) 0xBD;
8 | }
9 |
--------------------------------------------------------------------------------
/.idea/dictionaries/pio.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | apdu
5 | cardemulation
6 | hceservice
7 | lbraryreader
8 | libraryhce
9 | libraryreader
10 | piotrekwitkowski
11 | transceive
12 |
13 |
14 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/java/com/piotrekwitkowski/libraryhce/application/LibraryAID.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryhce.application;
2 |
3 | import com.piotrekwitkowski.nfc.desfire.AID;
4 | import com.piotrekwitkowski.nfc.desfire.InvalidParameterException;
5 |
6 | class LibraryAID extends AID {
7 | LibraryAID() throws InvalidParameterException {
8 | super("015548");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/states/ApplicationNotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se.states;
2 |
3 | // https://youtrack.jetbrains.com/issue/IDEA-209050
4 | @SuppressWarnings("WeakerAccess")
5 | public class ApplicationNotFoundException extends Exception {
6 | public ApplicationNotFoundException() {
7 | super("Application not found");
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/java/com/piotrekwitkowski/libraryhce/application/LibraryAESKey0.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryhce.application;
2 |
3 | import com.piotrekwitkowski.nfc.desfire.InvalidParameterException;
4 | import com.piotrekwitkowski.nfc.desfire.AESKey;
5 |
6 | class LibraryAESKey0 extends AESKey {
7 | LibraryAESKey0() throws InvalidParameterException {
8 | super("00000000000000000000000000000000");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/Command.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se;
2 |
3 | import java.util.Arrays;
4 |
5 | public class Command {
6 | private final byte[] bytes;
7 |
8 | Command(byte[] bytes) {
9 | this.bytes = bytes;
10 | }
11 |
12 | public byte getCode() {
13 | return bytes[0];
14 | }
15 |
16 | public byte[] getData() {
17 | return Arrays.copyOfRange(bytes, 1, bytes.length);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/java/com/piotrekwitkowski/libraryhce/application/LibraryApplication.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryhce.application;
2 |
3 | import com.piotrekwitkowski.nfc.desfire.InvalidParameterException;
4 | import com.piotrekwitkowski.nfc.se.Application;
5 |
6 | public class LibraryApplication extends Application {
7 | public LibraryApplication() throws InvalidParameterException {
8 | super(new LibraryAID(), new LibraryAESKey0(), new LibraryFile0());
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/log/src/test/java/com/piotrekwitkowski/log/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.log;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/nfc/src/test/java/com/piotrekwitkowski/nfc/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/LibraryHCE/src/test/java/com/piotrekwitkowski/libraryhce/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryhce;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/LibraryReader/src/test/java/com/piotrekwitkowski/libraryreader/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/Response.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | import java.util.Arrays;
4 |
5 | class Response {
6 | private final byte[] bytes;
7 |
8 | Response(byte[] responseBytes) {
9 | this.bytes = responseBytes;
10 | }
11 |
12 | byte[] getBytes() {
13 | return bytes;
14 | }
15 |
16 | byte getResponseCode() {
17 | return bytes[0];
18 | }
19 |
20 | byte[] getData() {
21 | return Arrays.copyOfRange(bytes, 1, bytes.length);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/Emulation.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se;
2 |
3 | import com.piotrekwitkowski.log.Log;
4 |
5 | public class Emulation {
6 | private static final String TAG = "Emulation";
7 | private final SecureElement secureElement;
8 |
9 | public Emulation(SecureElement secureElement) {
10 | this.secureElement = secureElement;
11 | }
12 |
13 | public byte[] getResponse(byte[] apdu) {
14 | Log.i(TAG, "getResponse()");
15 | return secureElement.processCommand(new Command(apdu));
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/desfire/AESKey.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.desfire;
2 |
3 | import com.piotrekwitkowski.nfc.ByteUtils;
4 |
5 | public class AESKey {
6 | private final byte[] key;
7 |
8 | public AESKey(String key) throws InvalidParameterException {
9 | if (key.length() == 32) {
10 | this.key = ByteUtils.toByteArray(key);
11 | } else {
12 | throw new InvalidParameterException("AES key length should be 32 chars");
13 | }
14 | }
15 |
16 | public byte[] getKey() {
17 | return key;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/AuthenticationResponse.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se;
2 |
3 | public class AuthenticationResponse {
4 | private final byte[] sessionKey;
5 | private final byte[] encryptedRotatedA;
6 |
7 | AuthenticationResponse(byte[] sessionKey, byte[] encryptedRotatedA) {
8 | this.sessionKey = sessionKey;
9 | this.encryptedRotatedA = encryptedRotatedA;
10 | }
11 |
12 | public byte[] getSessionKey() {
13 | return this.sessionKey;
14 | }
15 |
16 | public byte[] getEncryptedRotatedA() {
17 | return encryptedRotatedA;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/xml/hceservice.xml:
--------------------------------------------------------------------------------
1 |
4 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/states/CommandResult.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se.states;
2 |
3 | public class CommandResult {
4 | private final State state;
5 | private final byte[] response;
6 |
7 | CommandResult(State state, byte responseCode) {
8 | this.state = state;
9 | this.response = new byte[]{responseCode};
10 | }
11 |
12 | public CommandResult(State state, byte[] responseBytes) {
13 | this.state = state;
14 | this.response = responseBytes;
15 | }
16 |
17 | public State getState() {
18 | return state;
19 | }
20 |
21 | public byte[] getResponse() {
22 | return response;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/desfire/ResponseCodes.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.desfire;
2 |
3 | public class ResponseCodes {
4 | public static final byte SUCCESS = (byte) 0x00;
5 | public static final byte ILLEGAL_COMMAND = (byte) 0x1C;
6 | public static final byte NO_SUCH_KEY = (byte) 0x40;
7 | public static final byte LENGTH_ERROR = (byte) 0x7E;
8 | public static final byte APPLICATION_NOT_FOUND = (byte) 0xA0;
9 | public static final byte AUTHENTICATION_ERROR = (byte) 0xAE;
10 | public static final byte ADDITIONAL_FRAME = (byte) 0xAF;
11 | public static final byte BOUNDARY_ERROR = (byte) 0xBE;
12 | public static final byte FILE_NOT_FOUND = (byte) 0xF0;
13 | }
14 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/java/com/piotrekwitkowski/libraryhce/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryhce;
2 |
3 | import androidx.appcompat.app.AppCompatActivity;
4 |
5 | import android.os.Bundle;
6 | import android.widget.TextView;
7 |
8 | import com.piotrekwitkowski.log.Log;
9 |
10 | public class MainActivity extends AppCompatActivity {
11 | private static final String TAG = "MainActivity";
12 |
13 | @Override
14 | protected void onCreate(Bundle savedInstanceState) {
15 | super.onCreate(savedInstanceState);
16 | setContentView(R.layout.activity_main);
17 | TextView logTextView = findViewById(R.id.logTextView);
18 | Log.setLogTextView(logTextView);
19 | Log.reset(TAG, "onCreate()");
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/desfire/File.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.desfire;
2 |
3 | import com.piotrekwitkowski.nfc.ByteUtils;
4 |
5 | import java.util.Arrays;
6 |
7 | public class File {
8 | private final byte[] data;
9 |
10 | @SuppressWarnings("SameParameterValue")
11 | protected File(String data) {
12 | this.data = ByteUtils.toByteArray(data);
13 | }
14 |
15 | public byte[] readData(int offset, int length) throws ArrayIndexOutOfBoundsException, IllegalArgumentException, NullPointerException {
16 | if (length == 0) {
17 | return Arrays.copyOfRange(data, offset, data.length);
18 | } else {
19 | return Arrays.copyOfRange(data, offset, offset + length);
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/Application.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se;
2 |
3 | import com.piotrekwitkowski.nfc.desfire.AESKey;
4 | import com.piotrekwitkowski.nfc.desfire.AID;
5 | import com.piotrekwitkowski.nfc.desfire.File;
6 |
7 | public abstract class Application {
8 | private final AID aid;
9 | private final AESKey key0;
10 | private final File file0;
11 |
12 | protected Application(AID aid, AESKey aesKey0, File file0) {
13 | this.aid = aid;
14 | this.key0 = aesKey0;
15 | this.file0 = file0;
16 | }
17 |
18 | public AID getAid() {
19 | return aid;
20 | }
21 |
22 | public File getFile0() { return file0; }
23 |
24 | AESKey getKey0() {
25 | return this.key0;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/HCE.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | import android.content.Context;
4 |
5 | import com.piotrekwitkowski.log.Log;
6 | import com.piotrekwitkowski.nfc.ByteUtils;
7 |
8 | import java.io.IOException;
9 |
10 | import static com.piotrekwitkowski.nfc.Iso7816.wrapApdu;
11 |
12 | class HCE {
13 | private static final String TAG = "HCE";
14 |
15 | static Response selectAndroidApp(Context context, IsoDep isoDep) throws IOException {
16 | Log.i(TAG, "selectAndroidApp()");
17 |
18 | String HCE_AID = context.getString(com.piotrekwitkowski.nfc.R.string.hce_aid);
19 | byte[] commandApdu = wrapApdu(ByteUtils.toByteArray(HCE_AID));
20 | return isoDep.transceive(commandApdu);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/log/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/nfc/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/LibraryHCE/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/LibraryReader/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/SecureElement.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se;
2 |
3 | import com.piotrekwitkowski.log.Log;
4 | import com.piotrekwitkowski.nfc.se.states.CommandResult;
5 | import com.piotrekwitkowski.nfc.se.states.InitialState;
6 | import com.piotrekwitkowski.nfc.se.states.State;
7 |
8 | public class SecureElement {
9 | private static final String TAG = "SoftwareSEWrapper";
10 | private State state;
11 |
12 | public SecureElement(Application[] applications) {
13 | this.state = new InitialState(applications);
14 | }
15 |
16 | byte[] processCommand(Command command) {
17 | Log.i(TAG, "processCommand()");
18 |
19 | CommandResult result = this.state.processCommand(command);
20 | this.state = result.getState();
21 | return result.getResponse();
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/log/src/androidTest/java/com/piotrekwitkowski/log/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.log;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("com.piotrekwitkowski.log.test", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/nfc/src/androidTest/java/com/piotrekwitkowski/nfc/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("com.piotrekwitkowski.nfc.test", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/LibraryHCE/src/androidTest/java/com/piotrekwitkowski/libraryhce/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryhce;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("com.piotrekwitkowski.libraryhce", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/LibraryReader/src/androidTest/java/com/piotrekwitkowski/libraryreader/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("com.piotrekwitkowski.lbraryreader", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/desfire/AID.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.desfire;
2 |
3 | import com.piotrekwitkowski.nfc.ByteUtils;
4 |
5 | import java.util.Arrays;
6 |
7 | public class AID {
8 | private final byte[] bytes;
9 |
10 | public AID(String aid) throws InvalidParameterException {
11 | if (aid.length() == 6) {
12 | this.bytes = ByteUtils.toByteArray(aid);
13 | } else {
14 | throw new InvalidParameterException("AID length should be 6 chars");
15 | }
16 | }
17 |
18 | public AID(byte[] aid) throws InvalidParameterException {
19 | if (aid.length == 3) {
20 | this.bytes = aid;
21 | } else {
22 | throw new InvalidParameterException("AID length should be 3 bytes");
23 | }
24 | }
25 |
26 | public boolean equals(AID aid) {
27 | return Arrays.equals(this.bytes, aid.bytes);
28 | }
29 |
30 | public byte[] getBytes() {
31 | return bytes;
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/nfc/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 30
5 | buildToolsVersion '30.0.0'
6 |
7 | defaultConfig {
8 | minSdkVersion 19
9 | targetSdkVersion 29
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | consumerProguardFiles 'consumer-rules.pro'
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 |
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 |
29 | implementation 'androidx.appcompat:appcompat:1.1.0'
30 | testImplementation 'junit:junit:4.13'
31 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
32 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
33 | implementation project(path: ':log')
34 | }
35 |
--------------------------------------------------------------------------------
/log/src/main/java/com/piotrekwitkowski/log/Log.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.log;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.os.Handler;
5 | import android.os.Looper;
6 | import android.widget.TextView;
7 |
8 | @SuppressLint("SetTextI18n")
9 | public class Log {
10 | @SuppressLint("StaticFieldLeak")
11 | private static TextView logTextView;
12 |
13 | public static void setLogTextView(TextView tv) {
14 | logTextView = tv;
15 | }
16 |
17 | public static void i(final String tag, final String msg) {
18 | android.util.Log.i(tag, msg);
19 | new Handler(Looper.getMainLooper()).post(() -> logTextView.setText(logTextView.getText() + format(tag, msg)));
20 | }
21 |
22 | public static void reset(final String tag, final String msg) {
23 | android.util.Log.i(tag, msg);
24 | new Handler(Looper.getMainLooper()).post(() -> logTextView.setText(format(tag, msg)));
25 | }
26 |
27 | private static String format(String tag, String msg) {
28 | return tag + ": " + msg + '\n';
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
9 |
10 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/log/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 30
5 | buildToolsVersion '30.0.0'
6 |
7 | defaultConfig {
8 | minSdkVersion 19
9 | targetSdkVersion 29
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | consumerProguardFiles 'consumer-rules.pro'
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | compileOptions {
24 | sourceCompatibility = 1.8
25 | targetCompatibility = 1.8
26 | }
27 |
28 | }
29 |
30 | dependencies {
31 | implementation fileTree(dir: 'libs', include: ['*.jar'])
32 |
33 | implementation 'androidx.appcompat:appcompat:1.1.0'
34 | testImplementation 'junit:junit:4.13'
35 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
36 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
37 | }
38 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 |
21 |
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/drawable-anydpi-v24/ic_stat_name.xml:
--------------------------------------------------------------------------------
1 |
7 |
9 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
11 |
12 |
16 |
17 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
11 |
12 |
16 |
17 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/Iso7816.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc;
2 |
3 | public class Iso7816 {
4 | public static final byte[] RESPONSE_SUCCESS = new byte[] {(byte) 0x90, (byte) 0x00};
5 | public static final byte[] RESPONSE_INTERNAL_ERROR = new byte[] {(byte) 0x6F, (byte) 0x00};
6 | private static final byte SELECT = (byte) 0xA4;
7 | // private final static byte READ_BINARY = (byte) 0xB0;
8 | // private final static byte UPDATE_BINARY = (byte) 0xD6;
9 | // private final static byte READ_RECORDS = (byte) 0xB2;
10 | // private final static byte APPEND_RECORD = (byte) 0xE2;
11 | // private final static byte GET_CHALLENGE = (byte) 0x84;
12 | // private final static byte INTERNAL_AUTHENTICATE = (byte) 0x88;
13 | // private final static byte EXTERNAL_AUTHENTICATE = (byte) 0x82;
14 |
15 | public static byte[] wrapApdu(byte[] command) {
16 | byte[] apduRequiredPart = new byte[] {(byte) 0x00, SELECT, (byte) 0x04, (byte) 0x00};
17 | if (command.length == 0) {
18 | return apduRequiredPart;
19 | } else {
20 | byte[] apduCommandPart = ByteUtils.concatenate((byte) command.length, command);
21 | return ByteUtils.concatenate(apduRequiredPart, apduCommandPart);
22 | }
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/LibraryHCE/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 30
5 | buildToolsVersion '30.0.0'
6 |
7 | defaultConfig {
8 | applicationId "com.piotrekwitkowski.libraryhce"
9 | minSdkVersion 19
10 | targetSdkVersion 29
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | compileOptions {
24 | sourceCompatibility = 1.8
25 | targetCompatibility = 1.8
26 | }
27 |
28 | }
29 |
30 | dependencies {
31 | implementation fileTree(dir: 'libs', include: ['*.jar'])
32 |
33 | implementation 'androidx.appcompat:appcompat:1.1.0'
34 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
35 | testImplementation 'junit:junit:4.13'
36 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
37 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
38 | implementation project(path: ':log')
39 | implementation project(path: ':nfc')
40 | }
41 |
--------------------------------------------------------------------------------
/LibraryReader/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 30
5 | buildToolsVersion '30.0.0'
6 |
7 | defaultConfig {
8 | applicationId "com.piotrekwitkowski.libraryreader"
9 | minSdkVersion 19
10 | targetSdkVersion 29
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | compileOptions {
24 | sourceCompatibility = 1.8
25 | targetCompatibility = 1.8
26 | }
27 |
28 |
29 | }
30 |
31 | dependencies {
32 | implementation fileTree(dir: 'libs', include: ['*.jar'])
33 |
34 | implementation 'androidx.appcompat:appcompat:1.1.0'
35 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
36 | testImplementation 'junit:junit:4.13'
37 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
38 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
39 | implementation project(path: ':nfc')
40 | implementation project(path: ':log')
41 | }
42 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/LibraryReader.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | import android.content.Context;
4 | import android.nfc.Tag;
5 |
6 | import com.piotrekwitkowski.log.Log;
7 | import com.piotrekwitkowski.nfc.desfire.AID;
8 | import com.piotrekwitkowski.nfc.desfire.InvalidParameterException;
9 | import com.piotrekwitkowski.nfc.desfire.AESKey;
10 |
11 | class LibraryReader {
12 | private static final String TAG = "LibraryReader";
13 | private final Context context;
14 |
15 | LibraryReader(Context ctx) {
16 | this.context = ctx;
17 | }
18 |
19 | void processTag(Tag tag) throws InvalidParameterException {
20 | Log.i(TAG, "processTag()");
21 |
22 | final AID LIBRARY_AID = new AID("015548");
23 | final AESKey LIBRARY_KEY = new AESKey("00000000000000000000000000000000");
24 | final int LIBRARY_KEY_NUMBER = 0;
25 | final int FILE_NUMBER = 0;
26 | final int FILE_OFFSET = 10;
27 | final int FILE_LENGTH = 12;
28 | final IsoDep isoDep = IsoDep.get(tag);
29 |
30 | try {
31 | StudentId studentId = StudentId.getStudentId(this.context, isoDep);
32 | studentId.selectApplication(LIBRARY_AID);
33 | studentId.authenticateAES(LIBRARY_KEY, LIBRARY_KEY_NUMBER);
34 | byte[] libraryId = studentId.readData(FILE_NUMBER, FILE_OFFSET, FILE_LENGTH);
35 | Log.i(TAG, "libraryId: " + new String(libraryId));
36 |
37 | studentId.close();
38 | } catch (Exception e) {
39 | e.printStackTrace();
40 | }
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
17 |
18 |
22 |
23 |
24 |
25 |
26 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/IsoDep.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | import android.nfc.Tag;
4 |
5 | import com.piotrekwitkowski.log.Log;
6 | import com.piotrekwitkowski.nfc.ByteUtils;
7 |
8 | import java.io.IOException;
9 |
10 | class IsoDep {
11 | private static final String TAG = "IsoDep";
12 | private final android.nfc.tech.IsoDep mIsoDep;
13 |
14 | private IsoDep(android.nfc.tech.IsoDep isoDep) {
15 | mIsoDep = isoDep;
16 | }
17 |
18 | static IsoDep get(Tag tag) {
19 | return new IsoDep(android.nfc.tech.IsoDep.get(tag));
20 | }
21 |
22 | void connect() throws IOException {
23 | Log.i(TAG, "connect()");
24 | mIsoDep.connect();
25 | }
26 |
27 | @SuppressWarnings("SameParameterValue")
28 | Response transceive(byte command, byte data) throws IOException {
29 | return transceive(ByteUtils.concatenate(command, data));
30 | }
31 |
32 | Response transceive(byte command, byte[] data) throws IOException {
33 | return transceive(ByteUtils.concatenate(command, data));
34 | }
35 |
36 | Response transceive(byte[] data) throws IOException {
37 | Log.i(TAG, "--> " + ByteUtils.toHexString(data));
38 | byte[] response = mIsoDep.transceive(data);
39 | Log.i(TAG, "<-- " + ByteUtils.toHexString(response));
40 | return new Response(response);
41 | }
42 |
43 | void close() throws IOException {
44 | Log.i(TAG, "close()");
45 | mIsoDep.close();
46 | }
47 |
48 | byte[] getHistoricalBytes() {
49 | Log.i(TAG, "getHistoricalBytes()");
50 | return mIsoDep.getHistoricalBytes();
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | import android.nfc.NfcAdapter;
4 | import android.nfc.Tag;
5 | import android.os.Bundle;
6 | import android.widget.TextView;
7 |
8 | import androidx.appcompat.app.AppCompatActivity;
9 |
10 | import com.piotrekwitkowski.log.Log;
11 | import com.piotrekwitkowski.nfc.desfire.InvalidParameterException;
12 |
13 | public class MainActivity extends AppCompatActivity implements NfcAdapter.ReaderCallback {
14 | private static final String TAG = "MainActivity";
15 | private final LibraryReader libraryReader = new LibraryReader(this);
16 | private NfcAdapter nfcAdapter;
17 |
18 | @Override
19 | protected void onCreate(Bundle savedInstanceState) {
20 | super.onCreate(savedInstanceState);
21 | setContentView(R.layout.activity_main);
22 | nfcAdapter = NfcAdapter.getDefaultAdapter(this);
23 | TextView logTextView = findViewById(R.id.logTextView);
24 | Log.setLogTextView(logTextView);
25 | Log.reset(TAG, "onCreate()");
26 | }
27 |
28 | @Override
29 | protected void onResume() {
30 | super.onResume();
31 | Log.i(TAG, "onResume()");
32 | nfcAdapter.enableReaderMode(this, this, NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK, null);
33 | Log.i(TAG, "NFC adapter enabled. Waiting for a card...");
34 | }
35 |
36 | @Override
37 | protected void onPause() {
38 | super.onPause();
39 | Log.i(TAG, "onPause()");
40 | nfcAdapter.disableReaderMode(this);
41 | Log.i(TAG, "NFC adapter disabled.");
42 | }
43 |
44 | @Override
45 | public void onTagDiscovered(Tag tag) {
46 | Log.reset(TAG, "onTagDiscovered()");
47 | try {
48 | libraryReader.processTag(tag);
49 | } catch (InvalidParameterException e) {
50 | Log.i(TAG, e.getMessage());
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/java/com/piotrekwitkowski/libraryhce/NotificationService.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryhce;
2 |
3 | import android.app.NotificationChannel;
4 | import android.app.NotificationManager;
5 | import android.content.Context;
6 | import android.os.Build;
7 |
8 | import androidx.core.app.NotificationCompat;
9 | import androidx.core.app.NotificationManagerCompat;
10 |
11 | class NotificationService {
12 | private static final String NOTIFICATION_CHANNEL_NAME = "HCE Service";
13 | private static final String NOTIFICATION_CHANNEL_DESCRIPTION = "HCE Service channel";
14 | private final Context context;
15 |
16 | NotificationService(Context ctx) {
17 | this.context = ctx;
18 | }
19 |
20 | void show(String text) {
21 | int randomNotificationId = (int) (Math.random()*1000);
22 | NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_NAME)
23 | .setSmallIcon(R.drawable.ic_stat_name)
24 | .setContentTitle(context.getString(R.string.app_name))
25 | .setContentText(text)
26 | .setPriority(NotificationCompat.PRIORITY_DEFAULT);
27 | NotificationManagerCompat.from(context).notify(randomNotificationId, builder.build());
28 | }
29 |
30 | void createNotificationChannel(Context ctx) {
31 | // Create the NotificationChannel, but only on API 26+ because
32 | // the NotificationChannel class is new and not in the support library
33 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
34 | String name = ctx.getString(R.string.app_name);
35 | NotificationChannel nc = new NotificationChannel(NOTIFICATION_CHANNEL_NAME, name, NotificationManager.IMPORTANCE_DEFAULT);
36 | nc.setDescription(NOTIFICATION_CHANNEL_DESCRIPTION);
37 |
38 | NotificationManager nm = ctx.getSystemService(NotificationManager.class);
39 | if (nm != null) {
40 | nm.createNotificationChannel(nc);
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/states/InitialState.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se.states;
2 |
3 | import com.piotrekwitkowski.log.Log;
4 | import com.piotrekwitkowski.nfc.se.Command;
5 | import com.piotrekwitkowski.nfc.desfire.Commands;
6 | import com.piotrekwitkowski.nfc.desfire.ResponseCodes;
7 | import com.piotrekwitkowski.nfc.desfire.AID;
8 | import com.piotrekwitkowski.nfc.desfire.InvalidParameterException;
9 | import com.piotrekwitkowski.nfc.se.Application;
10 |
11 | public class InitialState extends State {
12 | private static final String TAG = "InitialState";
13 | private final Application[] applications;
14 |
15 | public InitialState(Application[] applications) {
16 | this.applications = applications;
17 | }
18 |
19 | public CommandResult processCommand(Command command) {
20 | Log.i(TAG, "processCommand()");
21 |
22 | if (command.getCode() == Commands.SELECT_APPLICATION) {
23 | return selectApplication(command.getData());
24 | } else {
25 | return new CommandResult(this, ResponseCodes.ILLEGAL_COMMAND);
26 | }
27 | }
28 |
29 | private CommandResult selectApplication(byte[] aid) {
30 | Log.i(TAG, "selectApplication()");
31 |
32 | try {
33 | AID aidToSelect = new AID(aid);
34 | return new CommandResult(selectApplication(aidToSelect), ResponseCodes.SUCCESS);
35 | } catch (InvalidParameterException ex) {
36 | return new CommandResult(this, ResponseCodes.LENGTH_ERROR);
37 | } catch (ApplicationNotFoundException ex) {
38 | return new CommandResult(this, ResponseCodes.APPLICATION_NOT_FOUND);
39 | }
40 | }
41 |
42 | private ApplicationSelectedState selectApplication(AID aidToSelect) throws ApplicationNotFoundException {
43 | Log.i(TAG, "selectApplication()");
44 | for (Application a : applications) {
45 | if (a.getAid().equals(aidToSelect)) {
46 | return new ApplicationSelectedState(a);
47 | }
48 | }
49 | throw new ApplicationNotFoundException();
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LibraryNFC
2 | is a school project to emulate NXP's MIFARE DESFire-based library ID cards with Android's Host Card Emulation.
3 |
4 | ## LibraryHCE
5 | This module offers emulation of a contactless library ID card. Emulation uses native MIFARE DESFire command set. The DESFire protocol implemented here is [this reverse engineered version](https://github.com/revk/DESFireAES/blob/master/DESFire.pdf).
6 |
7 | [See the list of supported commands.](nfc/src/main/java/com/piotrekwitkowski/nfc/desfire/Commands.java)
8 |
9 | ## LibraryReader
10 | This module enables reading data from physical and emulated DESFire-based library ID cards.
11 |
12 | Its [programmed use-case](LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader) is to
13 | 1. connect with a DESFire card (physical or with a specific Android application)
14 | 2. select a library DESFire Application
15 | 3. authenticate with AES key
16 | 4. read data from a DESFire File
17 |
18 | ## Configuration
19 |
20 | ### [HCE AID](https://developer.android.com/guide/topics/connectivity/nfc/hce#ManifestDeclaration)
21 | The "Android" AID used by both HCE and Reader Android applications can be configured in the [strings.xml](nfc/src/main/res/values/strings.xml) file of the nfc helper library.
22 |
23 | ### Emulated library ID
24 | The data (Application AID, AES key, Data Files) of the emulated DESFire Application can be configured [here](LibraryHCE/src/main/java/com/piotrekwitkowski/libraryhce/application).
25 |
26 | ### Library ID reader
27 | The data (Application AID and AES key) of the Reader module can be configured [here](LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/LibraryReader.java).
28 |
29 | ## Deployment
30 | To deploy the applications two NFC-capable Android phones are needed. My setup included motorola one (Emulator) and Nexus 4 (Reader). I have tested emulation with some Sony and Huawei phones and it didn't work so well. You can use [CTSVerifier](https://source.android.com/compatibility/cts/verifier) to test your phone's NFC capabilities.
31 |
32 | I was using Android Studio version 3.6.1.
33 |
34 | ## Issues
35 | Although I don't plan to update the app anytime soon, feel free to open Issues if you need clarification or help with NFC. I'd like to thank this way for many others that provided me with resources. Please consider starring the repo if you like it!
36 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/java/com/piotrekwitkowski/libraryhce/HCEService.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryhce;
2 |
3 | import android.nfc.cardemulation.HostApduService;
4 | import android.os.Bundle;
5 |
6 | import com.piotrekwitkowski.nfc.se.SecureElement;
7 | import com.piotrekwitkowski.log.Log;
8 | import com.piotrekwitkowski.nfc.ByteUtils;
9 | import com.piotrekwitkowski.nfc.Iso7816;
10 | import com.piotrekwitkowski.nfc.se.Application;
11 | import com.piotrekwitkowski.nfc.se.Emulation;
12 | import com.piotrekwitkowski.nfc.desfire.InvalidParameterException;
13 | import com.piotrekwitkowski.libraryhce.application.LibraryApplication;
14 |
15 | public class HCEService extends HostApduService {
16 | private static final String TAG = "HCEService";
17 | private static boolean firstInteraction = true;
18 | private static Emulation emulation;
19 | private final NotificationService notifications = new NotificationService(this);
20 |
21 | @Override
22 | public byte[] processCommandApdu(byte[] command, Bundle extras) {
23 | byte[] response = firstInteraction ? getFirstResponse(command) : getNextResponse(command);
24 | Log.i(TAG, "--> " + ByteUtils.toHexString(response));
25 | return response;
26 | }
27 |
28 | private byte[] getFirstResponse(byte[] command) {
29 | Log.reset(TAG, "<-- " + ByteUtils.toHexString(command));
30 | notifications.createNotificationChannel(this);
31 | notifications.show("<--" + ByteUtils.toHexString(command));
32 |
33 | try {
34 | emulation = getEmulation();
35 | firstInteraction = false;
36 | return Iso7816.RESPONSE_SUCCESS;
37 | } catch (InvalidParameterException e) {
38 | return Iso7816.RESPONSE_INTERNAL_ERROR;
39 | }
40 | }
41 |
42 | private Emulation getEmulation() throws InvalidParameterException {
43 | Application libraryApplication = new LibraryApplication();
44 | Application[] applications = new Application[] {libraryApplication};
45 | SecureElement seWrapper = new SecureElement(applications);
46 | return new Emulation(seWrapper);
47 | }
48 |
49 | private byte[] getNextResponse(byte[] command) {
50 | Log.i(TAG, "<-- " + ByteUtils.toHexString(command));
51 | notifications.show("<--" + ByteUtils.toHexString(command));
52 | return emulation.getResponse(command);
53 | }
54 |
55 | @Override
56 | public void onDeactivated(int reason) {
57 | Log.i(TAG, "onDeactivated(). Reason: " + reason);
58 | firstInteraction = true;
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/states/ApplicationAuthenticatedState.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se.states;
2 |
3 | import com.piotrekwitkowski.log.Log;
4 | import com.piotrekwitkowski.nfc.ByteUtils;
5 | import com.piotrekwitkowski.nfc.se.Command;
6 | import com.piotrekwitkowski.nfc.desfire.Commands;
7 | import com.piotrekwitkowski.nfc.desfire.File;
8 | import com.piotrekwitkowski.nfc.desfire.ResponseCodes;
9 | import com.piotrekwitkowski.nfc.se.Application;
10 |
11 | public class ApplicationAuthenticatedState extends State {
12 | private static final String TAG = "ApplicationAuthenticatedState";
13 | private final Application application;
14 | private final byte[] sessionKey;
15 |
16 | ApplicationAuthenticatedState(Application application, byte[] sessionKey) {
17 | this.application = application;
18 | this.sessionKey = sessionKey;
19 | }
20 |
21 | public CommandResult processCommand(Command command) {
22 | Log.i(TAG, "processCommand()");
23 |
24 | if (command.getCode() == Commands.READ_DATA) {
25 | byte[] commandData = command.getData();
26 | if (commandData.length == 7) {
27 | return readData(commandData);
28 | } else {
29 | return new CommandResult(this, ResponseCodes.LENGTH_ERROR);
30 | }
31 | } else {
32 | return new CommandResult(this, ResponseCodes.ILLEGAL_COMMAND);
33 | }
34 | }
35 |
36 | private CommandResult readData(byte[] commandData) {
37 | byte fileNumber = commandData[0];
38 | if (fileNumber == 0) {
39 | File file = application.getFile0();
40 | return readFile(file, commandData);
41 | } else {
42 | return new CommandResult(this, ResponseCodes.FILE_NOT_FOUND);
43 | }
44 | }
45 |
46 | private CommandResult readFile(File file, byte[] commandData) {
47 | byte[] offsetBytes = new byte[] {commandData[1], commandData[2], commandData[3]};
48 | byte[] lengthBytes = new byte[] {commandData[4], commandData[5], commandData[6]};
49 | int offset = ByteUtils.threeBytesToInt(offsetBytes);
50 | int length = ByteUtils.threeBytesToInt(lengthBytes);
51 |
52 | try {
53 | byte[] data = file.readData(offset, length);
54 | data = ByteUtils.concatenate(data, getCRC(data));
55 | return new CommandResult(this, ByteUtils.concatenate(ResponseCodes.SUCCESS, data));
56 | } catch (Exception e) {
57 | e.printStackTrace();
58 | return new CommandResult(this, ResponseCodes.BOUNDARY_ERROR);
59 | }
60 | }
61 |
62 | private byte[] getCRC(byte[] data) {
63 | Log.i(TAG, "sessionKey: " + ByteUtils.toHexString(sessionKey));
64 | Log.i(TAG, "generating CRC for: " + ByteUtils.toHexString(data));
65 |
66 | // TODO: implement CRC
67 | return new byte[8];
68 | }
69 |
70 | }
71 |
72 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/StudentId.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | import android.content.Context;
4 |
5 | import com.piotrekwitkowski.log.Log;
6 | import com.piotrekwitkowski.nfc.ByteUtils;
7 | import com.piotrekwitkowski.nfc.Iso7816;
8 | import com.piotrekwitkowski.nfc.desfire.AID;
9 | import com.piotrekwitkowski.nfc.desfire.AESKey;
10 |
11 | import java.io.IOException;
12 | import java.util.Arrays;
13 |
14 | @SuppressWarnings("SameParameterValue")
15 | class StudentId {
16 | private static final String TAG = "StudentId";
17 | private final IsoDep isoDep;
18 | enum idForm {PHYSICAL, HCE}
19 |
20 | private StudentId(IsoDep isoDep) {
21 | this.isoDep = isoDep;
22 | }
23 |
24 | static StudentId getStudentId(Context context, IsoDep isoDep) throws Exception {
25 | Log.i(TAG, "getStudentId()");
26 | isoDep.connect();
27 |
28 | idForm idForm = getIdForm(isoDep);
29 | Log.i(TAG, "ID form: "+ idForm);
30 |
31 | if (idForm == StudentId.idForm.PHYSICAL) {
32 | return new StudentId(isoDep);
33 | } else if (idForm == StudentId.idForm.HCE) {
34 | Response response = HCE.selectAndroidApp(context, isoDep);
35 | if (Arrays.equals(response.getBytes(), Iso7816.RESPONSE_SUCCESS)) {
36 | return new StudentId(isoDep);
37 | } else {
38 | throw new StudentIdException("HCE Mobile Application select was unsuccessful");
39 | }
40 | } else {
41 | throw new StudentIdException("ID form not supported");
42 | }
43 | }
44 |
45 | void close() throws IOException {
46 | isoDep.close();
47 | }
48 |
49 | private static idForm getIdForm(IsoDep isoDep) throws StudentIdException {
50 | Log.i(TAG, "getIdForm()");
51 |
52 | byte[] historicalBytes = isoDep.getHistoricalBytes();
53 | Log.i(TAG, "historicalBytes: " + ByteUtils.toHexString(historicalBytes));
54 |
55 | if (Arrays.equals(historicalBytes, new byte[]{(byte) 0x80})) {
56 | return idForm.PHYSICAL;
57 | } else if (Arrays.equals(historicalBytes, new byte[]{})) {
58 | return idForm.HCE;
59 | } else {
60 | throw new StudentIdException("id form not recognized");
61 | }
62 | }
63 |
64 | void selectApplication(AID aid) throws IOException, DESFireReaderException {
65 | byte[] applicationAid = aid.getBytes();
66 | DESFireReader.selectApplication(this.isoDep, applicationAid);
67 | Log.i(TAG, "Application selected: " + ByteUtils.toHexString(applicationAid));
68 | }
69 |
70 | void authenticateAES(AESKey key, int keyNumber) throws Exception {
71 | byte[] sessionKey = DESFireReader.authenticateAES(this.isoDep, key.getKey(), (byte) keyNumber);
72 | Log.i(TAG, "Session key: " + ByteUtils.toHexString(sessionKey));
73 | }
74 |
75 | byte[] readData(int fileNumber, int offset, int length) throws IOException, DESFireReaderException {
76 | byte[] response = DESFireReader.readData(this.isoDep, fileNumber, offset, length);
77 | // TODO: check CRC (last 8 bytes)
78 | byte[] data = ByteUtils.trimEnd(response, 8);
79 | Log.i(TAG, "Data: " + ByteUtils.toHexString(data));
80 | return data;
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/ByteUtils.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc;
2 |
3 | import java.nio.ByteBuffer;
4 | import java.security.SecureRandom;
5 | import java.util.Arrays;
6 |
7 | public class ByteUtils {
8 |
9 | public static byte[] toByteArray(String s) throws IllegalArgumentException {
10 | int len = s.length();
11 | if (len % 2 == 1) {
12 | throw new IllegalArgumentException("Hex string must have even number of characters");
13 | }
14 | byte[] data = new byte[len / 2]; // Allocate 1 byte per 2 hex characters
15 | for (int i = 0; i < len; i += 2) {
16 | // Convert each character into a integer (base-16), then bit-shift into place
17 | data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
18 | + Character.digit(s.charAt(i+1), 16));
19 | }
20 | return data;
21 | }
22 |
23 | public static String toHexString(byte[] bytes) {
24 | final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
25 | char[] hexChars = new char[bytes.length * 2]; // Each byte has two hex characters (nibbles)
26 | int v;
27 | for (int j = 0; j < bytes.length; j++) {
28 | v = bytes[j] & 0xFF; // Cast bytes[j] to int, treating as unsigned value
29 | hexChars[j * 2] = hexArray[v >>> 4]; // Select hex character from upper nibble
30 | hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // Select hex character from lower nibble
31 | }
32 | return new String(hexChars);
33 | }
34 |
35 | public static byte[] concatenate(byte a, byte b) {
36 | return new byte[] {a, b};
37 | }
38 |
39 | public static byte[] concatenate(byte a, byte[] b) {
40 | return concatenate(new byte[] { a }, b );
41 | }
42 |
43 | public static byte[] concatenate(byte[] a, byte[] b) {
44 | byte[] c = new byte[a.length + b.length];
45 | System.arraycopy(a, 0, c, 0, a.length);
46 | System.arraycopy(b, 0, c, a.length, b.length);
47 | return c;
48 | }
49 |
50 | public static byte[] rotateOneLeft(byte[] a) {
51 | final byte[] rotated = new byte[a.length];
52 | if (a.length - 1 >= 0) System.arraycopy(a, 1, rotated, 0, a.length - 1);
53 | rotated[rotated.length - 1] = a[0];
54 | return rotated;
55 | }
56 |
57 | public static byte[] first16Bytes(byte[] a) {
58 | return Arrays.copyOfRange(a,0, 16);
59 | }
60 |
61 | public static byte[] last16Bytes(byte[] a) {
62 | return Arrays.copyOfRange(a,a.length - 16, a.length);
63 | }
64 |
65 | public static byte[] getRandomBytes(int length) {
66 | byte[] random = new byte[length];
67 | new SecureRandom().nextBytes(random);
68 | return random;
69 | }
70 |
71 | public static byte[] first3Bytes(int i) {
72 | return new byte[] {
73 | (byte)((i) & 0xff),
74 | (byte)((i >> 8) & 0xff),
75 | (byte)((i >> 16) & 0xff),
76 | // (byte)((i >> 24) & 0xff),
77 | };
78 | }
79 |
80 | public static int threeBytesToInt(byte[] bytes) {
81 | byte[] moreBytes = new byte[] {
82 | (byte) 0x00,
83 | bytes[2],
84 | bytes[1],
85 | bytes[0],
86 | };
87 | return ByteBuffer.wrap(moreBytes).getInt();
88 | }
89 |
90 | public static byte[] trimEnd(byte[] bytes, int i) {
91 | return Arrays.copyOfRange(bytes, 0, bytes.length - i);
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | xmlns:android
14 |
15 | ^$
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | xmlns:.*
25 |
26 | ^$
27 |
28 |
29 | BY_NAME
30 |
31 |
32 |
33 |
34 |
35 |
36 | .*:id
37 |
38 | http://schemas.android.com/apk/res/android
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | .*:name
48 |
49 | http://schemas.android.com/apk/res/android
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | name
59 |
60 | ^$
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | style
70 |
71 | ^$
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | .*
81 |
82 | ^$
83 |
84 |
85 | BY_NAME
86 |
87 |
88 |
89 |
90 |
91 |
92 | .*
93 |
94 | http://schemas.android.com/apk/res/android
95 |
96 |
97 | ANDROID_ATTRIBUTE_ORDER
98 |
99 |
100 |
101 |
102 |
103 |
104 | .*
105 |
106 | .*
107 |
108 |
109 | BY_NAME
110 |
111 |
112 |
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/states/ApplicationSelectedState.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se.states;
2 |
3 | import com.piotrekwitkowski.log.Log;
4 | import com.piotrekwitkowski.nfc.ByteUtils;
5 | import com.piotrekwitkowski.nfc.desfire.Commands;
6 | import com.piotrekwitkowski.nfc.desfire.ResponseCodes;
7 | import com.piotrekwitkowski.nfc.se.Command;
8 | import com.piotrekwitkowski.nfc.se.Application;
9 | import com.piotrekwitkowski.nfc.se.Authentication;
10 | import com.piotrekwitkowski.nfc.se.AuthenticationException;
11 | import com.piotrekwitkowski.nfc.se.AuthenticationResponse;
12 | import com.piotrekwitkowski.nfc.se.NoSuchKeyException;
13 |
14 | public class ApplicationSelectedState extends State {
15 | private static final String TAG = "ApplicationSelectedState";
16 | private final Application application;
17 | private boolean authenticationInProgress = false;
18 | private Authentication authentication;
19 |
20 | ApplicationSelectedState(Application application) {
21 | this.application = application;
22 | }
23 |
24 | public CommandResult processCommand(Command command) {
25 | Log.i(TAG, "processCommand()");
26 |
27 | byte commandCode = command.getCode();
28 | byte[] commandData = command.getData();
29 |
30 | try {
31 | if (!authenticationInProgress && commandCode == Commands.AUTHENTICATE_AES) {
32 | return new CommandResult(this, ByteUtils.concatenate(ResponseCodes.ADDITIONAL_FRAME, initiateAESAuthentication(commandData)));
33 | } else if (authenticationInProgress && commandCode == Commands.ADDITIONAL_FRAME) {
34 | return proceedAuthentication(commandData);
35 | } else {
36 | return new CommandResult(this, ResponseCodes.ILLEGAL_COMMAND);
37 | }
38 | } catch (AuthenticationException e) {
39 | return new CommandResult(this, ResponseCodes.AUTHENTICATION_ERROR);
40 | } catch (CommandDataLengthException e) {
41 | return new CommandResult(this, ResponseCodes.LENGTH_ERROR);
42 | } catch (NoSuchKeyException e) {
43 | return new CommandResult(this, ResponseCodes.NO_SUCH_KEY);
44 | }
45 | }
46 |
47 | private byte[] initiateAESAuthentication(byte[] commandData) throws AuthenticationException, CommandDataLengthException, NoSuchKeyException {
48 | if (commandData.length == 1) {
49 | byte[] challenge = getChallenge(commandData[0]);
50 | Log.i(TAG, "challenge: " + ByteUtils.toHexString(challenge));
51 | this.authenticationInProgress = true;
52 | return challenge;
53 | } else {
54 | throw new CommandDataLengthException();
55 | }
56 | }
57 |
58 | private byte[] getChallenge(byte keyNumber) throws AuthenticationException, NoSuchKeyException {
59 | Log.i(TAG, "proceedAuthentication() " + keyNumber);
60 |
61 | try {
62 | this.authentication = new Authentication(this.application);
63 | return this.authentication.initiate(keyNumber);
64 | } catch (NoSuchKeyException e) {
65 | throw e;
66 | } catch (Exception e) {
67 | throw new AuthenticationException();
68 | }
69 | }
70 |
71 | private CommandResult proceedAuthentication(byte[] readerChallenge) throws AuthenticationException, CommandDataLengthException {
72 | Log.i(TAG, "proceedAuthentication() " + readerChallenge.length);
73 | if (readerChallenge.length == 32) {
74 | try {
75 | AuthenticationResponse authenticationResponse = this.authentication.proceed(readerChallenge);
76 | this.authenticationInProgress = false;
77 | byte[] response = ByteUtils.concatenate(ResponseCodes.SUCCESS, authenticationResponse.getEncryptedRotatedA());
78 | return new CommandResult(new ApplicationAuthenticatedState(this.application, authenticationResponse.getSessionKey()), response);
79 | } catch (Exception e) {
80 | throw new AuthenticationException();
81 | }
82 | } else {
83 | throw new CommandDataLengthException();
84 | }
85 | }
86 |
87 | }
--------------------------------------------------------------------------------
/nfc/src/main/java/com/piotrekwitkowski/nfc/se/Authentication.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.nfc.se;
2 |
3 | import com.piotrekwitkowski.log.Log;
4 | import com.piotrekwitkowski.nfc.ByteUtils;
5 | import com.piotrekwitkowski.nfc.desfire.AESKey;
6 |
7 | import java.io.ByteArrayOutputStream;
8 | import java.security.InvalidAlgorithmParameterException;
9 | import java.security.InvalidKeyException;
10 | import java.security.NoSuchAlgorithmException;
11 | import java.util.Arrays;
12 |
13 | import javax.crypto.BadPaddingException;
14 | import javax.crypto.Cipher;
15 | import javax.crypto.IllegalBlockSizeException;
16 | import javax.crypto.NoSuchPaddingException;
17 | import javax.crypto.spec.IvParameterSpec;
18 | import javax.crypto.spec.SecretKeySpec;
19 |
20 | public class Authentication {
21 | private static final String TAG = "ApplicationAuthentication";
22 | private final AESKey key;
23 | private final Cipher cipher;
24 | private final SecretKeySpec aes;
25 |
26 | private byte[] randomBytes;
27 | private byte[] challenge;
28 |
29 | public Authentication(Application application) throws NoSuchPaddingException, NoSuchAlgorithmException {
30 | this.key = application.getKey0();
31 | this.cipher = Cipher.getInstance("AES/CBC/NoPadding");
32 | this.aes = new SecretKeySpec(application.getKey0().getKey(), "AES");
33 | }
34 |
35 | public byte[] initiate(byte keyNumber) throws InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchKeyException {
36 | // 1. The reader asked for AES authentication for a specific key.
37 | if (keyNumber != 0) {
38 | throw new NoSuchKeyException();
39 | }
40 |
41 | // 2. The card creates a 16 byte random number (B) and encrypts it with the selected AES
42 | // key. The result is sent to the reader.
43 | this.randomBytes = ByteUtils.getRandomBytes(16);
44 | Log.i(TAG, "random bytes: " + ByteUtils.toHexString(randomBytes));
45 | IvParameterSpec ivParam = new IvParameterSpec(new byte[key.getKey().length]);
46 | cipher.init(Cipher.ENCRYPT_MODE, aes, ivParam);
47 | this.challenge = cipher.doFinal(this.randomBytes);
48 | return challenge;
49 | }
50 |
51 | public AuthenticationResponse proceed(byte[] readerChallenge) throws InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, AuthenticationException {
52 | // 3. The reader receives the 16 bytes, and decrypts it using the AES key to get back the
53 | // original 16 byte random number (B). This is decrypted with an IV of all 00 bytes.
54 | // 4. The reader generates its own 16 byte random number (A).
55 | // 5. The reader rotates B one byte to the left.
56 | // 6. The reader concatenates A and the rotated B together to make a 32 byte value C.
57 | // 7. The reader encrypts the 32 byte value C with the AES key and sends D to the card. The
58 | // IV for encrypting this is the 16 bytes received from the card (i.e. before decryption).
59 | // 8. The card receives the 32 byte value D and decrypts it with the AES key.
60 | IvParameterSpec ivParam = new IvParameterSpec(this.challenge);
61 | cipher.init(Cipher.DECRYPT_MODE, aes, ivParam);
62 | byte[] C = cipher.doFinal(readerChallenge);
63 | Log.i(TAG, "from Reader: " + ByteUtils.toHexString(C));
64 |
65 | // 9. The card checks the second 16 bytes of C match the original random number B (rotated one
66 | // byte left). If this fails the authentication has failed. If it matches, the card knows
67 | // the reader has the right key.
68 | if (!Arrays.equals(ByteUtils.last16Bytes(C), ByteUtils.rotateOneLeft(this.randomBytes))) {
69 | throw new AuthenticationException();
70 | }
71 |
72 | // 10. The card rotates the first 16 bytes (A) left by one byte.
73 | byte[] A = ByteUtils.first16Bytes(C);
74 | byte[] rotatedA = ByteUtils.rotateOneLeft(A);
75 |
76 | // 11. The card encrypts this rotated A using the AES key and sends it to the reader.
77 | // 12. The reader receives the 16 bytes and decrypts it. The IV for this is the last 16
78 | // bytes the reader sent to the card.
79 | ivParam = new IvParameterSpec(ByteUtils.last16Bytes(readerChallenge));
80 | cipher.init(Cipher.ENCRYPT_MODE, aes, ivParam);
81 | byte[] encryptedRotatedA = cipher.doFinal(rotatedA);
82 |
83 | // 13. The reader checks this matches the original A random number (rotated one byte left).
84 | // If this fails then the authentication fails. If it matches, the reader knows the card
85 | // has the AES key too.
86 | // 14. Finally both reader and card generate a 16 byte session key using the random numbers
87 | // they now know. This is done by concatenating the first 4 bytes of A, first 4 bytes of B,
88 | // last 4 bytes of A and last 4 bytes of B.
89 | ByteArrayOutputStream sessionKeyOutputStream = new ByteArrayOutputStream();
90 | sessionKeyOutputStream.write(A, 0, 4);
91 | sessionKeyOutputStream.write(randomBytes, 0, 4);
92 | sessionKeyOutputStream.write(A, 12, 4);
93 | sessionKeyOutputStream.write(randomBytes, 12, 4);
94 | byte[] sessionKey = sessionKeyOutputStream.toByteArray();
95 |
96 | return new AuthenticationResponse(sessionKey, encryptedRotatedA);
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ]; do
14 | ls=$(ls -ld "$PRG")
15 | link=$(expr "$ls" : '.*-> \(.*\)$')
16 | if expr "$link" : '/.*' >/dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=$(dirname "$PRG")"/$link"
20 | fi
21 | done
22 | SAVED="$(pwd)"
23 | cd "$(dirname \"$PRG\")/" >/dev/null
24 | APP_HOME="$(pwd -P)"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=$(basename "$0")
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn() {
37 | echo "$*"
38 | }
39 |
40 | die() {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "$(uname)" in
53 | CYGWIN*)
54 | cygwin=true
55 | ;;
56 | Darwin*)
57 | darwin=true
58 | ;;
59 | MINGW*)
60 | msys=true
61 | ;;
62 | NONSTOP*)
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ]; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ]; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ]; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ]; then
93 | MAX_FD_LIMIT=$(ulimit -H -n)
94 | if [ $? -eq 0 ]; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ]; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ]; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin; then
114 | APP_HOME=$(cygpath --path --mixed "$APP_HOME")
115 | CLASSPATH=$(cygpath --path --mixed "$CLASSPATH")
116 | JAVACMD=$(cygpath --unix "$JAVACMD")
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=$(find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null)
120 | SEP=""
121 | for dir in $ROOTDIRSRAW; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ]; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@"; do
133 | CHECK=$(echo "$arg" | egrep -c "$OURCYGPATTERN" -)
134 | CHECK2=$(echo "$arg" | egrep -c "^-") ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ]; then ### Added a condition
137 | eval $(echo args$i)=$(cygpath --path --ignore --mixed "$arg")
138 | else
139 | eval $(echo args$i)="\"$arg\""
140 | fi
141 | i=$((i + 1))
142 | done
143 | case $i in
144 | 0) set -- ;;
145 | 1) set -- "$args0" ;;
146 | 2) set -- "$args0" "$args1" ;;
147 | 3) set -- "$args0" "$args1" "$args2" ;;
148 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save() {
159 | for i; do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/"; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/LibraryHCE/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/LibraryReader/src/main/java/com/piotrekwitkowski/libraryreader/DESFireReader.java:
--------------------------------------------------------------------------------
1 | package com.piotrekwitkowski.libraryreader;
2 |
3 | import com.piotrekwitkowski.log.Log;
4 | import com.piotrekwitkowski.nfc.ByteUtils;
5 | import com.piotrekwitkowski.nfc.desfire.Commands;
6 | import com.piotrekwitkowski.nfc.desfire.ResponseCodes;
7 |
8 | import java.io.ByteArrayOutputStream;
9 | import java.io.IOException;
10 | import java.security.InvalidAlgorithmParameterException;
11 | import java.security.InvalidKeyException;
12 | import java.security.Key;
13 | import java.security.NoSuchAlgorithmException;
14 | import java.util.Arrays;
15 |
16 | import javax.crypto.BadPaddingException;
17 | import javax.crypto.Cipher;
18 | import javax.crypto.IllegalBlockSizeException;
19 | import javax.crypto.NoSuchPaddingException;
20 | import javax.crypto.spec.IvParameterSpec;
21 | import javax.crypto.spec.SecretKeySpec;
22 |
23 | class DESFireReader {
24 | private static final String TAG = "DESFireReader";
25 |
26 | static void selectApplication(IsoDep isoDep, byte[] aid) throws IOException, DESFireReaderException {
27 | Log.i(TAG, "selectApplication()");
28 |
29 | Response response = isoDep.transceive(Commands.SELECT_APPLICATION, aid);
30 | if (response.getResponseCode() != ResponseCodes.SUCCESS) {
31 | throw new DESFireReaderException("selectApplication() failed. Response status: " + response.getResponseCode());
32 | }
33 | }
34 |
35 | static byte[] authenticateAES(IsoDep isoDep, byte[] aesKey, byte keyNumber) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, DESFireReaderException {
36 | Log.i(TAG, "authenticateAES()");
37 |
38 | // 1. The reader asked for AES authentication for a specific key.
39 | // 2. The card creates a 16 byte random number (B) and encrypts it with the selected AES
40 | // key. The result is sent to the reader.
41 | Response response = isoDep.transceive(Commands.AUTHENTICATE_AES, keyNumber);
42 | byte[] challenge = response.getData();
43 | Log.i(TAG, "challenge: " + ByteUtils.toHexString(challenge));
44 |
45 | // 3. The reader receives the 16 bytes, and decrypts it using the AES key to get back the
46 | // original 16 byte random number (B). This is decrypted with an IV of all 00 bytes.
47 | Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
48 | Key aes = new SecretKeySpec(aesKey, "AES");
49 | IvParameterSpec ivParam = new IvParameterSpec(new byte[16]);
50 | cipher.init(Cipher.DECRYPT_MODE, aes, ivParam);
51 | byte[] B = cipher.doFinal(challenge);
52 | Log.i(TAG, "cipheredData: " + ByteUtils.toHexString(B));
53 |
54 | // 4. The reader generates its own 16 byte random number (A).
55 | byte[] A = ByteUtils.getRandomBytes(16);
56 |
57 | // 5. The reader rotates B one byte to the left.
58 | byte[] rotatedB = ByteUtils.rotateOneLeft(B);
59 |
60 | // 6. The reader concatenates A and the rotated B together to make a 32 byte value C.
61 | byte[] C = ByteUtils.concatenate(A, rotatedB);
62 |
63 | // 7. The reader encrypts the 32 byte value C with the AES key and sends D to the card. The
64 | // IV for encrypting this is the 16 bytes received from the card (i.e. before decryption).
65 | ivParam = new IvParameterSpec(challenge);
66 | cipher.init(Cipher.ENCRYPT_MODE, aes, ivParam);
67 | byte[] D = cipher.doFinal(C);
68 | byte[] command = ByteUtils.concatenate(Commands.ADDITIONAL_FRAME, D);
69 | response = isoDep.transceive(command);
70 | challenge = response.getData();
71 |
72 | // 8. The card receives the 32 byte value D and decrypts it with the AES key.
73 | // 9. The card checks the second 16 bytes match the original random number B (rotated one
74 | // byte left). If this fails the authentication has failed. If it matches, the card knows
75 | // the reader has the right key.
76 | if (response.getResponseCode() != ResponseCodes.SUCCESS) {
77 | throw new DESFireReaderException("authenticateAES failed");
78 | }
79 |
80 | // 10. The card rotates the first 16 bytes (A) left by one byte.
81 | // 11. The card encrypts this rotated A using the AES key and sends it to the reader.
82 | // 12. The reader receives the 16 bytes and decrypts it. The IV for this is the last 16
83 | // bytes the reader sent to the card.
84 | byte[] last16Bytes = ByteUtils.last16Bytes(command);
85 | ivParam = new IvParameterSpec(last16Bytes);
86 | cipher.init(Cipher.DECRYPT_MODE, aes, ivParam);
87 | byte[] E = cipher.doFinal(challenge);
88 |
89 | // 13. The reader checks this matches the original A random number (rotated one byte left).
90 | // If this fails then the authentication fails. If it matches, the reader knows the card
91 | // has the AES key too.
92 | if (!Arrays.equals(ByteUtils.rotateOneLeft(A), E)) {
93 | throw new DESFireReaderException("authenticateAES failed");
94 | }
95 |
96 | // 14. Finally both reader and card generate a 16 byte session key using the random numbers
97 | // they now know. This is done by concatenating the first 4 bytes of A, first 4 bytes of B,
98 | // last 4 bytes of A and last 4 bytes of B.
99 | ByteArrayOutputStream sessionKeyOutputStream = new ByteArrayOutputStream();
100 | sessionKeyOutputStream.write(A, 0, 4);
101 | sessionKeyOutputStream.write(B, 0, 4);
102 | sessionKeyOutputStream.write(A, 12, 4);
103 | sessionKeyOutputStream.write(B, 12, 4);
104 | return sessionKeyOutputStream.toByteArray();
105 | }
106 |
107 | static byte[] readData(IsoDep isoDep, int fileNumber, int offset, int length) throws IOException, DESFireReaderException {
108 | Log.i(TAG, "readData()");
109 |
110 | // TODO: check if file
111 | // TODO: check if offset and length smaller than 3 bytes, else throw Exception
112 | byte[] offsetBytes = ByteUtils.first3Bytes(offset);
113 | byte[] lengthBytes = ByteUtils.first3Bytes(length);
114 |
115 | byte[] params = ByteUtils.concatenate(offsetBytes, lengthBytes);
116 | byte[] commandData = ByteUtils.concatenate((byte) fileNumber, params);
117 |
118 | Response response = isoDep.transceive(Commands.READ_DATA, commandData);
119 | if (response.getResponseCode() == ResponseCodes.SUCCESS) {
120 | return response.getData();
121 | } else if (response.getResponseCode() == ResponseCodes.BOUNDARY_ERROR) {
122 | throw new DESFireReaderException("Boundary error!");
123 | } else {
124 | throw new DESFireReaderException("readData failed. Response status: " + response.getResponseCode());
125 | }
126 | }
127 |
128 | }
129 |
--------------------------------------------------------------------------------