Compare commits

..
8 Commits
Author SHA1 Message Date
Michele Balistreri 4d77e475af bump version 2024-09-23 11:27:28 +02:00
Michele Balistreri cb6eb0a9c6 add missing empty emitter methods 2024-09-23 10:50:43 +02:00
Michele Balistreri 3953d66cbc add try statements 2024-09-19 10:16:07 +02:00
Michele Balistreri f2d5c2ca53 fix compilation 2024-09-19 10:09:05 +02:00
Michele Balistreri fe748a8dcd add verifyCard for iOS 2024-09-19 09:49:45 +02:00
Michele Balistreri 36887aeb86 typo 2024-09-16 13:38:06 +02:00
Michele Balistreri 8698594eff typo 2024-09-16 13:32:54 +02:00
Michele Balistreri a360897369 add verifyCard command (android) 2024-09-16 13:31:33 +02:00
10 changed files with 273 additions and 410 deletions
+4 -3
View File
@@ -14,7 +14,7 @@ React Native library to interact with [Keycard](https://keycard.status.im/) usin
### Manual installation
Both iOS and Android are supported
Android is the only platform supported by now.
#### Android
@@ -38,6 +38,7 @@ Both iOS and Android are supported
Take a look into [docs](./docs/usage.md)
For more usage examples, please refer to https://github.com/status-im/status-mobile (assuming you can read Clojure)
For more usage examples, please refer to https://github.com/status-im/status-react (assuming you can read Clojure)
For Keycard API documention, please look into https://keycard.tech/docs/
For Keycard API documention, please look into https://status.im/keycard_api/
Binary file not shown.
@@ -0,0 +1,83 @@
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,7 +15,6 @@ 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;
@@ -25,6 +24,7 @@ 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;
@@ -316,12 +316,40 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
@ReactMethod
public void installApplet(final Promise promise) {
promise.reject("E_KEYCARD", "Not implemented (unused)");
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();
}
@ReactMethod
public void installAppletAndInitCard(final String pin, final Promise promise) {
promise.reject("E_KEYCARD", "Not implemented (unused)");
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();
}
@ReactMethod
@@ -415,7 +443,17 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
@ReactMethod
public void delete(final Promise promise) {
promise.reject("E_KEYCARD", "Not implemented (unused)");
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();
}
@ReactMethod
@@ -449,25 +487,11 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
}
@ReactMethod
public void getCardName(final Promise promise) {
public void unpairAndDelete(final String pin, final Promise promise) {
new Thread(new Runnable() {
public void run() {
try {
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);
smartCard.unpairAndDelete(pin);
promise.resolve(true);
} catch (IOException | APDUException e) {
Log.d(TAG, e.getMessage());
@@ -477,11 +501,6 @@ public class RNStatusKeycardModule extends ReactContextBaseJavaModule implements
}).start();
}
@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() {
@@ -496,19 +515,17 @@ 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 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);
@@ -519,16 +536,4 @@ 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);
}
}
@@ -35,7 +35,6 @@ 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;
@@ -50,19 +49,14 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
private CardChannel cardChannel;
private EventEmitter eventEmitter;
private static final String TAG = "SmartCard";
private boolean started = false;
private volatile boolean listening = false;
private Boolean started = 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) {
@@ -70,8 +64,6 @@ 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() {
@@ -110,41 +102,15 @@ 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) {
synchronized(lock) {
this.cardChannel = channel;
if (this.listening) {
eventEmitter.emit("keyCardOnConnected", null);
}
}
this.cardChannel = channel;
eventEmitter.emit("keyCardOnConnected", null);
}
@Override
public void onDisconnected() {
synchronized(lock) {
this.cardChannel = null;
if (this.listening) {
eventEmitter.emit("keyCardOnDisconnected", null);
}
}
eventEmitter.emit("keyCardOnDisconnected", null);
}
@Override
@@ -178,16 +144,24 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
public SmartCardSecrets init(final String userPin) throws IOException, APDUException, NoSuchAlgorithmException, InvalidKeySpecException {
KeycardCommandSet cmdSet = commandSet();
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
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 = commandSet();
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
Log.i(TAG, "Applet selection successful");
// First thing to do is selecting the applet on the card.
@@ -238,13 +212,8 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
cmdSet.autoPair("KeycardDefaultPairing");
Pairing pairing = cmdSet.getPairing();
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);
pairings.put(instanceUID, pairing.toBase64());
cardInfo.putString("new-pairing", pairing.toBase64());
openSecureChannel(cmdSet);
return true;
@@ -254,36 +223,8 @@ 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 = commandSet();
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
ApplicationInfo info = new ApplicationInfo(cmdSet.select().checkOK().getData());
Log.i(TAG, "Card initialized? " + info.isInitializedCard());
@@ -293,39 +234,26 @@ 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)) {
isAuthentic = verifyAuthenticity(cmdSet, instanceUID);
if (isAuthentic) {
isPaired = tryDefaultPairing(cmdSet, instanceUID, cardInfo);
}
isPaired = tryDefaultPairing(cmdSet, instanceUID, cardInfo);
} else {
try {
openSecureChannel(cmdSet);
isPaired = true;
isAuthentic = true;
} catch(APDUException e) {
isAuthentic = verifyAuthenticity(cmdSet, instanceUID);
if (isAuthentic) {
isPaired = tryDefaultPairing(cmdSet, instanceUID, cardInfo);
}
isPaired = tryDefaultPairing(cmdSet, instanceUID, cardInfo);
}
}
cardInfo.putBoolean("authentic?", isAuthentic);
if (isPaired) {
ApplicationStatus status = new ApplicationStatus(cmdSet.getStatus(KeycardCommandSet.GET_STATUS_P1_APPLICATION).checkOK().getData());
@@ -349,7 +277,7 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
public WritableMap factoryResetPost() throws IOException, APDUException {
ApplicationInfo info = new ApplicationInfo(commandSet().select().checkOK().getData());
ApplicationInfo info = new ApplicationInfo(new KeycardCommandSet(this.cardChannel).select().checkOK().getData());
Log.i(TAG, "Selecting the factory reset Keycard applet succeeded");
WritableMap cardInfo = Arguments.createMap();
@@ -359,7 +287,7 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
public WritableMap factoryResetFallback() throws IOException, APDUException {
GlobalPlatformCommandSet cmdSet = gpCommandSet();
GlobalPlatformCommandSet cmdSet = new GlobalPlatformCommandSet(this.cardChannel);
cmdSet.select().checkOK();
Log.i(TAG, "ISD selected");
@@ -376,7 +304,7 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
public WritableMap factoryReset() throws IOException, APDUException {
KeycardCommandSet cmdSet = commandSet();
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
APDUResponse resp = cmdSet.select();
if (!resp.isOK()) {
@@ -448,9 +376,6 @@ 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);
@@ -458,27 +383,24 @@ 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, p2).checkOK().getData();
BIP32KeyPair rootKeyPair = BIP32KeyPair.fromTLV(tlvRoot);
byte[] tlvRoot = cmdSet.exportKey(ROOT_PATH, false, true).checkOK().getData();
BIP32KeyPair keyPair = 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(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("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("whisper-address", Hex.toHexString(whisperKeyPair.toEthereumAddress()));
data.putString("whisper-public-key", Hex.toHexString(whisperKeyPair.getPublicKey()));
data.putString("whisper-private-key", Hex.toHexString(whisperKeyPair.getPrivateKey()));
@@ -491,7 +413,6 @@ 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);
@@ -499,7 +420,7 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
cmdSet.loadKey(keyPair).checkOK();
log("keypair loaded to card");
byte[] tlvRoot = cmdSet.exportKey(ROOT_PATH, false, p2).checkOK().getData();
byte[] tlvRoot = cmdSet.exportKey(ROOT_PATH, false, true).checkOK().getData();
Log.i(TAG, "Derived " + ROOT_PATH);
BIP32KeyPair rootKeyPair = BIP32KeyPair.fromTLV(tlvRoot);
@@ -511,34 +432,41 @@ 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()));
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("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;
@@ -581,6 +509,17 @@ 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);
@@ -604,6 +543,11 @@ 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);
@@ -662,7 +606,7 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
public String signPinless(final String message) throws IOException, APDUException {
CashCommandSet cmdSet = cashCommandSet();
CashCommandSet cmdSet = new CashCommandSet(this.cardChannel);
cmdSet.select().checkOK();
byte[] hash = Hex.decode(message);
@@ -685,21 +629,8 @@ 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();
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
cmdSet.select().checkOK();
byte[] rawChallenge = Hex.decode(challenge);
byte[] data = cmdSet.identifyCard(rawChallenge).checkOK().getData();
@@ -722,18 +653,6 @@ 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();
@@ -743,54 +662,13 @@ public class SmartCard extends BroadcastReceiver implements CardListener {
}
private KeycardCommandSet securedCommandSet() throws IOException, APDUException {
KeycardCommandSet cmdSet = commandSet();
KeycardCommandSet cmdSet = new KeycardCommandSet(this.cardChannel);
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);
+20 -3
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://keycard.tech/docs/sdk/securechannel.html
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
### 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://keycard.tech/docs/sdk/derivation_sign.html
More info about key derivation: https://status.im/keycard_api/sdk_derivation_sign.html
### Get keys from keycard
```javascript
@@ -205,7 +205,18 @@ Recovery ID: `0`
Would produce signature: `d684afb4ec9ce59f2d112a9c9400bd04f5a5b2518b251dba4ad135448f2e75367c2ea6412893d8001ed9c9efeb7c7d37bc11f7dfcf27c4818cf0861da199de1900`
More info about signing: https://keycard.tech/docs/sdk/derivation_sign.html
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
### Remove key
Removes master key from keycard:
@@ -267,5 +278,11 @@ 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.
+43 -140
View File
@@ -17,8 +17,6 @@ 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()
@@ -54,49 +52,40 @@ 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, exportOption: exportOption)
let rootKeyPair = try exportKey(cmdSet: cmdSet, path: .rootPath, makeCurrent: false, publicOnly: true)
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)
var keys = [
let info = try ApplicationInfo(cmdSet.select().checkOK().data)
resolve([
"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)
]
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)
"encryption-public-key": bytesToHex(encryptionKeyPair.publicKey),
"instance-uid": bytesToHex(info.instanceUID),
"key-uid": bytesToHex(info.keyUID)
])
}
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)
}
@@ -111,7 +100,7 @@ class SmartCard {
}
func factoryResetFallback(channel: CardChannel, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet: GlobalPlatformCommandSet = GlobalPlatformCommandSet(cardChannel: channel)
let cmdSet: GlobalPlatformCommandSet = GlobalPlatformCommandSet(cardChannel: channel);
try cmdSet.select().checkOK()
os_log("ISD selected")
@@ -155,9 +144,9 @@ class SmartCard {
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 rawChallenge = hexToBytes(challenge);
let data = try cmdSet.identifyCard(challenge: rawChallenge).checkOK().data
let caPubKey = try Certificate.verifyIdentity(hash: rawChallenge, tlvData: data)
let caPubKey = try Certificate.verifyIdentity(hash: rawChallenge, tlvData: data);
resolve([
"ca-public-key": bytesToHex(caPubKey ?? []),
@@ -165,27 +154,7 @@ class SmartCard {
])
}
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 {
func getApplicationInfo(channel: CardChannel, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) throws -> Void {
let cmdSet = KeycardCommandSet(cardChannel: channel)
let info = try ApplicationInfo(cmdSet.select().checkOK().data)
@@ -195,37 +164,23 @@ 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[instanceUID] {
if let _ = self.pairings[bytesToHex(info.instanceUID)] {
do {
try openSecureChannel(cmdSet: cmdSet)
isPaired = true
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)
} catch let error as CardError {
isPaired = try tryDefaultPairing(cmdSet: cmdSet, cardInfo: &cardInfo)
} catch let error as StatusWord {
isPaired = try tryDefaultPairing(cmdSet: cmdSet, 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)
@@ -248,7 +203,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) {
@@ -267,43 +222,36 @@ 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, exportOption: exportOption)
let rootKeyPair = try exportKey(cmdSet: cmdSet, path: .rootPath, makeCurrent: false, publicOnly: true)
let whisperKeyPair = try exportKey(cmdSet: cmdSet, path: .whisperPath, makeCurrent: false, publicOnly: false)
let walletKeyPair = try exportKey(cmdSet: cmdSet, path: .walletPath, makeCurrent: false, publicOnly: true)
var keys = [
let info = cmdSet.info!
resolve([
"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 {
@@ -334,7 +282,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()
@@ -423,19 +371,6 @@ 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))
@@ -448,27 +383,10 @@ class SmartCard {
}
func exportKey(cmdSet: KeycardCommandSet, path: DerivationPath, makeCurrent: Bool, publicOnly: Bool) throws -> BIP32KeyPair {
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
let tlvRoot = try cmdSet.exportKey(path: path.rawValue, makeCurrent: makeCurrent, publicOnly: publicOnly).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()
@@ -479,26 +397,12 @@ 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 {
@@ -509,20 +413,19 @@ class SmartCard {
return cmdSet
}
func tryDefaultPairing(cmdSet: KeycardCommandSet, eventEmitter: RCTEventEmitter, cardInfo: inout [String: Any]) throws -> Bool {
func tryDefaultPairing(cmdSet: KeycardCommandSet, cardInfo: inout [String: Any]) throws -> Bool {
do {
try cmdSet.autoPair(password: "KeycardDefaultPairing")
let pairing = Data(cmdSet.pairing!.bytes).base64EncodedString()
let instanceUID = bytesToHex(cmdSet.info!.instanceUID)
self.pairings[instanceUID] = pairing
self.pairings[bytesToHex(cmdSet.info!.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
-4
View File
@@ -33,14 +33,10 @@ 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
+2 -22
View File
@@ -80,7 +80,7 @@ class StatusKeycard: RCTEventEmitter {
@objc
func getApplicationInfo(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
keycardInvokation(reject) { [unowned self] channel in try self.smartCard.getApplicationInfo(channel: channel, eventEmitter: self, resolve: resolve, reject: reject) }
keycardInvokation(reject) { [unowned self] channel in try self.smartCard.getApplicationInfo(channel: channel, resolve: resolve, reject: reject) }
}
@objc
@@ -178,16 +178,6 @@ 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)
@@ -198,16 +188,6 @@ 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, *) {
@@ -297,7 +277,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.code == 102) && nsError.domain == "NFCError" {
if nsError.code == 100 && 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.tech/",
"version": "2.6.2",
"homepage": "https://keycard.status.im/",
"version": "2.6.0",
"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": "Michele Balistreri",
"author": "Dmitry Novotochinov",
"license": "MPL 2.0"
}