Compare commits

...
14 Commits
Author SHA1 Message Date
Michele Balistreri 5b456ea365 avoid NPE on disconnected cards 2024-12-17 14:30:08 +09:00
Michele Balistreri e78f46de10 Fix race condition on connect/disconnect (Android) (#57)
Fix race condition on connect/disconnect (Android)
2024-12-06 09:41:11 +01:00
Michele Balistreri 46dc14cea4 Pairing event (#56)
emit event on new pairing
2024-12-05 01:17:45 +01:00
Michele Balistreri 735bed7f98 Keycard 3.1.0 support (#54)
* full keycard 3.1 support (android)

* handle empty card name

* full keycard 3.1 support (ios)

* send keyCardOnDisconnected on NFC Error 102

* temporarely keep the wallet keys in exported data
2024-12-02 13:25:11 +01:00
Michele Balistreri 26c476b362 implement card verification (ios) 2024-10-15 12:59:30 +02:00
Michele Balistreri c8360eb0e3 implement card verification (android) 2024-10-15 10:20:08 +02:00
Michele Balistreri c5f12414da add ca-related methods 2024-10-15 08:40:09 +02:00
Michele Balistreri 7b3df428ab remove deprecated code 2024-10-15 07:32:18 +02:00
Michele Balistreri 2f9d46b2c7 bump version 2024-10-01 16:20:47 +02:00
Michele Balistreri b14e9f0b9a align android and ios behaviour regarding startNFC/stopNFC 2024-10-01 16:18:58 +02:00
Michele Balistreri 7da38ff5f7 Ident support (#53)
add IDENT support
2024-09-23 11:28:26 +02:00
Michele Balistreri 6de4b0deb0 implement v2 factory reset (#51)
implement v2 factory reset
2024-09-16 10:47:26 +02:00
Michele Balistreri 93dd64754e update sdk (#48)
* update sdk
2023-02-22 12:24:27 +01:00
Michele Balistreri 9c5b897991 Make compatible with newer XCode (#46)
xcode 14 compatibility
2022-09-19 14:51:16 +02:00
11 changed files with 545 additions and 285 deletions
+3 -4
View File
@@ -14,7 +14,7 @@ React Native library to interact with [Keycard](https://keycard.status.im/) usin
### Manual installation
Android is the only platform supported by now.
Both iOS and Android are supported
#### Android
@@ -38,7 +38,6 @@ Android is the only platform supported by now.
Take a look into [docs](./docs/usage.md)
For more usage examples, please refer to https://github.com/status-im/status-react (assuming you can read Clojure)
For more usage examples, please refer to https://github.com/status-im/status-mobile (assuming you can read Clojure)
For Keycard API documention, please look into https://status.im/keycard_api/
For Keycard API documention, please look into https://keycard.tech/docs/
+1 -1
View File
@@ -46,5 +46,5 @@ dependencies {
implementation 'com.facebook.react:react-native:+'
implementation 'org.bouncycastle:bcprov-jdk15on:1.60'
implementation 'org.apache.commons:commons-lang3:3.9'
implementation 'com.github.status-im.status-keycard-java:android:3.0.4'
implementation 'com.github.status-im.status-keycard-java:android:3.1.2'
}
Binary file not shown.
@@ -1,83 +0,0 @@
package im.status.ethereum.keycard;
import android.content.res.AssetManager;
import android.util.Log;
import im.status.keycard.globalplatform.GlobalPlatformCommandSet;
import im.status.keycard.globalplatform.LoadCallback;
import im.status.keycard.io.APDUException;
import im.status.keycard.io.CardChannel;
import org.bouncycastle.util.encoders.Hex;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
public class Installer {
private CardChannel plainChannel;
private AssetManager assets;
private String capPath;
private EventEmitter eventEmitter;
private GlobalPlatformCommandSet cmdSet;
private static final String TAG = "SmartCardInstaller";
public Installer(CardChannel channel, AssetManager assets, String capPath, EventEmitter eventEmitter) {
this.plainChannel = channel;
this.assets = assets;
this.capPath = capPath;
this.eventEmitter = eventEmitter;
}
public void start() throws IOException, APDUException, NoSuchAlgorithmException, InvalidKeySpecException {
Log.i(TAG, "installation started...");
long startTime = System.currentTimeMillis();
eventEmitter.emit("keycardInstallationProgress", 0.05);
Log.i(TAG, "select ISD...");
cmdSet = new GlobalPlatformCommandSet(this.plainChannel);
cmdSet.select().checkOK();
Log.i(TAG, "opening secure channel...");
cmdSet.openSecureChannel();
Log.i(TAG, "deleting old version (if present)...");
cmdSet.deleteKeycardInstancesAndPackage();
eventEmitter.emit("keycardInstallationProgress", 0.1);
Log.i(TAG, "loading package...");
cmdSet.loadKeycardPackage(this.assets.open(this.capPath), new LoadCallback() {
public void blockLoaded(int loadedBlock, int blockCount) {
Log.i(TAG, String.format("load %d/%d...", loadedBlock, blockCount));
eventEmitter.emit("keycardInstallationProgress", 0.1 + (0.6 * loadedBlock / blockCount));
}
});
Log.i(TAG, "installing NDEF applet...");
cmdSet.installNDEFApplet(Hex.decode("0024d40f12616e64726f69642e636f6d3a706b67696d2e7374617475732e657468657265756d")).checkOK();
eventEmitter.emit("keycardInstallationProgress", 0.72);
eventEmitter.emitWithDelay("keycardInstallationProgress", 0.77, 3100);
eventEmitter.emitWithDelay("keycardInstallationProgress", 0.82, 6200);
eventEmitter.emitWithDelay("keycardInstallationProgress", 0.85, 8500);
Log.i(TAG, "installing Keycard applet...");
cmdSet.installKeycardApplet().checkOK();
eventEmitter.removeCallbacksAndMessages();
eventEmitter.emit("keycardInstallationProgress", 0.88);
long duration = System.currentTimeMillis() - startTime;
Log.i(TAG, String.format("\n\ninstallation completed in %d seconds", duration / 1000));
}
}
@@ -15,6 +15,7 @@ import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableArray;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
@@ -24,7 +25,6 @@ import im.status.keycard.io.APDUException;
public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
private static final String TAG = "StatusKeycard";
private static final String CAP_FILENAME = "keycard_v2.2.1.cap";
private SmartCard smartCard;
private final ReactApplicationContext reactContext;
@@ -56,6 +56,17 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
public void onHostDestroy() {
}
// Required for rn built in EventEmitter Calls.
@ReactMethod
public void addListener(String eventName) {
}
@ReactMethod
public void removeListeners(Integer count) {
}
@ReactMethod
public void nfcIsSupported(final Promise promise) {
if (smartCard != null) {
@@ -305,40 +316,12 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
@ReactMethod
public void installApplet(final Promise promise) {
final ReactContext ctx = this.reactContext;
new Thread(new Runnable() {
public void run() {
try {
smartCard.installApplet(ctx.getAssets(), CAP_FILENAME);
promise.resolve(true);
} catch (IOException | APDUException | NoSuchAlgorithmException | InvalidKeySpecException e) {
Log.d(TAG, e.getMessage());
promise.reject(e);
}
}
}).start();
promise.reject("E_KEYCARD", "Not implemented (unused)");
}
@ReactMethod
public void installAppletAndInitCard(final String pin, final Promise promise) {
final ReactContext ctx = this.reactContext;
new Thread(new Runnable() {
public void run() {
try {
SmartCardSecrets s = smartCard.installAppletAndInitCard(pin, ctx.getAssets(), CAP_FILENAME);
WritableMap params = Arguments.createMap();
params.putString("pin", s.getPin());
params.putString("puk", s.getPuk());
params.putString("password", s.getPairingPassword());
promise.resolve(params);
} catch (IOException | APDUException | NoSuchAlgorithmException | InvalidKeySpecException e) {
Log.d(TAG, e.getMessage());
promise.reject(e);
}
}
}).start();
promise.reject("E_KEYCARD", "Not implemented (unused)");
}
@ReactMethod
@@ -432,17 +415,7 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
@ReactMethod
public void delete(final Promise promise) {
new Thread(new Runnable() {
public void run() {
try {
smartCard.delete();
promise.resolve(true);
} catch (IOException | APDUException e) {
Log.d(TAG, e.getMessage());
promise.reject(e);
}
}
}).start();
promise.reject("E_KEYCARD", "Not implemented (unused)");
}
@ReactMethod
@@ -476,11 +449,25 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
}
@ReactMethod
public void unpairAndDelete(final String pin, final Promise promise) {
public void getCardName(final Promise promise) {
new Thread(new Runnable() {
public void run() {
try {
smartCard.unpairAndDelete(pin);
promise.resolve(smartCard.getCardName());
} catch (IOException | APDUException e) {
Log.d(TAG, e.getMessage());
promise.reject(e);
}
}
}).start();
}
@ReactMethod
public void setCardName(final String pin, final String name, final Promise promise) {
new Thread(new Runnable() {
public void run() {
try {
smartCard.setCardName(pin, name);
promise.resolve(true);
} catch (IOException | APDUException e) {
Log.d(TAG, e.getMessage());
@@ -490,17 +477,38 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
}).start();
}
// These three methods below are a nop on Android since NFC is always listening and we have a custom UI. They are needed in iOS to show the NFC dialog
@ReactMethod
public void unpairAndDelete(final String pin, final Promise promise) {
promise.reject("E_KEYCARD", "Not implemented (unused)");
}
@ReactMethod
public void verifyCard(final String challenge, final Promise promise) {
new Thread(new Runnable() {
public void run() {
try {
promise.resolve(smartCard.verifyCard(challenge));
} catch (IOException | APDUException e) {
Log.d(TAG, e.getMessage());
promise.reject(e);
}
}
}).start();
}
@ReactMethod
public void startNFC(String prompt, final Promise promise) {
smartCard.startNFC();
promise.resolve(true);
}
@ReactMethod
public void stopNFC(String error, final Promise promise) {
smartCard.stopNFC();
promise.resolve(true);
}
// Only used on iOS
@ReactMethod
public void setNFCMessage(String message, final Promise promise) {
promise.resolve(true);
@@ -511,4 +519,16 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
smartCard.setPairings(pairings);
promise.resolve(true);
}
@ReactMethod
public void setCertificationAuthorities(ReadableArray caPubKeys, final Promise promise) {
smartCard.setCertificationAuthorities(caPubKeys);
promise.resolve(true);
}
@ReactMethod
public void setOneTimeVerificationSkip(String instanceUID, final Promise promise) {
smartCard.setOneTimeVerificationSkip(instanceUID);
promise.resolve(true);
}
}
@@ -25,6 +25,7 @@ import java.util.HashMap;
import java.util.Iterator;
import im.status.keycard.applet.RecoverableSignature;
import im.status.keycard.applet.Certificate;
import im.status.keycard.globalplatform.GlobalPlatformCommandSet;
import im.status.keycard.io.APDUException;
import im.status.keycard.io.APDUResponse;
@@ -34,6 +35,7 @@ import im.status.keycard.android.NFCCardManager;
import im.status.keycard.applet.ApplicationStatus;
import im.status.keycard.applet.BIP32KeyPair;
import im.status.keycard.applet.Mnemonic;
import im.status.keycard.applet.Metadata;
import im.status.keycard.applet.CashCommandSet;
import im.status.keycard.applet.KeycardCommandSet;
import im.status.keycard.applet.Pairing;
@@ -48,14 +50,19 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
private CardChannel cardChannel;
private EventEmitter eventEmitter;
private static final String TAG = "SmartCard";
private Boolean started = false;
private boolean started = false;
private volatile boolean listening = false;
private HashMap<String, String> pairings;
private String[] caPubKeys;
private String skipVerificationUID;
private final Object lock = new Object();
private static final String MASTER_PATH = "m";
private static final String ROOT_PATH = "m/44'/60'/0'/0";
private static final String WALLET_PATH = "m/44'/60'/0'/0/0";
private static final String WHISPER_PATH = "m/43'/60'/1581'/0'/0";
private static final String ENCRYPTION_PATH = "m/43'/60'/1581'/1'/0";
private static final String TAG_LOST = "Tag was lost.";
private static final int WORDS_LIST_SIZE = 2048;
public SmartCard(ReactContext reactContext) {
@@ -63,6 +70,8 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
this.cardManager.setCardListener(this);
this.eventEmitter = new EventEmitter(reactContext);
this.pairings = new HashMap<>();
this.caPubKeys = new String[0];
this.skipVerificationUID = "";
}
public String getName() {
@@ -101,15 +110,41 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
}
public void startNFC() {
synchronized(lock) {
this.listening = true;
if (this.cardChannel != null) {
eventEmitter.emit("keyCardOnConnected", null);
}
}
}
public void stopNFC() {
synchronized(lock) {
this.listening = false;
}
}
@Override
public void onConnected(final CardChannel channel) {
this.cardChannel = channel;
eventEmitter.emit("keyCardOnConnected", null);
synchronized(lock) {
this.cardChannel = channel;
if (this.listening) {
eventEmitter.emit("keyCardOnConnected", null);
}
}
}
@Override
public void onDisconnected() {
eventEmitter.emit("keyCardOnDisconnected", null);
synchronized(lock) {
this.cardChannel = null;
if (this.listening) {
eventEmitter.emit("keyCardOnDisconnected", null);
}
}
}
@Override
@@ -143,24 +178,16 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
public SmartCardSecrets init(final String userPin) throws IOException, APDUException, NoSuchAlgorithmException, InvalidKeySpecException {
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
KeycardCommandSet cmdSet = commandSet();
cmdSet.select().checkOK();
eventEmitter.emit("keycardInstallationProgress", 0.90);
SmartCardSecrets s = SmartCardSecrets.generate(userPin);
eventEmitter.emit("keycardInstallationProgress", 0.93);
cmdSet.init(s.getPin(), s.getPuk(), s.getPairingPassword()).checkOK();
eventEmitter.emit("keycardInstallationProgress", 1.0);
return s;
}
public String pair(String pairingPassword) throws IOException, APDUException {
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
KeycardCommandSet cmdSet = commandSet();
Log.i(TAG, "Applet selection successful");
// First thing to do is selecting the applet on the card.
@@ -211,8 +238,13 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
cmdSet.autoPair("KeycardDefaultPairing");
Pairing pairing = cmdSet.getPairing();
pairings.put(instanceUID, pairing.toBase64());
cardInfo.putString("new-pairing", pairing.toBase64());
String base64Pairing = pairing.toBase64();
pairings.put(instanceUID, base64Pairing);
cardInfo.putString("new-pairing", base64Pairing);
WritableMap eventBody = Arguments.createMap();
eventBody.putString("pairing", base64Pairing);
eventBody.putString("instanceUID", instanceUID);
eventEmitter.emit("keyCardNewPairing", eventBody);
openSecureChannel(cmdSet);
return true;
@@ -222,8 +254,36 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
}
private boolean verifyAuthenticity(KeycardCommandSet cmdSet, String instanceUID) throws IOException {
if ((this.caPubKeys.length == 0) || instanceUID.equals(this.skipVerificationUID)) {
this.skipVerificationUID = "";
return true;
}
try {
byte[] rawChallenge = SmartCardSecrets.randomBytes(32);
byte[] data = cmdSet.identifyCard(rawChallenge).checkOK().getData();
byte[] caPubKey = Certificate.verifyIdentity(rawChallenge, data);
if (caPubKey == null) {
return false;
}
String caStr = Hex.toHexString(caPubKey);
for (int i = 0; i < this.caPubKeys.length; i++) {
if (caStr.equals(this.caPubKeys[i])) {
return true;
}
}
} catch(APDUException e) {
Log.i(TAG, "verification failed: " + e.getMessage());
}
return false;
}
public WritableMap getApplicationInfo() throws IOException, APDUException {
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
KeycardCommandSet cmdSet = commandSet();
ApplicationInfo info = new ApplicationInfo(cmdSet.select().checkOK().getData());
Log.i(TAG, "Card initialized? " + info.isInitializedCard());
@@ -233,26 +293,39 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
if (info.isInitializedCard()) {
String instanceUID = Hex.toHexString(info.getInstanceUID());
String cardName = getCardNameOrDefault(cmdSet);
cardInfo.putString("card-name", cardName);
Log.i(TAG, "Instance UID: " + instanceUID);
Log.i(TAG, "Card name: " + cardName);
Log.i(TAG, "Key UID: " + Hex.toHexString(info.getKeyUID()));
Log.i(TAG, "Secure channel public key: " + Hex.toHexString(info.getSecureChannelPubKey()));
Log.i(TAG, "Application version: " + info.getAppVersionString());
Log.i(TAG, "Free pairing slots: " + info.getFreePairingSlots());
Boolean isPaired = false;
Boolean isAuthentic = false;
if (!pairings.containsKey(instanceUID)) {
isPaired = tryDefaultPairing(cmdSet, instanceUID, cardInfo);
isAuthentic = verifyAuthenticity(cmdSet, instanceUID);
if (isAuthentic) {
isPaired = tryDefaultPairing(cmdSet, instanceUID, cardInfo);
}
} else {
try {
openSecureChannel(cmdSet);
isPaired = true;
isAuthentic = true;
} catch(APDUException e) {
isPaired = tryDefaultPairing(cmdSet, instanceUID, cardInfo);
isAuthentic = verifyAuthenticity(cmdSet, instanceUID);
if (isAuthentic) {
isPaired = tryDefaultPairing(cmdSet, instanceUID, cardInfo);
}
}
}
cardInfo.putBoolean("authentic?", isAuthentic);
if (isPaired) {
ApplicationStatus status = new ApplicationStatus(cmdSet.getStatus(KeycardCommandSet.GET_STATUS_P1_APPLICATION).checkOK().getData());
@@ -275,8 +348,18 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
return cardInfo;
}
public WritableMap factoryReset() throws IOException, APDUException {
GlobalPlatformCommandSet cmdSet = new GlobalPlatformCommandSet(this.cardChannel);
public WritableMap factoryResetPost() throws IOException, APDUException {
ApplicationInfo info = new ApplicationInfo(commandSet().select().checkOK().getData());
Log.i(TAG, "Selecting the factory reset Keycard applet succeeded");
WritableMap cardInfo = Arguments.createMap();
cardInfo.putBoolean("initialized?", info.isInitializedCard());
return cardInfo;
}
public WritableMap factoryResetFallback() throws IOException, APDUException {
GlobalPlatformCommandSet cmdSet = gpCommandSet();
cmdSet.select().checkOK();
Log.i(TAG, "ISD selected");
@@ -287,15 +370,30 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
Log.i(TAG, "Keycard applet instance deleted");
cmdSet.installKeycardApplet().checkOK();
Log.i(TAG, "Keycard applet instance re-installed");
Log.i(TAG, "Keycard applet instance re-installed");
ApplicationInfo info = new ApplicationInfo(new KeycardCommandSet(this.cardChannel).select().checkOK().getData());
Log.i(TAG, "Selecting the newly installed Keycard applet succeeded");
return factoryResetPost();
}
WritableMap cardInfo = Arguments.createMap();
cardInfo.putBoolean("initialized?", info.isInitializedCard());
public WritableMap factoryReset() throws IOException, APDUException {
KeycardCommandSet cmdSet = commandSet();
APDUResponse resp = cmdSet.select();
return cardInfo;
if (!resp.isOK()) {
return factoryResetFallback();
}
ApplicationInfo info = new ApplicationInfo(resp.getData());
if (!info.hasFactoryResetCapability()) {
return factoryResetFallback();
}
if (!cmdSet.factoryReset().isOK()) {
return factoryResetFallback();
}
return factoryResetPost();
}
public void deriveKey(final String path, final String pin) throws IOException, APDUException {
@@ -350,6 +448,9 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
public WritableMap importKeys(final String pin) throws IOException, APDUException {
KeycardCommandSet cmdSet = authenticatedCommandSet(pin);
ApplicationInfo info = cmdSet.getApplicationInfo();
byte p2 = (info.getAppVersion() < 0x0310) ? KeycardCommandSet.EXPORT_KEY_P2_PUBLIC_ONLY : KeycardCommandSet.EXPORT_KEY_P2_EXTENDED_PUBLIC;
byte[] tlvEncryption = cmdSet.exportKey(ENCRYPTION_PATH, false, false).checkOK().getData();
BIP32KeyPair encryptionKeyPair = BIP32KeyPair.fromTLV(tlvEncryption);
@@ -357,24 +458,27 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
byte[] tlvMaster = cmdSet.exportKey(MASTER_PATH, false, true).checkOK().getData();
BIP32KeyPair masterPair = BIP32KeyPair.fromTLV(tlvMaster);
byte[] tlvRoot = cmdSet.exportKey(ROOT_PATH, false, true).checkOK().getData();
BIP32KeyPair keyPair = BIP32KeyPair.fromTLV(tlvRoot);
byte[] tlvRoot = cmdSet.exportKey(ROOT_PATH, false, p2).checkOK().getData();
BIP32KeyPair rootKeyPair = BIP32KeyPair.fromTLV(tlvRoot);
byte[] tlvWhisper = cmdSet.exportKey(WHISPER_PATH, false, false).checkOK().getData();
BIP32KeyPair whisperKeyPair = BIP32KeyPair.fromTLV(tlvWhisper);
byte[] tlvWallet = cmdSet.exportKey(WALLET_PATH, false, true).checkOK().getData();
BIP32KeyPair walletKeyPair = BIP32KeyPair.fromTLV(tlvWallet);
ApplicationInfo info = cmdSet.getApplicationInfo();
WritableMap data = Arguments.createMap();
data.putString("address", Hex.toHexString(masterPair.toEthereumAddress()));
data.putString("public-key", Hex.toHexString(masterPair.getPublicKey()));
data.putString("wallet-root-address", Hex.toHexString(keyPair.toEthereumAddress()));
data.putString("wallet-root-public-key", Hex.toHexString(keyPair.getPublicKey()));
data.putString("wallet-address", Hex.toHexString(walletKeyPair.toEthereumAddress()));
data.putString("wallet-public-key", Hex.toHexString(walletKeyPair.getPublicKey()));
data.putString("wallet-root-address", Hex.toHexString(rootKeyPair.toEthereumAddress()));
data.putString("wallet-root-public-key", Hex.toHexString(rootKeyPair.getPublicKey()));
if (rootKeyPair.isExtended()) {
data.putString("wallet-root-chain-code", Hex.toHexString(rootKeyPair.getChainCode()));
} //else { (for now we return both keys, because xpub support is not yet available)
byte[] tlvWallet = cmdSet.exportKey(WALLET_PATH, false, true).checkOK().getData();
BIP32KeyPair walletKeyPair = BIP32KeyPair.fromTLV(tlvWallet);
data.putString("wallet-address", Hex.toHexString(walletKeyPair.toEthereumAddress()));
data.putString("wallet-public-key", Hex.toHexString(walletKeyPair.getPublicKey()));
//}
data.putString("whisper-address", Hex.toHexString(whisperKeyPair.toEthereumAddress()));
data.putString("whisper-public-key", Hex.toHexString(whisperKeyPair.getPublicKey()));
data.putString("whisper-private-key", Hex.toHexString(whisperKeyPair.getPrivateKey()));
@@ -387,6 +491,7 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
public WritableMap generateAndLoadKey(final String mnemonic, final String pin) throws IOException, APDUException {
KeycardCommandSet cmdSet = authenticatedCommandSet(pin);
byte p2 = (cmdSet.getApplicationInfo().getAppVersion() < 0x0310) ? KeycardCommandSet.EXPORT_KEY_P2_PUBLIC_ONLY : KeycardCommandSet.EXPORT_KEY_P2_EXTENDED_PUBLIC;
byte[] seed = Mnemonic.toBinarySeed(mnemonic, "");
BIP32KeyPair keyPair = BIP32KeyPair.fromBinarySeed(seed);
@@ -394,7 +499,7 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
cmdSet.loadKey(keyPair).checkOK();
log("keypair loaded to card");
byte[] tlvRoot = cmdSet.exportKey(ROOT_PATH, false, true).checkOK().getData();
byte[] tlvRoot = cmdSet.exportKey(ROOT_PATH, false, p2).checkOK().getData();
Log.i(TAG, "Derived " + ROOT_PATH);
BIP32KeyPair rootKeyPair = BIP32KeyPair.fromTLV(tlvRoot);
@@ -406,41 +511,34 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
Log.i(TAG, "Derived " + ENCRYPTION_PATH);
BIP32KeyPair encryptionKeyPair = BIP32KeyPair.fromTLV(tlvEncryption);
byte[] tlvWallet = cmdSet.exportKey(WALLET_PATH, false, true).checkOK().getData();
Log.i(TAG, "Derived " + WALLET_PATH);
BIP32KeyPair walletKeyPair = BIP32KeyPair.fromTLV(tlvWallet);
ApplicationInfo info = new ApplicationInfo(cmdSet.select().checkOK().getData());
WritableMap data = Arguments.createMap();
data.putString("address", Hex.toHexString(keyPair.toEthereumAddress()));
data.putString("public-key", Hex.toHexString(keyPair.getPublicKey()));
data.putString("wallet-root-address", Hex.toHexString(rootKeyPair.toEthereumAddress()));
data.putString("wallet-root-public-key", Hex.toHexString(rootKeyPair.getPublicKey()));
data.putString("wallet-address", Hex.toHexString(walletKeyPair.toEthereumAddress()));
data.putString("wallet-public-key", Hex.toHexString(walletKeyPair.getPublicKey()));
if (rootKeyPair.isExtended()) {
data.putString("wallet-root-chain-code", Hex.toHexString(rootKeyPair.getChainCode()));
} //else { (see note above)
byte[] tlvWallet = cmdSet.exportKey(WALLET_PATH, false, true).checkOK().getData();
BIP32KeyPair walletKeyPair = BIP32KeyPair.fromTLV(tlvWallet);
data.putString("wallet-address", Hex.toHexString(walletKeyPair.toEthereumAddress()));
data.putString("wallet-public-key", Hex.toHexString(walletKeyPair.getPublicKey()));
//}
data.putString("whisper-address", Hex.toHexString(whisperKeyPair.toEthereumAddress()));
data.putString("whisper-public-key", Hex.toHexString(whisperKeyPair.getPublicKey()));
data.putString("whisper-private-key", Hex.toHexString(whisperKeyPair.getPrivateKey()));
data.putString("encryption-public-key", Hex.toHexString(encryptionKeyPair.getPublicKey()));
ApplicationInfo info = new ApplicationInfo(cmdSet.select().checkOK().getData());
data.putString("instance-uid", Hex.toHexString(info.getInstanceUID()));
data.putString("key-uid", Hex.toHexString(info.getKeyUID()));
return data;
}
public void installApplet(AssetManager assets, String capPath) throws IOException, APDUException, NoSuchAlgorithmException, InvalidKeySpecException {
Installer installer = new Installer(this.cardChannel, assets, capPath, eventEmitter);
installer.start();
}
public SmartCardSecrets installAppletAndInitCard(final String userPin, AssetManager assets, String capPath) throws IOException, APDUException, NoSuchAlgorithmException, InvalidKeySpecException {
Installer installer = new Installer(this.cardChannel, assets, capPath, eventEmitter);
installer.start();
return init(userPin);
}
public int verifyPin(final String pin) throws IOException, APDUException {
KeycardCommandSet cmdSet = authenticatedCommandSet(pin);
return 3;
@@ -483,17 +581,6 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
pairings.remove(instanceUID);
}
public void delete() throws IOException, APDUException {
GlobalPlatformCommandSet cmdSet = new GlobalPlatformCommandSet(this.cardChannel);
cmdSet.select().checkOK();
cmdSet.openSecureChannel();
Log.i(TAG, "secure channel opened");
cmdSet.deleteKeycardInstancesAndPackage();
Log.i(TAG, "instance and package deleted");
}
public void removeKey(final String pin) throws IOException, APDUException {
KeycardCommandSet cmdSet = authenticatedCommandSet(pin);
@@ -517,11 +604,6 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
pairings.remove(instanceUID);
}
public void unpairAndDelete(final String pin) throws IOException, APDUException {
unpair(pin);
delete();
}
public String sign(final String pin, final String message) throws IOException, APDUException {
KeycardCommandSet cmdSet = authenticatedCommandSet(pin);
@@ -580,7 +662,7 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
public String signPinless(final String message) throws IOException, APDUException {
CashCommandSet cmdSet = new CashCommandSet(this.cardChannel);
CashCommandSet cmdSet = cashCommandSet();
cmdSet.select().checkOK();
byte[] hash = Hex.decode(message);
@@ -603,6 +685,33 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
return sig;
}
public String getCardName() throws IOException, APDUException {
KeycardCommandSet cmdSet = commandSet();
cmdSet.select().checkOK();
return getCardNameOrDefault(cmdSet);
}
public void setCardName(final String pin, final String name) throws IOException, APDUException {
KeycardCommandSet cmdSet = authenticatedCommandSet(pin);
Metadata m = new Metadata(name);
cmdSet.storeData(m.toByteArray(), KeycardCommandSet.STORE_DATA_P1_PUBLIC).checkOK();
}
public WritableMap verifyCard(final String challenge) throws IOException, APDUException {
KeycardCommandSet cmdSet = commandSet();
cmdSet.select().checkOK();
byte[] rawChallenge = Hex.decode(challenge);
byte[] data = cmdSet.identifyCard(rawChallenge).checkOK().getData();
byte[] caPubKey = Certificate.verifyIdentity(rawChallenge, data);
WritableMap out = Arguments.createMap();
out.putString("ca-public-key", Hex.toHexString(caPubKey));
out.putString("tlv-data", Hex.toHexString(data));
return out;
}
public void setPairings(ReadableMap newPairings) {
pairings.clear();
Iterator<Map.Entry<String,Object>> i = newPairings.getEntryIterator();
@@ -613,6 +722,18 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
}
public void setCertificationAuthorities(ReadableArray newCAPubKeys) {
this.caPubKeys = new String[newCAPubKeys.size()];
for (int i = 0; i < newCAPubKeys.size(); i++) {
this.caPubKeys[i] = newCAPubKeys.getString(i);
}
}
public void setOneTimeVerificationSkip(String instanceUID) {
this.skipVerificationUID = instanceUID;
}
private KeycardCommandSet authenticatedCommandSet(String pin) throws IOException, APDUException {
KeycardCommandSet cmdSet = securedCommandSet();
cmdSet.verifyPIN(pin).checkOK();
@@ -622,13 +743,54 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
private KeycardCommandSet securedCommandSet() throws IOException, APDUException {
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
KeycardCommandSet cmdSet = commandSet();
cmdSet.select().checkOK();
openSecureChannel(cmdSet);
return cmdSet;
}
private KeycardCommandSet commandSet() throws IOException {
synchronized(lock) {
if (this.cardChannel != null) {
return new KeycardCommandSet(this.cardChannel);
}
}
throw new IOException(TAG_LOST);
}
private CashCommandSet cashCommandSet() throws IOException {
synchronized(lock) {
if (this.cardChannel != null) {
return new CashCommandSet(this.cardChannel);
}
}
throw new IOException(TAG_LOST);
}
private GlobalPlatformCommandSet gpCommandSet() throws IOException {
synchronized(lock) {
if (this.cardChannel != null) {
return new GlobalPlatformCommandSet(this.cardChannel);
}
}
throw new IOException(TAG_LOST);
}
private String getCardNameOrDefault(KeycardCommandSet cmdSet) throws IOException, APDUException {
byte[] data = cmdSet.getData(KeycardCommandSet.STORE_DATA_P1_PUBLIC).checkOK().getData();
try {
Metadata m = Metadata.fromData(data);
return m.getCardName();
} catch(Exception e) {
return "";
}
}
private void openSecureChannel(KeycardCommandSet cmdSet) throws IOException, APDUException {
String instanceUID = Hex.toHexString(cmdSet.getApplicationInfo().getInstanceUID());
String pairingBase64 = pairings.get(instanceUID);
+3 -20
View File
@@ -100,7 +100,7 @@ Keycard.pair(password).then(pairing => console.log(pairing));
```
`pairing` object contains pairing key as base64 string.
You will need pairing key to open secure channel for most keycard operations. More info on pairing https://status.im/keycard_api/sdk_securechannel.html
You will need pairing key to open secure channel for most keycard operations. More info on pairing https://keycard.tech/docs/sdk/securechannel.html
### Generate mnemonic phrase
```javascript
@@ -154,7 +154,7 @@ Keycard.generateAndLoadKey(mnemonic, pairing, pin).then(data => console.log(data
`encryption-public-key` is public key with derivation path `m/43'/60'/1581'/1'/0`
More info about key derivation: https://status.im/keycard_api/sdk_derivation_sign.html
More info about key derivation: https://keycard.tech/docs/sdk/derivation_sign.html
### Get keys from keycard
```javascript
@@ -205,18 +205,7 @@ Recovery ID: `0`
Would produce signature: `d684afb4ec9ce59f2d112a9c9400bd04f5a5b2518b251dba4ad135448f2e75367c2ea6412893d8001ed9c9efeb7c7d37bc11f7dfcf27c4818cf0861da199de1900`
More info about signing: https://status.im/keycard_api/sdk_derivation_sign.html
### Derive key
Changes derivation path:
```javascript
const path = "m/44'/60'/0'/0/0"
const pairing = "AFFdkP01GywuaJRQkGDq+OyPHBE9nECEDDCfXhpfaxlo";
const pin = "123456";
Keycard.deriveKey(path, pairing, pin).then(path => console.log("path changed to " + path));
```
More information on key derivation: https://status.im/keycard_api/sdk_derivation_sign.html
More info about signing: https://keycard.tech/docs/sdk/derivation_sign.html
### Remove key
Removes master key from keycard:
@@ -278,11 +267,5 @@ const newPin = "111111";
Keycard.removeKey(pairing, puk, newPin).then(() => console.log("pin unblocked"));
```
### Install applet
Keycard usually comes with installed applet. But if you have empty keycard without the applet, you can install applet with:
```javascript
Keycard.installApplet().then(() => console.log("applet installed"));
```
### Keycard CLI
You can also interact with keycard (installing and removing applet, getting card info, etc) using [keycard cli](https://github.com/status-im/keycard-cli). You'll need a USB reader for that.
+188 -49
View File
@@ -17,6 +17,8 @@ enum DerivationPath: String {
class SmartCard {
var pairings: [String: String] = [:]
var caPubKeys: [String] = []
var skipVerificationUID: String = ""
func initialize(channel: CardChannel, pin: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let puk = self.randomPUK()
@@ -52,45 +54,64 @@ class SmartCard {
func generateAndLoadKey(channel: CardChannel, mnemonic: String, pin: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = try authenticatedCommandSet(channel: channel, pin: pin)
let exportOption = cmdSet.info!.appVersion < 0x0310 ? KeycardCommandSet.ExportOption.publicOnly : .extendedPublic
let seed = Mnemonic.toBinarySeed(mnemonicPhrase: mnemonic)
let keyPair = BIP32KeyPair(fromSeed: seed)
try cmdSet.loadKey(keyPair: keyPair).checkOK()
os_log("keypair loaded to card");
os_log("keypair loaded to card")
let rootKeyPair = try exportKey(cmdSet: cmdSet, path: .rootPath, makeCurrent: false, publicOnly: true)
let rootKeyPair = try exportKey(cmdSet: cmdSet, path: .rootPath, makeCurrent: false, exportOption: exportOption)
let whisperKeyPair = try exportKey(cmdSet: cmdSet, path: .whisperPath, makeCurrent: false, publicOnly: false)
let encryptionKeyPair = try exportKey(cmdSet: cmdSet, path: .encryptionPath, makeCurrent: false, publicOnly: false)
let walletKeyPair = try exportKey(cmdSet: cmdSet, path: .walletPath, makeCurrent: false, publicOnly: true)
let info = try ApplicationInfo(cmdSet.select().checkOK().data)
resolve([
var keys = [
"address": bytesToHex(keyPair.toEthereumAddress()),
"public-key": bytesToHex(keyPair.publicKey),
"wallet-root-address": bytesToHex(rootKeyPair.toEthereumAddress()),
"wallet-root-public-key": bytesToHex(rootKeyPair.publicKey),
"wallet-address": bytesToHex(walletKeyPair.toEthereumAddress()),
"wallet-public-key": bytesToHex(walletKeyPair.publicKey),
"whisper-address": bytesToHex(whisperKeyPair.toEthereumAddress()),
"whisper-public-key": bytesToHex(whisperKeyPair.publicKey),
"whisper-private-key": bytesToHex(whisperKeyPair.privateKey!),
"encryption-public-key": bytesToHex(encryptionKeyPair.publicKey),
"instance-uid": bytesToHex(info.instanceUID),
"key-uid": bytesToHex(info.keyUID)
])
"encryption-public-key": bytesToHex(encryptionKeyPair.publicKey)
]
if rootKeyPair.isExtended {
keys["wallet-root-chain-code"] = bytesToHex(rootKeyPair.chainCode!)
} //else { (for now we return both keys, because xpub support is not yet available)
let walletKeyPair = try exportKey(cmdSet: cmdSet, path: .walletPath, makeCurrent: false, publicOnly: true)
keys["wallet-address"] = bytesToHex(walletKeyPair.toEthereumAddress())
keys["wallet-public-key"] = bytesToHex(walletKeyPair.publicKey)
//}
let info = try ApplicationInfo(cmdSet.select().checkOK().data)
keys["instance-uid"] = bytesToHex(info.instanceUID)
keys["key-uid"] = bytesToHex(info.keyUID)
resolve(keys)
}
func saveMnemonic(channel: CardChannel, mnemonic: String, pin: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = try authenticatedCommandSet(channel: channel, pin: pin)
let seed = Mnemonic.toBinarySeed(mnemonicPhrase: mnemonic)
try cmdSet.loadKey(seed: seed).checkOK()
os_log("seed loaded to card");
os_log("seed loaded to card")
resolve(true)
}
func factoryReset(channel: CardChannel, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet: GlobalPlatformCommandSet = GlobalPlatformCommandSet(cardChannel: channel);
func factoryResetPost(channel: CardChannel, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let info = try ApplicationInfo(KeycardCommandSet(cardChannel: channel).select().checkOK().data)
os_log("Selecting the factory reset Keycard applet succeeded")
var cardInfo = [String: Any]()
cardInfo["initialized?"] = info.initializedCard
resolve(cardInfo)
}
func factoryResetFallback(channel: CardChannel, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet: GlobalPlatformCommandSet = GlobalPlatformCommandSet(cardChannel: channel)
try cmdSet.select().checkOK()
os_log("ISD selected")
@@ -103,16 +124,68 @@ class SmartCard {
try cmdSet.installKeycardInstance().checkOK()
os_log("Keycard applet instance re-installed")
let info = try ApplicationInfo(KeycardCommandSet(cardChannel: channel).select().checkOK().data)
os_log("Selecting the newly installed Keycard applet succeeded")
var cardInfo = [String: Any]()
cardInfo["initialized?"] = info.initializedCard
resolve(cardInfo)
try factoryResetPost(channel: channel, resolve: resolve, reject: reject)
}
func getApplicationInfo(channel: CardChannel, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
func factoryReset(channel: CardChannel, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = KeycardCommandSet(cardChannel: channel)
var resp = try cmdSet.select()
if (resp.sw != 0x9000) {
try factoryResetFallback(channel: channel, resolve: resolve, reject: reject)
return
}
let info = try ApplicationInfo(resp.data)
if (!info.hasFactoryResetCapability) {
try factoryResetFallback(channel: channel, resolve: resolve, reject: reject)
return
}
resp = try cmdSet.factoryReset()
if (resp.sw != 0x9000) {
try factoryResetFallback(channel: channel, resolve: resolve, reject: reject)
return
}
try factoryResetPost(channel: channel, resolve: resolve, reject: reject)
}
func verifyCard(channel: CardChannel, challenge: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws {
let cmdSet = KeycardCommandSet(cardChannel: channel)
try cmdSet.select().checkOK()
let rawChallenge = hexToBytes(challenge)
let data = try cmdSet.identifyCard(challenge: rawChallenge).checkOK().data
let caPubKey = try Certificate.verifyIdentity(hash: rawChallenge, tlvData: data)
resolve([
"ca-public-key": bytesToHex(caPubKey ?? []),
"tlv-data": bytesToHex(data)
])
}
private func verifyAuthenticity(cmdSet: KeycardCommandSet, instanceUID: String) throws -> Bool {
if (self.caPubKeys.count == 0 || self.skipVerificationUID == instanceUID) {
self.skipVerificationUID = ""
return true
}
let rawChallenge = (0..<32).map({ _ in UInt8.random(in: 0...UInt8.max) })
do {
let data = try cmdSet.identifyCard(challenge: rawChallenge).checkOK().data
let caPubKey = try Certificate.verifyIdentity(hash: rawChallenge, tlvData: data)
if let caPubKeyBytes = caPubKey {
return self.caPubKeys.contains(bytesToHex(caPubKeyBytes))
}
} catch _ as StatusWord {}
return false
}
func getApplicationInfo(channel: CardChannel, eventEmitter: RCTEventEmitter, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = KeycardCommandSet(cardChannel: channel)
let info = try ApplicationInfo(cmdSet.select().checkOK().data)
@@ -122,23 +195,37 @@ class SmartCard {
if (info.initializedCard) {
logAppInfo(info)
let cardName = try cardNameOrDefault(cmdSet: cmdSet)
cardInfo["card-name"] = cardName
var isPaired = false
var isAuthentic = false
let instanceUID = bytesToHex(info.instanceUID)
if let _ = self.pairings[bytesToHex(info.instanceUID)] {
if let _ = self.pairings[instanceUID] {
do {
try openSecureChannel(cmdSet: cmdSet)
isPaired = true
} catch let error as CardError {
isPaired = try tryDefaultPairing(cmdSet: cmdSet, cardInfo: &cardInfo)
} catch let error as StatusWord {
isPaired = try tryDefaultPairing(cmdSet: cmdSet, cardInfo: &cardInfo)
isAuthentic = true
} catch _ as CardError {
isPaired = false
} catch _ as StatusWord {
isPaired = false
}
}
if (!isPaired) {
isAuthentic = try verifyAuthenticity(cmdSet: cmdSet, instanceUID: instanceUID)
if (isAuthentic) {
isPaired = try tryDefaultPairing(cmdSet: cmdSet, eventEmitter: eventEmitter, cardInfo: &cardInfo)
}
} else {
isPaired = try tryDefaultPairing(cmdSet: cmdSet, cardInfo: &cardInfo)
}
cardInfo["authentic?"] = isAuthentic
if (isPaired) {
let status = try ApplicationStatus(cmdSet.getStatus(info: GetStatusP1.application.rawValue).checkOK().data);
let status = try ApplicationStatus(cmdSet.getStatus(info: GetStatusP1.application.rawValue).checkOK().data)
os_log("PIN retry counter: %d", status.pinRetryCount)
os_log("PUK retry counter: %d", status.pukRetryCount)
@@ -161,7 +248,7 @@ class SmartCard {
func deriveKey(channel: CardChannel, path: String, pin: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = try authenticatedCommandSet(channel: channel, pin: pin)
let currentPath = try KeyPath(data: cmdSet.getStatus(info: GetStatusP1.keyPath.rawValue).checkOK().data);
let currentPath = try KeyPath(data: cmdSet.getStatus(info: GetStatusP1.keyPath.rawValue).checkOK().data)
os_log("Current key path: %@", currentPath.description)
if (currentPath.description != path) {
@@ -180,36 +267,43 @@ class SmartCard {
func exportKeyWithPath(channel: CardChannel, pin: String, path: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = try authenticatedCommandSet(channel: channel, pin: pin)
let key = try BIP32KeyPair(fromTLV: cmdSet.exportKey(path: path, makeCurrent: false, publicOnly: true).checkOK().data).publicKey;
let key = try BIP32KeyPair(fromTLV: cmdSet.exportKey(path: path, makeCurrent: false, publicOnly: true).checkOK().data).publicKey
resolve(bytesToHex(key))
}
func importKeys(channel: CardChannel, pin: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = try authenticatedCommandSet(channel: channel, pin: pin)
let info = cmdSet.info!
let exportOption = info.appVersion < 0x0310 ? KeycardCommandSet.ExportOption.publicOnly : .extendedPublic
let encryptionKeyPair = try exportKey(cmdSet: cmdSet, path: .encryptionPath, makeCurrent: false, publicOnly: false)
let masterPair = try exportKey(cmdSet: cmdSet, path: .masterPath, makeCurrent: false, publicOnly: true)
let rootKeyPair = try exportKey(cmdSet: cmdSet, path: .rootPath, makeCurrent: false, publicOnly: true)
let rootKeyPair = try exportKey(cmdSet: cmdSet, path: .rootPath, makeCurrent: false, exportOption: exportOption)
let whisperKeyPair = try exportKey(cmdSet: cmdSet, path: .whisperPath, makeCurrent: false, publicOnly: false)
let walletKeyPair = try exportKey(cmdSet: cmdSet, path: .walletPath, makeCurrent: false, publicOnly: true)
let info = cmdSet.info!
resolve([
var keys = [
"address": bytesToHex(masterPair.toEthereumAddress()),
"public-key": bytesToHex(masterPair.publicKey),
"wallet-root-address": bytesToHex(rootKeyPair.toEthereumAddress()),
"wallet-root-public-key": bytesToHex(rootKeyPair.publicKey),
"wallet-address": bytesToHex(walletKeyPair.toEthereumAddress()),
"wallet-public-key": bytesToHex(walletKeyPair.publicKey),
"whisper-address": bytesToHex(whisperKeyPair.toEthereumAddress()),
"whisper-public-key": bytesToHex(whisperKeyPair.publicKey),
"whisper-private-key": bytesToHex(whisperKeyPair.privateKey!),
"encryption-public-key": bytesToHex(encryptionKeyPair.publicKey),
"instance-uid": bytesToHex(info.instanceUID),
"key-uid": bytesToHex(info.keyUID)
])
]
if rootKeyPair.isExtended {
keys["wallet-root-chain-code"] = bytesToHex(rootKeyPair.chainCode!)
} //else { (see note above)
let walletKeyPair = try exportKey(cmdSet: cmdSet, path: .walletPath, makeCurrent: false, publicOnly: true)
keys["wallet-address"] = bytesToHex(walletKeyPair.toEthereumAddress())
keys["wallet-public-key"] = bytesToHex(walletKeyPair.publicKey)
//}
resolve(keys)
}
func getKeys(channel: CardChannel, pin: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
@@ -240,7 +334,7 @@ class SmartCard {
let cmdSet = try authenticatedCommandSet(channel: channel, pin: pin)
let sig = try processSignature(message) {
if (cmdSet.info!.appVersion < 0x0202) {
let currentPath = try KeyPath(data: cmdSet.getStatus(info: GetStatusP1.keyPath.rawValue).checkOK().data);
let currentPath = try KeyPath(data: cmdSet.getStatus(info: GetStatusP1.keyPath.rawValue).checkOK().data)
if (currentPath.description != path) {
try cmdSet.deriveKey(path: path).checkOK()
@@ -329,6 +423,19 @@ class SmartCard {
resolve(true)
}
func getCardName(channel: CardChannel, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = KeycardCommandSet(cardChannel: channel)
try cmdSet.select().checkOK()
resolve(try cardNameOrDefault(cmdSet: cmdSet))
}
func setCardName(channel: CardChannel, pin: String, name: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = try authenticatedCommandSet(channel: channel, pin: pin)
let m = Metadata(name)
try cmdSet.storeData(data: m.serialize(), type: Keycard.StoreDataP1.publicData.rawValue).checkOK()
resolve(true)
}
func randomPUK() -> String {
return String(format: "%012ld", Int64.random(in: 0..<999999999999))
@@ -341,10 +448,27 @@ class SmartCard {
}
func exportKey(cmdSet: KeycardCommandSet, path: DerivationPath, makeCurrent: Bool, publicOnly: Bool) throws -> BIP32KeyPair {
let tlvRoot = try cmdSet.exportKey(path: path.rawValue, makeCurrent: makeCurrent, publicOnly: publicOnly).checkOK().data
let option = publicOnly ? KeycardCommandSet.ExportOption.publicOnly : KeycardCommandSet.ExportOption.privateAndPublic
return try exportKey(cmdSet: cmdSet, path: path, makeCurrent: makeCurrent, exportOption: option)
}
func exportKey(cmdSet: KeycardCommandSet, path: DerivationPath, makeCurrent: Bool, exportOption: KeycardCommandSet.ExportOption) throws -> BIP32KeyPair {
let tlvRoot = try cmdSet.exportKey(path: path.rawValue, makeCurrent: makeCurrent, exportOption: exportOption).checkOK().data
os_log("Derived %@", path.rawValue)
return try BIP32KeyPair(fromTLV: tlvRoot)
}
func cardNameOrDefault(cmdSet: KeycardCommandSet) throws -> String {
let data = try cmdSet.getData(type: Keycard.StoreDataP1.publicData.rawValue).checkOK().data
if data.count > 0 {
do {
return try Metadata.fromData(data).cardName
} catch _ {}
}
return ""
}
func setPairings(newPairings: NSDictionary, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
self.pairings.removeAll()
@@ -355,12 +479,26 @@ class SmartCard {
resolve(true)
}
func setCertificationAuthorities(newCAPubKeys: NSArray, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
self.caPubKeys.removeAll()
for caPubKey in (newCAPubKeys as! [String]) {
self.caPubKeys.append(caPubKey)
}
resolve(true)
}
func setOneTimeVerificationSkip(instanceUID: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
self.skipVerificationUID = instanceUID
resolve(true)
}
func authenticatedCommandSet(channel: CardChannel, pin: String) throws -> KeycardCommandSet {
let cmdSet = try securedCommandSet(channel: channel)
try cmdSet.verifyPIN(pin: pin).checkAuthOK()
os_log("pin verified")
return cmdSet;
return cmdSet
}
func securedCommandSet(channel: CardChannel) throws -> KeycardCommandSet {
@@ -371,19 +509,20 @@ class SmartCard {
return cmdSet
}
func tryDefaultPairing(cmdSet: KeycardCommandSet, cardInfo: inout [String: Any]) throws -> Bool {
func tryDefaultPairing(cmdSet: KeycardCommandSet, eventEmitter: RCTEventEmitter, cardInfo: inout [String: Any]) throws -> Bool {
do {
try cmdSet.autoPair(password: "KeycardDefaultPairing")
let pairing = Data(cmdSet.pairing!.bytes).base64EncodedString()
self.pairings[bytesToHex(cmdSet.info!.instanceUID)] = pairing
let instanceUID = bytesToHex(cmdSet.info!.instanceUID)
self.pairings[instanceUID] = pairing
cardInfo["new-pairing"] = pairing
eventEmitter.sendEvent(withName: "keyCardNewPairing", body: ["pairing": pairing, "instanceUID": instanceUID])
try openSecureChannel(cmdSet: cmdSet)
return true
} catch let error as CardError {
os_log("autoOpenSecureChannel failed: %@", String(describing: error));
os_log("autoOpenSecureChannel failed: %@", String(describing: error))
} catch let error as StatusWord {
os_log("autoOpenSecureChannel failed: %@", String(describing: error));
os_log("autoOpenSecureChannel failed: %@", String(describing: error))
}
return false
+5
View File
@@ -13,6 +13,7 @@ RCT_EXTERN_METHOD(generateAndLoadKey:(NSString *)mnemonic pin:(NSString *)pin re
RCT_EXTERN_METHOD(saveMnemonic:(NSString *)mnemonic pin:(NSString *)pin resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(getApplicationInfo:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(factoryReset:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(verifyCard:(NSString *)challenge resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(deriveKey:(NSString *)path pin:(NSString *)pin resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(exportKey:(NSString *)pin resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(exportKeyWithPath:(NSString *)pin path:(NSString *)path resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
@@ -32,10 +33,14 @@ RCT_EXTERN_METHOD(unpair:(NSString *)pin resolve:(RCTPromiseResolveBlock)resolve
RCT_EXTERN_METHOD(delete:(RCTPromiseResolveBlock)resolve reject: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(removeKey:(NSString *)pin resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(removeKeyWithUnpair:(NSString *)pin resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(getCardName:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(setCardName:(NSString *)pin name:(NSString *)name resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(unpairAndDelete:(NSString *)pin resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(startNFC:(NSString *)prompt resolve:(RCTPromiseResolveBlock)resolve reject: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(stopNFC:(NSString *)err resolve:(RCTPromiseResolveBlock)resolve reject: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(setNFCMessage:(NSString *)message resolve:(RCTPromiseResolveBlock)resolve reject: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(setPairings:(NSDictionary *)pairings resolve:(RCTPromiseResolveBlock)resolve reject: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(setCertificationAuthorities:(NSArray *)caPubKeys resolve:(RCTPromiseResolveBlock)resolve reject: (RCTPromiseRejectBlock)reject)
RCT_EXTERN_METHOD(setOneTimeVerificationSkip:(NSString *)instanceUID resolve:(RCTPromiseResolveBlock)resolve reject: (RCTPromiseRejectBlock)reject)
@end
+38 -3
View File
@@ -9,8 +9,18 @@ class StatusKeycard: RCTEventEmitter {
var cardChannel: CardChannel? = nil
var nfcStartPrompt: String = "Hold your iPhone near a Status Keycard."
private var _keycardController: Any? = nil
@available(iOS 13.0, *)
private(set) lazy var keycardController: KeycardController? = nil
private var keycardController: KeycardController? {
get {
return _keycardController as? KeycardController
}
set(kc) {
_keycardController = kc
}
}
@objc
func nfcIsSupported(_ resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
@@ -62,10 +72,15 @@ class StatusKeycard: RCTEventEmitter {
func factoryReset(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
keycardInvokation(reject) { [unowned self] channel in try self.smartCard.factoryReset(channel: channel, resolve: resolve, reject: reject) }
}
@objc
func verifyCard(_ challenge: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
keycardInvokation(reject) { [unowned self] channel in try self.smartCard.verifyCard(channel: channel, challenge: challenge, resolve: resolve, reject: reject) }
}
@objc
func getApplicationInfo(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
keycardInvokation(reject) { [unowned self] channel in try self.smartCard.getApplicationInfo(channel: channel, resolve: resolve, reject: reject) }
keycardInvokation(reject) { [unowned self] channel in try self.smartCard.getApplicationInfo(channel: channel, eventEmitter: self, resolve: resolve, reject: reject) }
}
@objc
@@ -163,6 +178,16 @@ class StatusKeycard: RCTEventEmitter {
keycardInvokation(reject) { [unowned self] channel in try self.smartCard.removeKeyWithUnpair(channel: channel, pin: pin, resolve: resolve, reject: reject) }
}
@objc
func getCardName(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
keycardInvokation(reject) { [unowned self] channel in try self.smartCard.getCardName(channel: channel, resolve: resolve, reject: reject) }
}
@objc
func setCardName(_ pin: String, name: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
keycardInvokation(reject) { [unowned self] channel in try self.smartCard.setCardName(channel: channel, pin: pin, name: name, resolve: resolve, reject: reject) }
}
@objc
func unpairAndDelete(_ pin: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
reject("E_KEYCARD", "Not implemented (unused)", nil)
@@ -173,6 +198,16 @@ class StatusKeycard: RCTEventEmitter {
self.smartCard.setPairings(newPairings: pairings, resolve: resolve, reject: reject)
}
@objc
func setCertificationAuthorities(_ caPubKeys: NSArray, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
self.smartCard.setCertificationAuthorities(newCAPubKeys: caPubKeys, resolve: resolve, reject: reject)
}
@objc
func setOneTimeVerificationSkip(_ instanceUID: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
self.smartCard.setOneTimeVerificationSkip(instanceUID: instanceUID, resolve: resolve, reject: reject)
}
@objc
func startNFC(_ prompt: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
if #available(iOS 13.0, *) {
@@ -262,7 +297,7 @@ class StatusKeycard: RCTEventEmitter {
if type(of: error) is NSError.Type {
let nsError = error as NSError
errMsg = "\(nsError.domain):\(nsError.code)"
if nsError.code == 100 && nsError.domain == "NFCError" {
if (nsError.code == 100 || nsError.code == 102) && nsError.domain == "NFCError" {
self.sendEvent(withName: "keyCardOnDisconnected", body: nil)
self.keycardController?.restartPolling()
self.keycardController?.setAlert(self.nfcStartPrompt)
+3 -3
View File
@@ -1,12 +1,12 @@
{
"name": "react-native-status-keycard",
"homepage": "https://keycard.status.im/",
"version": "2.5.37",
"homepage": "https://keycard.tech/",
"version": "2.6.2",
"description": "React Native library to interact with Status Keycard using NFC connection",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Dmitry Novotochinov",
"author": "Michele Balistreri",
"license": "MPL 2.0"
}