├── LICENSE ├── README.md ├── TagWallet.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ ├── IDEWorkspaceChecks.plist │ │ └── swiftpm │ │ └── Package.resolved └── xcuserdata │ └── kevinbrewster.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── TagWallet ├── MiFareTag.swift ├── NTAG215Tag.swift ├── TagDump.swift └── TagEncyption.swift └── TagWalletUI ├── AppDelegate.swift ├── Assets.xcassets ├── AppIcon.appiconset │ └── Contents.json ├── Contents.json └── binary_file.imageset │ ├── Contents.json │ ├── binary_file.png │ └── icons8-binary-file-100.png ├── Base.lproj ├── LaunchScreen.storyboard └── Main.storyboard ├── Info.plist ├── SceneDelegate.swift ├── TagProduct.swift ├── TagProductViewController.swift ├── TagProductsCollectionViewController+TagReading.swift ├── TagProductsCollectionViewController.swift ├── TagWallet.entitlements └── initialTagWallet.json /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kevin Brewster 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TagWallet 2 | 3 | TagWallet is an simple iOS app to manage MiFare NTAG215 NFC (e.g. Amiibo) tags. You can read tags, save the data dumps, 4 | and optionally write those data dumps to a new blank tag. 5 | 6 | It's similar to the Android [TagMo](https://github.com/HiddenRamblings/TagMo) App. 7 | 8 | ## Background 9 | 10 | [Reverse Engineering Nintendo Amiibo](https://kevinbrewster.github.io/Amiibo-Reverse-Engineering/) 11 | 12 | ## Requirements 13 | 14 | iPhone 7 or above and iOS 13 or above (for NFC write capabilities) 15 | 16 | ## Installation 17 | 18 | There is no binary available and the app is not available on the App Store. You need to download the code, 19 | open in Xcode and manually run it on an iPhone. 20 | 21 | ## Configuration 22 | 23 | In the TagWalletUI folder is a file `initialTagWallet.json`. By default, this file is misconfigured. You will need 24 | to update the file with valid values to enable decrpytion and cloning of certain NTAG215 cards. 25 | 26 | `staticKey`: An 80-byte base64 encoded retail key (aka "locked-secret.bin") 27 | 28 | `dataKey`: An 80-byte base64 encoded retail key (aka "unfixed-info.bin") 29 | 30 | `tagProducts`: An array of previously dumped tag data. 31 | 32 | 33 | Example `initialTagWallet.json`: 34 | 35 | ```json 36 | { 37 | "dataKey": { 38 | "data": "__SOME_BASE64_ENCODED_STRING_OF_80_BYTES__" 39 | }, 40 | "staticKey": { 41 | "data": "__SOME_BASE64_ENCODED_STRING_OF_80_BYTES__" 42 | }, 43 | "tagProducts": [ 44 | { 45 | "tail": "__4_BYTE_HEX__", 46 | "character": "Test", 47 | "head": "__4_BYTE_HEX__", 48 | "gameSeries": "Test", 49 | "type": "Figure", 50 | "imageURL": "", 51 | "name": "Test", 52 | "productSeries": "Test", 53 | "dumps": [ 54 | { 55 | "data": "__SOME_BASE64_ENCODED_STRING_OF_540_BYTES__" 56 | } 57 | ] 58 | } 59 | ] 60 | } 61 | ``` 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /TagWallet.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 52; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 67BC1483245205A00028E9FE /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC1482245205A00028E9FE /* AppDelegate.swift */; }; 11 | 67BC1485245205A00028E9FE /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC1484245205A00028E9FE /* SceneDelegate.swift */; }; 12 | 67BC148A245205A00028E9FE /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 67BC1488245205A00028E9FE /* Main.storyboard */; }; 13 | 67BC148C245205A20028E9FE /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 67BC148B245205A20028E9FE /* Assets.xcassets */; }; 14 | 67BC148F245205A20028E9FE /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 67BC148D245205A20028E9FE /* LaunchScreen.storyboard */; }; 15 | 67BC1498245206C70028E9FE /* TagProduct.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC1497245206C70028E9FE /* TagProduct.swift */; }; 16 | 67BC149C245206F00028E9FE /* TagEncyption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC149B245206F00028E9FE /* TagEncyption.swift */; }; 17 | 67BC149F245207930028E9FE /* CryptoSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 67BC149E245207930028E9FE /* CryptoSwift */; }; 18 | 67BC14A1245208190028E9FE /* TagProductsCollectionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC14A0245208190028E9FE /* TagProductsCollectionViewController.swift */; }; 19 | 67BC14A324520A350028E9FE /* TagProductsCollectionViewController+TagReading.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC14A224520A350028E9FE /* TagProductsCollectionViewController+TagReading.swift */; }; 20 | 67BC14A524520A5E0028E9FE /* TagProductViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC14A424520A5E0028E9FE /* TagProductViewController.swift */; }; 21 | 67BC14A924520BAB0028E9FE /* TagDump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC14A824520BAB0028E9FE /* TagDump.swift */; }; 22 | 67BC14AC24520BB70028E9FE /* NTAG215Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC14AA24520BB70028E9FE /* NTAG215Tag.swift */; }; 23 | 67BC14AD24520BB70028E9FE /* MiFareTag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67BC14AB24520BB70028E9FE /* MiFareTag.swift */; }; 24 | 67CC96952456228800592A27 /* initialTagWallet.json in Resources */ = {isa = PBXBuildFile; fileRef = 67CC96942456228800592A27 /* initialTagWallet.json */; }; 25 | /* End PBXBuildFile section */ 26 | 27 | /* Begin PBXFileReference section */ 28 | 67BC147F245205A00028E9FE /* TagWallet.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TagWallet.app; sourceTree = BUILT_PRODUCTS_DIR; }; 29 | 67BC1482245205A00028E9FE /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 30 | 67BC1484245205A00028E9FE /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; 31 | 67BC1489245205A00028E9FE /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 32 | 67BC148B245205A20028E9FE /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 33 | 67BC148E245205A20028E9FE /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 34 | 67BC1490245205A20028E9FE /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 35 | 67BC1497245206C70028E9FE /* TagProduct.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TagProduct.swift; sourceTree = ""; }; 36 | 67BC149B245206F00028E9FE /* TagEncyption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TagEncyption.swift; sourceTree = ""; }; 37 | 67BC14A0245208190028E9FE /* TagProductsCollectionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TagProductsCollectionViewController.swift; sourceTree = ""; }; 38 | 67BC14A224520A350028E9FE /* TagProductsCollectionViewController+TagReading.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TagProductsCollectionViewController+TagReading.swift"; sourceTree = ""; }; 39 | 67BC14A424520A5E0028E9FE /* TagProductViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TagProductViewController.swift; sourceTree = ""; }; 40 | 67BC14A824520BAB0028E9FE /* TagDump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TagDump.swift; sourceTree = ""; }; 41 | 67BC14AA24520BB70028E9FE /* NTAG215Tag.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NTAG215Tag.swift; sourceTree = ""; }; 42 | 67BC14AB24520BB70028E9FE /* MiFareTag.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MiFareTag.swift; sourceTree = ""; }; 43 | 67CC96932454091E00592A27 /* TagWallet.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = TagWallet.entitlements; sourceTree = ""; }; 44 | 67CC96942456228800592A27 /* initialTagWallet.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = initialTagWallet.json; sourceTree = ""; }; 45 | /* End PBXFileReference section */ 46 | 47 | /* Begin PBXFrameworksBuildPhase section */ 48 | 67BC147C245205A00028E9FE /* Frameworks */ = { 49 | isa = PBXFrameworksBuildPhase; 50 | buildActionMask = 2147483647; 51 | files = ( 52 | 67BC149F245207930028E9FE /* CryptoSwift in Frameworks */, 53 | ); 54 | runOnlyForDeploymentPostprocessing = 0; 55 | }; 56 | /* End PBXFrameworksBuildPhase section */ 57 | 58 | /* Begin PBXGroup section */ 59 | 67BC1476245205A00028E9FE = { 60 | isa = PBXGroup; 61 | children = ( 62 | 67BC1496245205F10028E9FE /* TagWallet */, 63 | 67BC1481245205A00028E9FE /* TagWalletUI */, 64 | 67BC1480245205A00028E9FE /* Products */, 65 | ); 66 | sourceTree = ""; 67 | }; 68 | 67BC1480245205A00028E9FE /* Products */ = { 69 | isa = PBXGroup; 70 | children = ( 71 | 67BC147F245205A00028E9FE /* TagWallet.app */, 72 | ); 73 | name = Products; 74 | sourceTree = ""; 75 | }; 76 | 67BC1481245205A00028E9FE /* TagWalletUI */ = { 77 | isa = PBXGroup; 78 | children = ( 79 | 67CC96932454091E00592A27 /* TagWallet.entitlements */, 80 | 67CC96942456228800592A27 /* initialTagWallet.json */, 81 | 67BC1482245205A00028E9FE /* AppDelegate.swift */, 82 | 67BC1484245205A00028E9FE /* SceneDelegate.swift */, 83 | 67BC1497245206C70028E9FE /* TagProduct.swift */, 84 | 67BC1488245205A00028E9FE /* Main.storyboard */, 85 | 67BC148B245205A20028E9FE /* Assets.xcassets */, 86 | 67BC14A0245208190028E9FE /* TagProductsCollectionViewController.swift */, 87 | 67BC14A224520A350028E9FE /* TagProductsCollectionViewController+TagReading.swift */, 88 | 67BC14A424520A5E0028E9FE /* TagProductViewController.swift */, 89 | 67BC148D245205A20028E9FE /* LaunchScreen.storyboard */, 90 | 67BC1490245205A20028E9FE /* Info.plist */, 91 | ); 92 | path = TagWalletUI; 93 | sourceTree = ""; 94 | }; 95 | 67BC1496245205F10028E9FE /* TagWallet */ = { 96 | isa = PBXGroup; 97 | children = ( 98 | 67BC14AB24520BB70028E9FE /* MiFareTag.swift */, 99 | 67BC14AA24520BB70028E9FE /* NTAG215Tag.swift */, 100 | 67BC14A824520BAB0028E9FE /* TagDump.swift */, 101 | 67BC149B245206F00028E9FE /* TagEncyption.swift */, 102 | ); 103 | path = TagWallet; 104 | sourceTree = ""; 105 | }; 106 | /* End PBXGroup section */ 107 | 108 | /* Begin PBXNativeTarget section */ 109 | 67BC147E245205A00028E9FE /* TagWallet */ = { 110 | isa = PBXNativeTarget; 111 | buildConfigurationList = 67BC1493245205A20028E9FE /* Build configuration list for PBXNativeTarget "TagWallet" */; 112 | buildPhases = ( 113 | 67BC147B245205A00028E9FE /* Sources */, 114 | 67BC147C245205A00028E9FE /* Frameworks */, 115 | 67BC147D245205A00028E9FE /* Resources */, 116 | ); 117 | buildRules = ( 118 | ); 119 | dependencies = ( 120 | ); 121 | name = TagWallet; 122 | packageProductDependencies = ( 123 | 67BC149E245207930028E9FE /* CryptoSwift */, 124 | ); 125 | productName = TagWallet; 126 | productReference = 67BC147F245205A00028E9FE /* TagWallet.app */; 127 | productType = "com.apple.product-type.application"; 128 | }; 129 | /* End PBXNativeTarget section */ 130 | 131 | /* Begin PBXProject section */ 132 | 67BC1477245205A00028E9FE /* Project object */ = { 133 | isa = PBXProject; 134 | attributes = { 135 | LastSwiftUpdateCheck = 1140; 136 | LastUpgradeCheck = 1140; 137 | ORGANIZATIONNAME = "Kevin Brewster"; 138 | TargetAttributes = { 139 | 67BC147E245205A00028E9FE = { 140 | CreatedOnToolsVersion = 11.4.1; 141 | }; 142 | }; 143 | }; 144 | buildConfigurationList = 67BC147A245205A00028E9FE /* Build configuration list for PBXProject "TagWallet" */; 145 | compatibilityVersion = "Xcode 9.3"; 146 | developmentRegion = en; 147 | hasScannedForEncodings = 0; 148 | knownRegions = ( 149 | en, 150 | Base, 151 | ); 152 | mainGroup = 67BC1476245205A00028E9FE; 153 | packageReferences = ( 154 | 67BC149D245207930028E9FE /* XCRemoteSwiftPackageReference "CryptoSwift" */, 155 | ); 156 | productRefGroup = 67BC1480245205A00028E9FE /* Products */; 157 | projectDirPath = ""; 158 | projectRoot = ""; 159 | targets = ( 160 | 67BC147E245205A00028E9FE /* TagWallet */, 161 | ); 162 | }; 163 | /* End PBXProject section */ 164 | 165 | /* Begin PBXResourcesBuildPhase section */ 166 | 67BC147D245205A00028E9FE /* Resources */ = { 167 | isa = PBXResourcesBuildPhase; 168 | buildActionMask = 2147483647; 169 | files = ( 170 | 67BC148F245205A20028E9FE /* LaunchScreen.storyboard in Resources */, 171 | 67BC148C245205A20028E9FE /* Assets.xcassets in Resources */, 172 | 67BC148A245205A00028E9FE /* Main.storyboard in Resources */, 173 | 67CC96952456228800592A27 /* initialTagWallet.json in Resources */, 174 | ); 175 | runOnlyForDeploymentPostprocessing = 0; 176 | }; 177 | /* End PBXResourcesBuildPhase section */ 178 | 179 | /* Begin PBXSourcesBuildPhase section */ 180 | 67BC147B245205A00028E9FE /* Sources */ = { 181 | isa = PBXSourcesBuildPhase; 182 | buildActionMask = 2147483647; 183 | files = ( 184 | 67BC1498245206C70028E9FE /* TagProduct.swift in Sources */, 185 | 67BC14AD24520BB70028E9FE /* MiFareTag.swift in Sources */, 186 | 67BC14A1245208190028E9FE /* TagProductsCollectionViewController.swift in Sources */, 187 | 67BC14AC24520BB70028E9FE /* NTAG215Tag.swift in Sources */, 188 | 67BC14A924520BAB0028E9FE /* TagDump.swift in Sources */, 189 | 67BC14A524520A5E0028E9FE /* TagProductViewController.swift in Sources */, 190 | 67BC14A324520A350028E9FE /* TagProductsCollectionViewController+TagReading.swift in Sources */, 191 | 67BC1483245205A00028E9FE /* AppDelegate.swift in Sources */, 192 | 67BC1485245205A00028E9FE /* SceneDelegate.swift in Sources */, 193 | 67BC149C245206F00028E9FE /* TagEncyption.swift in Sources */, 194 | ); 195 | runOnlyForDeploymentPostprocessing = 0; 196 | }; 197 | /* End PBXSourcesBuildPhase section */ 198 | 199 | /* Begin PBXVariantGroup section */ 200 | 67BC1488245205A00028E9FE /* Main.storyboard */ = { 201 | isa = PBXVariantGroup; 202 | children = ( 203 | 67BC1489245205A00028E9FE /* Base */, 204 | ); 205 | name = Main.storyboard; 206 | sourceTree = ""; 207 | }; 208 | 67BC148D245205A20028E9FE /* LaunchScreen.storyboard */ = { 209 | isa = PBXVariantGroup; 210 | children = ( 211 | 67BC148E245205A20028E9FE /* Base */, 212 | ); 213 | name = LaunchScreen.storyboard; 214 | sourceTree = ""; 215 | }; 216 | /* End PBXVariantGroup section */ 217 | 218 | /* Begin XCBuildConfiguration section */ 219 | 67BC1491245205A20028E9FE /* Debug */ = { 220 | isa = XCBuildConfiguration; 221 | buildSettings = { 222 | ALWAYS_SEARCH_USER_PATHS = NO; 223 | CLANG_ANALYZER_NONNULL = YES; 224 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 225 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; 226 | CLANG_CXX_LIBRARY = "libc++"; 227 | CLANG_ENABLE_MODULES = YES; 228 | CLANG_ENABLE_OBJC_ARC = YES; 229 | CLANG_ENABLE_OBJC_WEAK = YES; 230 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 231 | CLANG_WARN_BOOL_CONVERSION = YES; 232 | CLANG_WARN_COMMA = YES; 233 | CLANG_WARN_CONSTANT_CONVERSION = YES; 234 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 235 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 236 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 237 | CLANG_WARN_EMPTY_BODY = YES; 238 | CLANG_WARN_ENUM_CONVERSION = YES; 239 | CLANG_WARN_INFINITE_RECURSION = YES; 240 | CLANG_WARN_INT_CONVERSION = YES; 241 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 242 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 243 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 244 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 245 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 246 | CLANG_WARN_STRICT_PROTOTYPES = YES; 247 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 248 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 249 | CLANG_WARN_UNREACHABLE_CODE = YES; 250 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 251 | COPY_PHASE_STRIP = NO; 252 | DEBUG_INFORMATION_FORMAT = dwarf; 253 | ENABLE_STRICT_OBJC_MSGSEND = YES; 254 | ENABLE_TESTABILITY = YES; 255 | GCC_C_LANGUAGE_STANDARD = gnu11; 256 | GCC_DYNAMIC_NO_PIC = NO; 257 | GCC_NO_COMMON_BLOCKS = YES; 258 | GCC_OPTIMIZATION_LEVEL = 0; 259 | GCC_PREPROCESSOR_DEFINITIONS = ( 260 | "DEBUG=1", 261 | "$(inherited)", 262 | ); 263 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 264 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 265 | GCC_WARN_UNDECLARED_SELECTOR = YES; 266 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 267 | GCC_WARN_UNUSED_FUNCTION = YES; 268 | GCC_WARN_UNUSED_VARIABLE = YES; 269 | IPHONEOS_DEPLOYMENT_TARGET = 13.4; 270 | MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; 271 | MTL_FAST_MATH = YES; 272 | ONLY_ACTIVE_ARCH = YES; 273 | SDKROOT = iphoneos; 274 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; 275 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 276 | }; 277 | name = Debug; 278 | }; 279 | 67BC1492245205A20028E9FE /* Release */ = { 280 | isa = XCBuildConfiguration; 281 | buildSettings = { 282 | ALWAYS_SEARCH_USER_PATHS = NO; 283 | CLANG_ANALYZER_NONNULL = YES; 284 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 285 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; 286 | CLANG_CXX_LIBRARY = "libc++"; 287 | CLANG_ENABLE_MODULES = YES; 288 | CLANG_ENABLE_OBJC_ARC = YES; 289 | CLANG_ENABLE_OBJC_WEAK = YES; 290 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 291 | CLANG_WARN_BOOL_CONVERSION = YES; 292 | CLANG_WARN_COMMA = YES; 293 | CLANG_WARN_CONSTANT_CONVERSION = YES; 294 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 295 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 296 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 297 | CLANG_WARN_EMPTY_BODY = YES; 298 | CLANG_WARN_ENUM_CONVERSION = YES; 299 | CLANG_WARN_INFINITE_RECURSION = YES; 300 | CLANG_WARN_INT_CONVERSION = YES; 301 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 302 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 303 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 304 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 305 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 306 | CLANG_WARN_STRICT_PROTOTYPES = YES; 307 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 308 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 309 | CLANG_WARN_UNREACHABLE_CODE = YES; 310 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 311 | COPY_PHASE_STRIP = NO; 312 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 313 | ENABLE_NS_ASSERTIONS = NO; 314 | ENABLE_STRICT_OBJC_MSGSEND = YES; 315 | GCC_C_LANGUAGE_STANDARD = gnu11; 316 | GCC_NO_COMMON_BLOCKS = YES; 317 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 318 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 319 | GCC_WARN_UNDECLARED_SELECTOR = YES; 320 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 321 | GCC_WARN_UNUSED_FUNCTION = YES; 322 | GCC_WARN_UNUSED_VARIABLE = YES; 323 | IPHONEOS_DEPLOYMENT_TARGET = 13.4; 324 | MTL_ENABLE_DEBUG_INFO = NO; 325 | MTL_FAST_MATH = YES; 326 | SDKROOT = iphoneos; 327 | SWIFT_COMPILATION_MODE = wholemodule; 328 | SWIFT_OPTIMIZATION_LEVEL = "-O"; 329 | VALIDATE_PRODUCT = YES; 330 | }; 331 | name = Release; 332 | }; 333 | 67BC1494245205A20028E9FE /* Debug */ = { 334 | isa = XCBuildConfiguration; 335 | buildSettings = { 336 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 337 | CODE_SIGN_ENTITLEMENTS = TagWalletUI/TagWallet.entitlements; 338 | CODE_SIGN_STYLE = Automatic; 339 | DEVELOPMENT_TEAM = G68Z6JNXEP; 340 | INFOPLIST_FILE = TagWalletUI/Info.plist; 341 | LD_RUNPATH_SEARCH_PATHS = ( 342 | "$(inherited)", 343 | "@executable_path/Frameworks", 344 | ); 345 | PRODUCT_BUNDLE_IDENTIFIER = kevinbrewster.TagWallet; 346 | PRODUCT_NAME = "$(TARGET_NAME)"; 347 | SWIFT_VERSION = 5.0; 348 | TARGETED_DEVICE_FAMILY = "1,2"; 349 | }; 350 | name = Debug; 351 | }; 352 | 67BC1495245205A20028E9FE /* Release */ = { 353 | isa = XCBuildConfiguration; 354 | buildSettings = { 355 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 356 | CODE_SIGN_ENTITLEMENTS = TagWalletUI/TagWallet.entitlements; 357 | CODE_SIGN_STYLE = Automatic; 358 | DEVELOPMENT_TEAM = G68Z6JNXEP; 359 | INFOPLIST_FILE = TagWalletUI/Info.plist; 360 | LD_RUNPATH_SEARCH_PATHS = ( 361 | "$(inherited)", 362 | "@executable_path/Frameworks", 363 | ); 364 | PRODUCT_BUNDLE_IDENTIFIER = kevinbrewster.TagWallet; 365 | PRODUCT_NAME = "$(TARGET_NAME)"; 366 | SWIFT_VERSION = 5.0; 367 | TARGETED_DEVICE_FAMILY = "1,2"; 368 | }; 369 | name = Release; 370 | }; 371 | /* End XCBuildConfiguration section */ 372 | 373 | /* Begin XCConfigurationList section */ 374 | 67BC147A245205A00028E9FE /* Build configuration list for PBXProject "TagWallet" */ = { 375 | isa = XCConfigurationList; 376 | buildConfigurations = ( 377 | 67BC1491245205A20028E9FE /* Debug */, 378 | 67BC1492245205A20028E9FE /* Release */, 379 | ); 380 | defaultConfigurationIsVisible = 0; 381 | defaultConfigurationName = Release; 382 | }; 383 | 67BC1493245205A20028E9FE /* Build configuration list for PBXNativeTarget "TagWallet" */ = { 384 | isa = XCConfigurationList; 385 | buildConfigurations = ( 386 | 67BC1494245205A20028E9FE /* Debug */, 387 | 67BC1495245205A20028E9FE /* Release */, 388 | ); 389 | defaultConfigurationIsVisible = 0; 390 | defaultConfigurationName = Release; 391 | }; 392 | /* End XCConfigurationList section */ 393 | 394 | /* Begin XCRemoteSwiftPackageReference section */ 395 | 67BC149D245207930028E9FE /* XCRemoteSwiftPackageReference "CryptoSwift" */ = { 396 | isa = XCRemoteSwiftPackageReference; 397 | repositoryURL = "https://github.com/krzyzanowskim/CryptoSwift.git"; 398 | requirement = { 399 | kind = upToNextMajorVersion; 400 | minimumVersion = 1.3.1; 401 | }; 402 | }; 403 | /* End XCRemoteSwiftPackageReference section */ 404 | 405 | /* Begin XCSwiftPackageProductDependency section */ 406 | 67BC149E245207930028E9FE /* CryptoSwift */ = { 407 | isa = XCSwiftPackageProductDependency; 408 | package = 67BC149D245207930028E9FE /* XCRemoteSwiftPackageReference "CryptoSwift" */; 409 | productName = CryptoSwift; 410 | }; 411 | /* End XCSwiftPackageProductDependency section */ 412 | }; 413 | rootObject = 67BC1477245205A00028E9FE /* Project object */; 414 | } 415 | -------------------------------------------------------------------------------- /TagWallet.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /TagWallet.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /TagWallet.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "object": { 3 | "pins": [ 4 | { 5 | "package": "CryptoSwift", 6 | "repositoryURL": "https://github.com/krzyzanowskim/CryptoSwift.git", 7 | "state": { 8 | "branch": null, 9 | "revision": "39f08ac5269361a50c08ce1e2f41989bfc4b1ec8", 10 | "version": "1.3.1" 11 | } 12 | } 13 | ] 14 | }, 15 | "version": 1 16 | } 17 | -------------------------------------------------------------------------------- /TagWallet.xcodeproj/xcuserdata/kevinbrewster.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | TagWallet.xcscheme_^#shared#^_ 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /TagWallet/MiFareTag.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MiFareTag.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/20/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import CoreNFC 11 | import CryptoSwift 12 | 13 | enum NFCMiFareTagError : Swift.Error { 14 | case invalidData 15 | case invalidArgument 16 | case crcError 17 | case invalidAuthentication 18 | case eepromWriteError 19 | case unknownError 20 | } 21 | enum NFCMiFareTagWriteResult { 22 | case success 23 | case failure(Error) 24 | 25 | init(ack: UInt8) { 26 | switch ack { 27 | case 0x0A: 28 | self = .success 29 | case 0x00: 30 | self = .failure(NFCMiFareTagError.invalidArgument) 31 | case 0x01: 32 | self = .failure(NFCMiFareTagError.crcError) 33 | case 0x04: 34 | self = .failure(NFCMiFareTagError.invalidAuthentication) 35 | case 0x05: 36 | self = .failure(NFCMiFareTagError.eepromWriteError) 37 | default: 38 | self = .failure(NFCMiFareTagError.unknownError) 39 | } 40 | } 41 | } 42 | struct NFCMiFareTagVersionInfo { 43 | private let data: Data 44 | var header: UInt8 { return data[0] } 45 | var vendorID: UInt8 { return data[1] } 46 | var productType: UInt8 { return data[2] } 47 | var productSubtype: UInt8 { return data[3] } 48 | var majorProductVersion: UInt8 { return data[4] } 49 | var minorProductVersion: UInt8 { return data[5] } 50 | var storageSize: UInt8 { return data[6] } 51 | var protocolType: UInt8 { return data[7] } 52 | 53 | init?(data: Data) { 54 | guard data.count == 8 else { return nil } 55 | self.data = data 56 | } 57 | } 58 | extension NFCMiFareTag { 59 | func getVersion(completionHandler: @escaping (Result) -> Void) { 60 | sendMiFareCommand(commandPacket: Data([0x60])) { (data, error) in 61 | if let error = error { 62 | completionHandler(.failure(error)) 63 | } else if let versionInfo = NFCMiFareTagVersionInfo(data: data) { 64 | completionHandler(.success(versionInfo)) 65 | } else { 66 | completionHandler(.failure(NFCMiFareTagError.unknownError)) 67 | } 68 | } 69 | } 70 | func fastRead(start: UInt8, end: UInt8, batchSize: UInt8, completionHandler: @escaping (Data, Error?) -> Void) { 71 | // FAST_READ seems to timeout if you try to read too many pages at once, so necessary to read in batches! 72 | _fastRead(start: start, end: end, batchSize: batchSize, accumulatedData: Data(), completionHandler: completionHandler) 73 | } 74 | private func _fastRead(start: UInt8, end: UInt8, batchSize: UInt8, accumulatedData: Data, completionHandler: @escaping (Data, Error?) -> Void) { 75 | // Note: The FAST_READ Command is INCLUSIVE of both the start page end page! 76 | let batchEnd = min(start + batchSize - 1, end) 77 | sendMiFareCommand(commandPacket: Data([0x3A, start, batchEnd])) { (data, error) in 78 | guard error == nil else { 79 | completionHandler(Data(), error) 80 | return 81 | } 82 | let accumulatedData = accumulatedData + data 83 | 84 | if batchEnd < end { 85 | self._fastRead(start: batchEnd + 1, end: end, batchSize: batchSize, accumulatedData: accumulatedData, completionHandler: completionHandler) 86 | } else { 87 | completionHandler(accumulatedData, nil) 88 | } 89 | } 90 | } 91 | func write(page: Int, data: Data, completionHandler: @escaping (NFCMiFareTagWriteResult) -> Void) { 92 | guard page < 255, data.count == 4 else { 93 | completionHandler(NFCMiFareTagWriteResult.failure(NFCMiFareTagError.invalidData)) 94 | return 95 | } 96 | let commandPacket = Data([0xA2, UInt8(page)]) + data 97 | sendMiFareCommand(commandPacket: commandPacket) { (data, error) in 98 | if let error = error { 99 | completionHandler(.failure(error)) 100 | return 101 | } 102 | guard data.count == 1 else { 103 | completionHandler(.failure(NFCMiFareTagError.unknownError)) 104 | return 105 | } 106 | completionHandler(NFCMiFareTagWriteResult(ack: data[0])) 107 | } 108 | } 109 | func write(batch: [(page: Int, data: Data)], completionHandler: @escaping (NFCMiFareTagWriteResult) -> Void) { 110 | if let write = batch.first { 111 | //NSLog("Gonna write page #\(batch.page)") 112 | self.write(page: write.page, data: write.data) { result in 113 | switch result { 114 | case .success: 115 | self.write(batch: Array(batch[1.. String { 131 | /*guard count == 540 else { 132 | return "[[INVALID]]]" 133 | }*/ 134 | let pages = count / 4 135 | var string = "" 136 | for page in 0..= count { break } 140 | string += "\(String(self[(4 * page) + i]))\t" 141 | } 142 | string += "\n" 143 | } 144 | return string 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /TagWallet/NTAG215Tag.swift: -------------------------------------------------------------------------------- 1 | // 2 | // NTAG215Tag.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/21/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import CoreNFC 11 | 12 | class NTAG215Tag { 13 | enum Error : Swift.Error { 14 | case invalidTagType 15 | case unknownError 16 | } 17 | 18 | 19 | let tag: NFCMiFareTag 20 | let versionInfo: NFCMiFareTagVersionInfo 21 | let dump: TagDump 22 | var isLocked: Bool 23 | 24 | 25 | static func initialize(tag: NFCMiFareTag, completionHandler: @escaping (Result) -> Void) { 26 | tag.getVersion() { result in 27 | switch result { 28 | case .failure(let error): 29 | completionHandler(.failure(error)) 30 | case .success(let versionInfo): 31 | guard versionInfo.isNFC215 else { 32 | completionHandler(.failure(Error.invalidTagType)) 33 | return 34 | } 35 | tag.fastRead(start: 0, end: 0x86, batchSize: 0x20) { (data, error) in 36 | if let ntag215Tag = NTAG215Tag(tag: tag, versionInfo: versionInfo, data: data) { 37 | completionHandler(.success(ntag215Tag)) 38 | } else { 39 | completionHandler(.failure(Error.unknownError)) 40 | } 41 | } 42 | } 43 | } 44 | } 45 | 46 | 47 | init?(tag: NFCMiFareTag, versionInfo: NFCMiFareTagVersionInfo, data: Data) { 48 | guard versionInfo.isNFC215 else { 49 | return nil 50 | } 51 | guard let dump = TagDump(data: data) else { 52 | return nil 53 | } 54 | self.tag = tag 55 | self.versionInfo = versionInfo 56 | self.dump = dump 57 | isLocked = data[10] != 0 && data[11] != 0 58 | } 59 | 60 | func patchAndWriteDump(_ originalDump: TagDump, staticKey: TagKey, dataKey: TagKey, completionHandler: @escaping (NFCMiFareTagWriteResult) -> Void) { 61 | do { 62 | let patchedDump = try originalDump.patchedDump(withUID: dump.uid, staticKey: staticKey, dataKey: dataKey) 63 | 64 | var writes = [(Int, Data)]() 65 | 66 | // Main Data 67 | for page in 3..<130 { 68 | let dataStartIndex = page * 4 69 | writes += [(page, patchedDump.data.subdata(in: dataStartIndex.. Void) { 90 | 91 | } 92 | } 93 | 94 | extension NFCMiFareTagVersionInfo { 95 | var isNFC215: Bool { 96 | return productType == 0x04 && storageSize == 0x11 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /TagWallet/TagDump.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TagDump.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/23/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | typealias TagUID = Data // Full Nine-byte UID 12 | 13 | struct TagDump : Codable, Equatable { 14 | enum Error : Swift.Error { 15 | case invalidUID 16 | } 17 | let data: Data 18 | 19 | init?(data: Data) { 20 | guard data.count >= 532 else { 21 | NSLog("TagDump: invalid data of \(data.count)") 22 | return nil } 23 | self.data = data.subdata(in: 0.. Data { 27 | guard uid.count == 9 else { 28 | throw Error.invalidUID 29 | } 30 | var password = Data(repeating: 0, count: 4) 31 | password[0] = 0xAA ^ (uid[1] ^ uid[4]) 32 | password[1] = 0x55 ^ (uid[2] ^ uid[5]) 33 | password[2] = 0xAA ^ (uid[4] ^ uid[6]) 34 | password[3] = 0x55 ^ (uid[5] ^ uid[7]) 35 | return password 36 | } 37 | var headHex: String { 38 | return data[84..<88].map { String(format: "%02hhx", $0) }.joined() 39 | } 40 | var tailHex: String { 41 | return data[88..<92].map { String(format: "%02hhx", $0) }.joined() 42 | } 43 | 44 | 45 | var uid: TagUID { data.subdata(in: 0..<9) } 46 | private var writeCounter: Data { data.subdata(in: 17..<19) } 47 | private var keygenSalt: Data { data.subdata(in: 96..<128) } 48 | 49 | func patchedDump(withUID newUID: TagUID, staticKey: TagKey, dataKey: TagKey) throws -> TagDump { 50 | guard newUID.count == 9 else { 51 | throw Error.invalidUID 52 | } 53 | // Decrypt the data 54 | let decryptDataKeys = dataKey.derivedKey(uid: uid, writeCounter: writeCounter, salt: keygenSalt) 55 | let decryptedData = try decryptDataKeys.decrypt(data.subdata(in: 20..<52) + data.subdata(in: 160..<520)) 56 | 57 | var newData = Data(data) 58 | newData[0..<9] = newUID 59 | newData[20..<52] = decryptedData[0..<32] 60 | newData[160..<520] = decryptedData[32..<392] 61 | 62 | 63 | // Generated tag HMAC 64 | let encryptTagKeys = staticKey.derivedKey(uid: newUID, writeCounter: writeCounter, salt: keygenSalt) 65 | let tagHMAC = encryptTagKeys.hmac(newData.subdata(in: 0..<8) + newData.subdata(in: 84..<128)) 66 | newData[52..<84] = tagHMAC 67 | 68 | // Generated data HMAC 69 | let encryptDataKeys = dataKey.derivedKey(uid: newUID, writeCounter: writeCounter, salt: keygenSalt) 70 | let dataHMAC = encryptDataKeys.hmac(newData.subdata(in: 17..<52) + newData.subdata(in: 160..<520) + newData.subdata(in: 52..<84) + newData.subdata(in: 0..<8) + newData.subdata(in: 84..<128)) 71 | newData[128..<160] = dataHMAC 72 | 73 | // Re-encrypt the data 74 | let encryptedData = try encryptDataKeys.decrypt(decryptedData) 75 | newData[20..<52] = encryptedData[0..<32] 76 | newData[160..<520] = encryptedData[32..<392] 77 | 78 | return TagDump(data: newData)! 79 | } 80 | } 81 | 82 | 83 | -------------------------------------------------------------------------------- /TagWallet/TagEncyption.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TagEncyption.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/23/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import CryptoKit 11 | import CryptoSwift 12 | 13 | struct TagKey : Codable { 14 | private let data: Data // 80 bytes 15 | 16 | var hmacKey: Data { data.subdata(in: 0..<16) } 17 | var typeString: Data { data.subdata(in: 16..<30) } 18 | var magicBytesSize: UInt8 { data[31] } 19 | var magicBytes: Data { data.subdata(in: 32..<(32 + Int(magicBytesSize))) } 20 | var xorPad: Data { data.subdata(in: 48..<80) } 21 | 22 | init?(data: Data) { 23 | guard data.count == 80, data.startIndex == 0 else { 24 | return nil 25 | } 26 | guard data[31] <= 16 else { 27 | return nil // invalid magic byte size 28 | } 29 | self.data = data 30 | 31 | } 32 | func derivedKey(uid: Data, writeCounter: Data, salt: Data) -> DerivedTagKey { 33 | var seed = Data(typeString) 34 | if magicBytesSize < 16 { 35 | seed.append(writeCounter) 36 | } 37 | seed.append(magicBytes) 38 | seed.append(uid[0..<8]) 39 | seed.append(uid[0..<8]) 40 | seed.append(contentsOf: (0..<32).map { salt[$0] ^ xorPad[$0] }) 41 | 42 | let output = hmac(seed: seed, iteration: 0) + hmac(seed: seed, iteration: 1)[0..<16] 43 | 44 | return DerivedTagKey( 45 | aesKey: output.subdata(in: 0..<16), 46 | aesIV: output.subdata(in: 16..<32), 47 | hmacKey: output.subdata(in: 32..<48) 48 | ) 49 | } 50 | private func hmac(seed: Data, iteration: UInt8) -> Data { 51 | var hmac = CryptoKit.HMAC.init(key: SymmetricKey(data: hmacKey)) 52 | let data = Data([(iteration >> 8) & 0x0f, (iteration >> 0) & 0x0f]) + seed 53 | hmac.update(data: data) 54 | return Data(hmac.finalize()) 55 | } 56 | } 57 | 58 | struct DerivedTagKey { 59 | let aesKey: Data 60 | let aesIV: Data 61 | let hmacKey: Data 62 | 63 | func hmac(_ input: Data) -> Data { 64 | var hmac = CryptoKit.HMAC.init(key: SymmetricKey(data: hmacKey)) 65 | hmac.update(data: input) 66 | return Data(hmac.finalize()) 67 | } 68 | func decrypt(_ input: Data) throws -> Data { 69 | let aes = try AES(key: [UInt8](aesKey), blockMode: CTR(iv: [UInt8](aesIV))) 70 | let output = try aes.decrypt([UInt8](input)) 71 | return Data(output) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /TagWalletUI/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/23/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | @UIApplicationMain 12 | class AppDelegate: UIResponder, UIApplicationDelegate { 13 | 14 | 15 | 16 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { 17 | // Override point for customization after application launch. 18 | return true 19 | } 20 | 21 | // MARK: UISceneSession Lifecycle 22 | 23 | func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { 24 | // Called when a new scene session is being created. 25 | // Use this method to select a configuration to create the new scene with. 26 | return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) 27 | } 28 | 29 | func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { 30 | // Called when the user discards a scene session. 31 | // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. 32 | // Use this method to release any resources that were specific to the discarded scenes, as they will not return. 33 | } 34 | 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /TagWalletUI/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "scale" : "2x", 6 | "size" : "20x20" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "scale" : "3x", 11 | "size" : "20x20" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "scale" : "2x", 16 | "size" : "29x29" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "scale" : "3x", 21 | "size" : "29x29" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "scale" : "2x", 26 | "size" : "40x40" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "scale" : "3x", 31 | "size" : "40x40" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "scale" : "2x", 36 | "size" : "60x60" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "scale" : "3x", 41 | "size" : "60x60" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "scale" : "1x", 46 | "size" : "20x20" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "scale" : "2x", 51 | "size" : "20x20" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "scale" : "1x", 56 | "size" : "29x29" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "scale" : "2x", 61 | "size" : "29x29" 62 | }, 63 | { 64 | "idiom" : "ipad", 65 | "scale" : "1x", 66 | "size" : "40x40" 67 | }, 68 | { 69 | "idiom" : "ipad", 70 | "scale" : "2x", 71 | "size" : "40x40" 72 | }, 73 | { 74 | "idiom" : "ipad", 75 | "scale" : "1x", 76 | "size" : "76x76" 77 | }, 78 | { 79 | "idiom" : "ipad", 80 | "scale" : "2x", 81 | "size" : "76x76" 82 | }, 83 | { 84 | "idiom" : "ipad", 85 | "scale" : "2x", 86 | "size" : "83.5x83.5" 87 | }, 88 | { 89 | "idiom" : "ios-marketing", 90 | "scale" : "1x", 91 | "size" : "1024x1024" 92 | } 93 | ], 94 | "info" : { 95 | "author" : "xcode", 96 | "version" : 1 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /TagWalletUI/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /TagWalletUI/Assets.xcassets/binary_file.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "filename" : "binary_file.png", 5 | "idiom" : "universal", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "filename" : "icons8-binary-file-100.png", 10 | "idiom" : "universal", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "scale" : "3x" 16 | } 17 | ], 18 | "info" : { 19 | "author" : "xcode", 20 | "version" : 1 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /TagWalletUI/Assets.xcassets/binary_file.imageset/binary_file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kevinbrewster/TagWallet/021e70a57b5555bad1e17b4237aeaaeb9acf04b5/TagWalletUI/Assets.xcassets/binary_file.imageset/binary_file.png -------------------------------------------------------------------------------- /TagWalletUI/Assets.xcassets/binary_file.imageset/icons8-binary-file-100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kevinbrewster/TagWallet/021e70a57b5555bad1e17b4237aeaaeb9acf04b5/TagWalletUI/Assets.xcassets/binary_file.imageset/icons8-binary-file-100.png -------------------------------------------------------------------------------- /TagWalletUI/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /TagWalletUI/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 239 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | -------------------------------------------------------------------------------- /TagWalletUI/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | $(PRODUCT_BUNDLE_PACKAGE_TYPE) 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | NFCReaderUsageDescription 24 | Scan NFC tags into wallet. 25 | UIApplicationSceneManifest 26 | 27 | UIApplicationSupportsMultipleScenes 28 | 29 | UISceneConfigurations 30 | 31 | UIWindowSceneSessionRoleApplication 32 | 33 | 34 | UISceneConfigurationName 35 | Default Configuration 36 | UISceneDelegateClassName 37 | $(PRODUCT_MODULE_NAME).SceneDelegate 38 | UISceneStoryboardFile 39 | Main 40 | 41 | 42 | 43 | 44 | UILaunchStoryboardName 45 | LaunchScreen 46 | UIMainStoryboardFile 47 | Main 48 | UIRequiredDeviceCapabilities 49 | 50 | armv7 51 | 52 | UISupportedInterfaceOrientations 53 | 54 | UIInterfaceOrientationPortrait 55 | UIInterfaceOrientationLandscapeLeft 56 | UIInterfaceOrientationLandscapeRight 57 | 58 | UISupportedInterfaceOrientations~ipad 59 | 60 | UIInterfaceOrientationPortrait 61 | UIInterfaceOrientationPortraitUpsideDown 62 | UIInterfaceOrientationLandscapeLeft 63 | UIInterfaceOrientationLandscapeRight 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /TagWalletUI/SceneDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SceneDelegate.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/23/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | class SceneDelegate: UIResponder, UIWindowSceneDelegate { 12 | 13 | var window: UIWindow? 14 | 15 | 16 | func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { 17 | // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. 18 | // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. 19 | // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). 20 | guard let _ = (scene as? UIWindowScene) else { return } 21 | } 22 | 23 | func sceneDidDisconnect(_ scene: UIScene) { 24 | // Called as the scene is being released by the system. 25 | // This occurs shortly after the scene enters the background, or when its session is discarded. 26 | // Release any resources associated with this scene that can be re-created the next time the scene connects. 27 | // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). 28 | } 29 | 30 | func sceneDidBecomeActive(_ scene: UIScene) { 31 | // Called when the scene has moved from an inactive state to an active state. 32 | // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. 33 | } 34 | 35 | func sceneWillResignActive(_ scene: UIScene) { 36 | // Called when the scene will move from an active state to an inactive state. 37 | // This may occur due to temporary interruptions (ex. an incoming phone call). 38 | } 39 | 40 | func sceneWillEnterForeground(_ scene: UIScene) { 41 | // Called as the scene transitions from the background to the foreground. 42 | // Use this method to undo the changes made on entering the background. 43 | } 44 | 45 | func sceneDidEnterBackground(_ scene: UIScene) { 46 | // Called as the scene transitions from the foreground to the background. 47 | // Use this method to save data, release shared resources, and store enough scene-specific state information 48 | // to restore the scene back to its current state. 49 | } 50 | 51 | 52 | } 53 | 54 | -------------------------------------------------------------------------------- /TagWalletUI/TagProduct.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TagProduct.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/23/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import UIKit 11 | 12 | struct TagProduct: Codable { 13 | let productSeries: String 14 | let character: String 15 | let gameSeries: String 16 | let imageURL: String 17 | let name: String 18 | let type: String 19 | let head: String 20 | let tail: String 21 | let dumps: [TagDump] 22 | 23 | static let imageDataCache = NSCache() 24 | 25 | func getImage(completion: @escaping (UIImage?) -> Void) { 26 | if let imageData = Self.imageDataCache.object(forKey: imageURL as NSString) { 27 | completion(UIImage(data: imageData as Data)) 28 | } else if let url = URL(string: imageURL) { 29 | URLSession.shared.dataTask(with: url) { data, response, error in 30 | guard let imageData = data else { return } 31 | DispatchQueue.main.async { 32 | Self.imageDataCache.setObject(imageData as NSData, forKey: self.imageURL as NSString) 33 | completion(UIImage(data: imageData)) 34 | } 35 | }.resume() 36 | } 37 | } 38 | } 39 | 40 | struct TagWallet: Codable { 41 | var tagProducts: [TagProduct] 42 | let staticKey: TagKey? 43 | let dataKey: TagKey? 44 | } 45 | -------------------------------------------------------------------------------- /TagWalletUI/TagProductViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TagProductViewController.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/23/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import UIKit 11 | import CryptoKit 12 | import CoreNFC 13 | 14 | class TagProductViewController : UITableViewController { 15 | @IBOutlet weak var imageView: UIImageView! 16 | 17 | var tagProduct: TagProduct! 18 | var staticKey: TagKey? 19 | var dataKey: TagKey? 20 | 21 | lazy var dateFormatter: DateFormatter = { 22 | let dateFormatter = DateFormatter() 23 | dateFormatter.dateStyle = .medium 24 | dateFormatter.timeStyle = .medium 25 | return dateFormatter 26 | }() 27 | 28 | internal var tagReaderSession: NFCTagReaderSession? 29 | var dumpToWrite: TagDump? 30 | var newlyReadDump: TagDump? 31 | weak var tagProductsCollectionViewContoller: TagProductsCollectionViewContoller? 32 | 33 | @IBAction func doneButtonPressed(_ sender: UIBarButtonItem) { 34 | dismiss(animated: true, completion: nil) 35 | } 36 | 37 | override func viewWillAppear(_ animated: Bool) { 38 | super.viewWillAppear(animated) 39 | 40 | title = tagProduct.name 41 | navigationItem.prompt = tagProduct.productSeries 42 | tagProduct.getImage { self.imageView.image = $0 } 43 | 44 | if tagProduct.dumps.count > 0 { 45 | tableView.tableFooterView = nil 46 | } 47 | } 48 | override func viewDidAppear(_ animated: Bool) { 49 | super.viewDidAppear(animated) 50 | 51 | if let newlyReadDump = newlyReadDump, !tagProduct.dumps.contains(newlyReadDump) { 52 | let alert = UIAlertController(title: "Do you want to save this dump?", message: nil, preferredStyle: .alert) 53 | alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in 54 | // todo: Add dump to wallet 55 | })) 56 | alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)) 57 | present(alert, animated: true, completion: nil) 58 | } 59 | } 60 | } 61 | extension TagProductViewController { 62 | override func numberOfSections(in tableView: UITableView) -> Int { 63 | return 1 64 | } 65 | override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 66 | return tagProduct.dumps.count 67 | } 68 | override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 69 | let cell = tableView.dequeueReusableCell(withIdentifier: "Dump", for: indexPath) 70 | let dump = tagProduct.dumps[indexPath.row] 71 | cell.textLabel?.text = "Tag Dump" 72 | cell.detailTextLabel?.text = "\(SHA256.hash(data: dump.data))" 73 | return cell 74 | } 75 | override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 76 | dumpToWrite = nil 77 | 78 | if staticKey != nil && dataKey != nil { 79 | // We have the decryption keys so we can proceed with writing dump to tag 80 | let alert = UIAlertController(title: "Write to blank NTAG215?", message: nil, preferredStyle: .alert) 81 | alert.addAction(UIAlertAction(title: "Write", style: .default, handler: { action in 82 | self.dumpToWrite = self.tagProduct.dumps[indexPath.row] 83 | self.tagReaderSession = NFCTagReaderSession(pollingOption: NFCTagReaderSession.PollingOption.iso14443, delegate: self) 84 | self.tagReaderSession?.alertMessage = "Hold blank NFC215 tag to phone." 85 | self.tagReaderSession?.begin() 86 | self.tableView.deselectRow(at: indexPath, animated: true) 87 | })) 88 | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in 89 | self.tableView.deselectRow(at: indexPath, animated: true) 90 | })) 91 | present(alert, animated: true, completion: nil) 92 | 93 | } else { 94 | let alert = UIAlertController(title: "No decryption keys in wallet!", message: "You cannot write this dump without decryption keys!", preferredStyle: .alert) 95 | alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) 96 | present(alert, animated: true, completion: nil) 97 | } 98 | } 99 | } 100 | extension TagProductViewController { 101 | func writeDump(to ntag215Tag: NTAG215Tag) { 102 | guard let dumpToWrite = dumpToWrite, let staticKey = staticKey, let dataKey = dataKey else { 103 | return 104 | } 105 | ntag215Tag.patchAndWriteDump(dumpToWrite, staticKey: staticKey, dataKey: dataKey) {result in 106 | switch result { 107 | case .success: 108 | self.tagReaderSession?.invalidate() 109 | self.dumpToWrite = nil 110 | 111 | let alert = UIAlertController(title: "Tag successfully written!", message: nil, preferredStyle: .alert) 112 | alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) 113 | DispatchQueue.main.async { 114 | self.present(alert, animated: true, completion: nil) 115 | } 116 | 117 | case .failure(let error): 118 | self.tagReaderSession?.invalidate(errorMessage: error.localizedDescription) 119 | } 120 | } 121 | } 122 | func handleConnectedTag(tag: NFCMiFareTag) { 123 | NTAG215Tag.initialize(tag: tag) { result in 124 | switch result { 125 | case .success(let ntag215Tag): 126 | if ntag215Tag.isLocked { 127 | self.tagReaderSession?.invalidate(errorMessage: "Tag is locked! Can't overwrite!") 128 | } else { 129 | self.writeDump(to: ntag215Tag) 130 | } 131 | case .failure(let error): 132 | self.tagReaderSession?.invalidate(errorMessage: error.localizedDescription) 133 | } 134 | } 135 | } 136 | } 137 | extension TagProductViewController : NFCTagReaderSessionDelegate { 138 | func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) { 139 | NSLog("tagReaderSessionDidBecomeActive") 140 | } 141 | 142 | func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) { 143 | NSLog("NFCTagReaderSession, didInvalidateWithError \(error)") 144 | } 145 | 146 | func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) { 147 | guard case let NFCTag.miFare(tag) = tags.first! else { 148 | tagReaderSession?.invalidate(errorMessage: "Invalid tag type.") 149 | return 150 | } 151 | session.connect(to: tags.first!) { (error: Error?) in 152 | if let error = error { 153 | session.invalidate(errorMessage: error.localizedDescription) 154 | } else { 155 | self.handleConnectedTag(tag: tag) 156 | } 157 | } 158 | } 159 | 160 | } 161 | 162 | -------------------------------------------------------------------------------- /TagWalletUI/TagProductsCollectionViewController+TagReading.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TagProductsCollectionViewController+TagReading.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/23/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import UIKit 11 | import CoreNFC 12 | 13 | extension TagProductsCollectionViewContoller { 14 | @IBAction func startTagReadingSession() { 15 | tagReaderSession = NFCTagReaderSession(pollingOption: NFCTagReaderSession.PollingOption.iso14443, delegate: self) 16 | tagReaderSession?.alertMessage = "Hold tag to back of phone!" 17 | tagReaderSession?.begin() 18 | } 19 | func handleConnectedTag(tag: NFCMiFareTag) { 20 | NTAG215Tag.initialize(tag: tag) { result in 21 | switch result { 22 | case .success(let ntag215Tag): 23 | if let tagProduct = self.tagWallet?.tagProducts.first(where: { $0.head + $0.tail == ntag215Tag.dump.headHex + ntag215Tag.dump.tailHex }) { 24 | self.tagReaderSession?.invalidate() 25 | DispatchQueue.main.async { 26 | self.showTagProduct(tagProduct, newDump: ntag215Tag.dump) 27 | } 28 | } else { 29 | self.unknownProductTag(ntag215Tag: ntag215Tag) 30 | } 31 | case .failure(let error): 32 | self.tagReaderSession?.invalidate(errorMessage: error.localizedDescription) 33 | } 34 | } 35 | } 36 | func unknownProductTag(ntag215Tag: NTAG215Tag) { 37 | let alert = UIAlertController(title: "Unknown NTAG215 Product", message: "What do you want to name it?", preferredStyle: .alert) 38 | alert.addTextField { textField in 39 | textField.placeholder = "Product Name.." 40 | } 41 | alert.addAction(UIAlertAction(title: "Save", style: .default, handler: { action in 42 | let tagProduct = TagProduct.init(productSeries: "", character: "", gameSeries: "", imageURL: "", name: alert.textFields?.first?.text ?? "", type: "", head: ntag215Tag.dump.headHex, tail: ntag215Tag.dump.tailHex, dumps: [ntag215Tag.dump]) 43 | self.tagWallet?.tagProducts += [tagProduct] 44 | self.saveTagWallet() 45 | })) 46 | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) 47 | present(alert, animated: true, completion: nil) 48 | } 49 | } 50 | extension TagProductsCollectionViewContoller : NFCTagReaderSessionDelegate { 51 | func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) { 52 | NSLog("tagReaderSessionDidBecomeActive") 53 | } 54 | 55 | func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) { 56 | NSLog("NFCTagReaderSession, didInvalidateWithError \(error)") 57 | } 58 | 59 | func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) { 60 | guard case let NFCTag.miFare(tag) = tags.first! else { 61 | tagReaderSession?.invalidate(errorMessage: "Invalid tag type.") 62 | return 63 | } 64 | session.connect(to: tags.first!) { (error: Error?) in 65 | if let error = error { 66 | session.invalidate(errorMessage: error.localizedDescription) 67 | } else { 68 | self.handleConnectedTag(tag: tag) 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /TagWalletUI/TagProductsCollectionViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TagProductsCollectionViewController.swift 3 | // TagWallet 4 | // 5 | // Created by Kevin Brewster on 4/23/20. 6 | // Copyright © 2020 Kevin Brewster. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import UIKit 11 | import CoreNFC 12 | import CoreData 13 | 14 | class TagProductsCollectionViewContoller : UIViewController { 15 | @IBOutlet weak var headerView: UIView! 16 | @IBOutlet weak var headerViewHeightConstraint: NSLayoutConstraint! 17 | @IBOutlet weak var collectionView: UICollectionView! 18 | 19 | internal var tagReaderSession: NFCTagReaderSession? 20 | 21 | var tagWallet: TagWallet? 22 | var searchController: UISearchController! 23 | 24 | var productTagType: String? = "Figure" 25 | var filteredTagProductGroups: [(gameSeries: String, tagProducts: [TagProduct])] = [] 26 | 27 | @IBAction func productTagTypeChanged(_ sender: UISegmentedControl) { 28 | switch sender.selectedSegmentIndex { 29 | case 0: productTagType = "Figure" 30 | case 1: productTagType = "Card" 31 | default: productTagType = nil 32 | } 33 | NSLog("TagProduct type changed!") 34 | updateFilteredTagProducts() 35 | } 36 | 37 | var tagWalletURL: URL { 38 | let documentsDirectory: URL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! 39 | return documentsDirectory.appendingPathComponent("tagWallet.json") 40 | } 41 | 42 | override func viewDidLoad() { 43 | super.viewDidLoad() 44 | 45 | setupSearchController() 46 | loadTagWallet() 47 | } 48 | 49 | 50 | func loadTagWallet() { 51 | // Copy the built-in tagWallet.json file from bundle to documents folder if it doesn't exist 52 | if !FileManager.default.fileExists(atPath: tagWalletURL.path), let builtInDataURL = Bundle.main.url(forResource: "initialTagWallet", withExtension: "json") { 53 | do { 54 | try FileManager.default.copyItem(at: builtInDataURL, to: tagWalletURL) 55 | } catch let error { 56 | NSLog("Error copying built in data to tagProducts.json: \(error)") 57 | return 58 | } 59 | } 60 | do { 61 | let data = try Data(contentsOf: tagWalletURL) 62 | tagWallet = try JSONDecoder().decode(TagWallet.self, from: data) 63 | updateFilteredTagProducts() 64 | } catch let error { 65 | NSLog("Error loading tagProducts.json: \(error)") 66 | tagWallet = TagWallet(tagProducts: [], staticKey: nil, dataKey: nil) 67 | return 68 | 69 | } 70 | } 71 | 72 | 73 | func saveTagWallet() { 74 | do { 75 | let tagWalletData = try JSONEncoder().encode(tagWallet) 76 | try tagWalletData.write(to: tagWalletURL) 77 | NSLog("Saved tag wallet to: \(tagWalletURL)") 78 | } catch let error { 79 | NSLog("Error writing tagWallet.json: \(error)") 80 | return 81 | } 82 | } 83 | 84 | func setupSearchController() { 85 | self.definesPresentationContext = true 86 | searchController = UISearchController(searchResultsController: nil) 87 | searchController.definesPresentationContext = false 88 | searchController.hidesNavigationBarDuringPresentation = false 89 | searchController.obscuresBackgroundDuringPresentation = false 90 | searchController.searchResultsUpdater = self 91 | headerView.addSubview(searchController.searchBar) 92 | headerViewHeightConstraint.constant = searchController.searchBar.frame.height 93 | } 94 | 95 | func updateFilteredTagProducts() { 96 | var filteredTagProducts = tagWallet?.tagProducts ?? [] 97 | if let type = productTagType { 98 | filteredTagProducts = filteredTagProducts.filter { $0.type == type } 99 | } 100 | if let search = searchController.searchBar.text?.lowercased(), search != "" { 101 | filteredTagProducts = filteredTagProducts.filter { $0.productSeries.lowercased().contains(search) || $0.gameSeries.lowercased().contains(search) || $0.name.lowercased().contains(search) } 102 | } 103 | filteredTagProductGroups = Dictionary(grouping: filteredTagProducts, by: { $0.productSeries }).map({ $0 }).sorted(by: { (a, b) -> Bool in 104 | a.gameSeries < b.gameSeries 105 | }) 106 | self.collectionView.reloadData() 107 | } 108 | 109 | func showTagProduct(_ tagProduct: TagProduct, newDump: TagDump? = nil) { 110 | guard let navVC = storyboard?.instantiateViewController(identifier: "TagProductNavViewController") as? UINavigationController, 111 | let tagProductVC = navVC.topViewController as? TagProductViewController else { 112 | return 113 | } 114 | tagProductVC.tagProduct = tagProduct 115 | tagProductVC.newlyReadDump = newDump 116 | tagProductVC.tagProductsCollectionViewContoller = self 117 | searchController.searchBar.endEditing(true) 118 | present(navVC, animated: true, completion: nil) 119 | } 120 | } 121 | extension TagProductsCollectionViewContoller : UISearchResultsUpdating { 122 | func updateSearchResults(for searchController: UISearchController) { 123 | updateFilteredTagProducts() 124 | } 125 | } 126 | extension TagProductsCollectionViewContoller : UICollectionViewDelegate, UICollectionViewDataSource { 127 | func numberOfSections(in collectionView: UICollectionView) -> Int { 128 | return filteredTagProductGroups.count 129 | } 130 | func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 131 | guard kind == UICollectionView.elementKindSectionHeader else { 132 | return UICollectionReusableView() 133 | } 134 | 135 | let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! TagProductsHeaderView 136 | header.gameSeriesLabel.text = filteredTagProductGroups[indexPath.section].gameSeries 137 | 138 | return header 139 | } 140 | func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 141 | return filteredTagProductGroups[section].tagProducts.count 142 | } 143 | func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 144 | let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagProduct", for: indexPath) as! TagProductCollectionViewCell 145 | cell.tagProduct = filteredTagProductGroups[indexPath.section].tagProducts[indexPath.row] 146 | return cell 147 | } 148 | func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 149 | showTagProduct(filteredTagProductGroups[indexPath.section].tagProducts[indexPath.row]) 150 | } 151 | 152 | 153 | } 154 | extension TagProductsCollectionViewContoller : UICollectionViewDelegateFlowLayout { 155 | func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 156 | return CGSize(width: 114, height: 190) 157 | } 158 | } 159 | 160 | class TagProductsHeaderView : UICollectionReusableView { 161 | @IBOutlet weak var gameSeriesLabel: UILabel! 162 | } 163 | 164 | class TagProductCollectionViewCell : UICollectionViewCell { 165 | @IBOutlet weak var imageView: UIImageView! 166 | @IBOutlet weak var imageViewHeightContraint: NSLayoutConstraint! 167 | @IBOutlet weak var nameLabel: UILabel! 168 | 169 | var tagProduct: TagProduct! { 170 | didSet { 171 | nameLabel.text = tagProduct.name 172 | tagProduct.getImage { self.imageView.image = $0 } 173 | } 174 | } 175 | 176 | } 177 | -------------------------------------------------------------------------------- /TagWalletUI/TagWallet.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.developer.nfc.readersession.formats 6 | 7 | NDEF 8 | TAG 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /TagWalletUI/initialTagWallet.json: -------------------------------------------------------------------------------- 1 | {"dataKey":{"data":"__SOME_BASE64_ENCODED_STRING_OF_80_BYTES__"},"staticKey":{"data":"__SOME_BASE64_ENCODED_STRING_OF_80_BYTES__"},"tagProducts":[{"tail":"__4_BYTE_HEX__","character":"Test","head":"__4_BYTE_HEX__","gameSeries":"Test","type":"Figure","imageURL":"","name":"Test","productSeries":"Test", "dumps":[{"data":"__SOME_BASE64_ENCODED_STRING_OF_540_BYTES__"}]}]} 2 | --------------------------------------------------------------------------------