Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,9 @@ public PersonalData personalData() throws SmartCardReaderException {

@Override
public byte[] certificate(CertificateType type) throws SmartCardReaderException {
byte[] file = certificateFile(type);
selectMainAid();
reader.transmit(0x00, 0xA4, 0x09, 0x0C, CERT_MAP.get(type), null);
reader.transmit(0x00, 0xA4, 0x09, 0x0C, file, null);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
while (true) {
Expand Down Expand Up @@ -151,6 +152,10 @@ public byte[] decrypt(byte[] pin1, byte[] data, boolean ecc) throws SmartCardRea
throw new SmartCardReaderException("Decryption not supported on this card");
}

protected byte[] certificateFile(CertificateType type) throws SmartCardReaderException {
return CERT_MAP.get(type);
}

protected void verifyCode(CodeType type, byte[] code) throws SmartCardReaderException {
try {
reader.transmit(0x00, 0x20, 0x00, Objects.requireNonNull(VERIFY_PIN_MAP.get(type)), code(code), null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ class IdemiaWithPace extends Idemia implements TokenWithPace, ApduEncryptor {
*/
private final NfcSmartCardReader nfcReader;

protected Byte authKeyRef = (byte) 0x81;
protected Byte signKeyRef = (byte) 0x9F;
protected byte authKeyRef = (byte) 0x81;
protected byte signKeyRef = (byte) 0x9F;

protected String paceEcSpec;
protected byte paceDomainParam;
Expand Down Expand Up @@ -808,9 +808,9 @@ protected byte[] decryptMseTemplate() {

@Override
public byte[] authenticate(byte[] pin1, byte[] token) throws SmartCardReaderException {
byte keyRef = getAuthKeyRef();
selectOberthurAid();
verifyCode(CodeType.PIN1, pin1);
byte keyRef = getAuthKeyRef();
byte[] template = authMseTemplate();
byte[] body = concatenate(template, new byte[] {(byte) 0x84, 0x01, keyRef});

Expand All @@ -826,9 +826,9 @@ public byte[] authenticate(byte[] pin1, byte[] token) throws SmartCardReaderExce

@Override
public byte[] calculateSignature(byte[] pin2, byte[] hash, boolean ecc) throws SmartCardReaderException {
byte keyRef = getSignKeyRef();
selectQSCDAid();
verifyCode(CodeType.PIN2, pin2);
byte keyRef = getSignKeyRef();
byte[] template = signMseTemplate();
byte[] body = concatenate(template, new byte[] {(byte) 0x84, 0x01, keyRef});

Expand All @@ -844,9 +844,9 @@ public byte[] calculateSignature(byte[] pin2, byte[] hash, boolean ecc) throws S

@Override
public byte[] decrypt(byte[] pin1, byte[] data, boolean ecc) throws SmartCardReaderException {
byte keyRef = getAuthKeyRef();
selectOberthurAid();
verifyCode(CodeType.PIN1, pin1);
byte keyRef = getAuthKeyRef();
byte[] template = decryptMseTemplate();
byte[] body = concatenate(template, new byte[] {(byte) 0x84, 0x01, keyRef});

Expand All @@ -860,134 +860,14 @@ public byte[] decrypt(byte[] pin1, byte[] data, boolean ecc) throws SmartCardRea
return reader.transmit(0x00, 0x2A, 0x80, 0x86, concatenate(new byte[] {0x00}, data), 0x00);
}

/**
* Get the authentication key reference. If null, attempts dynamic discovery from PrKDF.
* Cached after first read.
*/
protected byte getAuthKeyRef() throws SmartCardReaderException {
if (authKeyRef == null) {
byte ref = readKeyRefFromCurrentContext();
if (ref != 0) {
authKeyRef = ref;
LoggingUtil.Companion.debugLog(TAG,
String.format("PrKDF auth key ref discovered: 0x%02x", authKeyRef & 0xFF),
null
);
} else {
throw new SmartCardReaderException("Auth key reference not found in PrKDF");
}
}

return authKeyRef;
}

/**
* Get the signing key reference. If null, attempts dynamic discovery from PrKDF.
* Cached after first read.
*/
protected byte getSignKeyRef() throws SmartCardReaderException {
if (signKeyRef == null) {
byte ref = readKeyRefFromCurrentContext();
if (ref != 0) {
signKeyRef = ref;
LoggingUtil.Companion.debugLog(TAG,
String.format("PrKDF sign key ref discovered: 0x%02x", signKeyRef & 0xFF),
null
);
} else {
throw new SmartCardReaderException("Sign key reference not found in PrKDF");
}
}

return signKeyRef;
}

/**
* Read the first private key reference from the PrKDF in the currently selected AID context.
*
* Flow (matching Web eID libelectronic-id):
* 1. Select and read EF_OD (0x5031) — Object Directory File
* 2. Find tag 0xA0 (private key dir ref) → extract PrKDF file ID
* 3. Read PrKDF file
* 4. Return first keyReference INTEGER found
*
* @return key reference byte, or 0 if not found
*/
private byte readKeyRefFromCurrentContext() throws SmartCardReaderException {
// Read EF_OD (Object Directory File at 0x5031)
reader.transmit(0x00, 0xA4, 0x02, 0x0C, new byte[] {0x50, 0x31}, null);
byte[] efOd = readBinaryFile();

// Find tag 0xA0 (private key directory reference)
List<TLV> odEntries = TLV.parseAll(efOd);
TLV privKeyDir = TLV.findByTag(odEntries, 0xA0);
if (privKeyDir == null || privKeyDir.children == null) {
return 0;
}

// Navigate: A0 → 30 → 04 to get PrKDF file ID
TLV seq = privKeyDir.findByTag(0x30);
if (seq == null) {
return 0;
}
TLV fileIdTlv = seq.findByTag(0x04);
if (fileIdTlv == null || fileIdTlv.getValue().length != 2) {
return 0;
}

// Select and read PrKDF
byte[] fileId = fileIdTlv.getValue();
reader.transmit(0x00, 0xA4, 0x02, 0x0C, fileId, null);
byte[] prKdfData = readBinaryFile();

// Parse PrKDF entries and return first key reference found
List<TLV> keyEntries = TLV.parseAll(prKdfData);
for (TLV entry : keyEntries) {
if (entry.children == null || entry.children.size() < 2) {
continue;
}
byte keyRef = extractKeyReference(entry);
if (keyRef != 0) {
return keyRef;
}
}
return 0;
}

/**
* Extract key reference from a PKCS#15 PrivateKeyType entry.
*
* Structure: SEQUENCE { CommonObjectAttributes, CommonKeyAttributes, TypeAttributes }
* CommonKeyAttributes contains: iD, usage, ..., keyReference (INTEGER)
*
* In DER, key refs >= 0x80 are encoded as 2-byte INTEGERs (e.g., 02 02 00 82).
*/
protected static byte extractKeyReference(TLV entry) {
if (entry.children == null || entry.children.size() < 2) {
return 0;
}

// Second child SEQUENCE = CommonKeyAttributes
TLV commonKeyAttrs = entry.children.get(1);
if (commonKeyAttrs.children == null) {
return 0;
}

// Find INTEGER (tag 0x02) — this is the keyReference
for (TLV child : commonKeyAttrs.children) {
if (child.getTag() == 0x02) {
byte[] val = child.getValue();
if (val.length == 2) {
// 2-byte DER INTEGER (e.g., 00 82 → key ref 0x82)
return val[1];
} else if (val.length == 1) {
return val[0];
}
}
}
return 0;
}

/**
* Read a binary file from the currently selected EF.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

package ee.ria.DigiDoc.idcard;

import static org.bouncycastle.util.Arrays.concatenate;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name;
Expand All @@ -17,6 +19,9 @@
import java.security.cert.X509Certificate;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

import ee.ria.DigiDoc.smartcardreader.SmartCardReaderException;
import ee.ria.DigiDoc.smartcardreader.nfc.NfcSmartCardReader;
Expand All @@ -36,10 +41,21 @@
class LatviaIdemiaWithPace extends IdemiaWithPace {
private static final String TAG = LatviaIdemiaWithPace.class.getName();

private static final byte[] EF_OD = {0x50, 0x31};
private static final int TAG_CERTIFICATE_DIRECTORY = 0xA4;
private static final int TAG_PRIVATE_KEY_DIRECTORY = 0xA0;
private static final int TAG_PRIVATE_EC_KEY = 0xA0;

private static final byte[] ADF1 = {(byte) 0xAD, (byte) 0xF1};
private static final byte[] ADF2 = {(byte) 0xAD, (byte) 0xF2};

private final Map<CertificateType, byte[]> certificateFiles =
new EnumMap<>(CertificateType.class);
private final Map<CertificateType, Byte> keyReferences =
new EnumMap<>(CertificateType.class);

LatviaIdemiaWithPace(NfcSmartCardReader reader) {
super(reader);
authKeyRef = (byte) 0x82;
signKeyRef = (byte) 0x9E;
}

@Override
Expand Down Expand Up @@ -157,4 +173,133 @@ private static String rdnString(X500Name name, ASN1ObjectIdentifier oid) {
return IETFUtils.valueToString(rdns[0].getFirst().getValue());
}

@Override
protected byte[] certificateFile(CertificateType type) throws SmartCardReaderException {
byte[] cached = certificateFiles.get(type);
if (cached != null) {
return cached;
}

byte[] certificateDirectory = readDirectory(type, TAG_CERTIFICATE_DIRECTORY, "EF.CD");
byte[] file = descriptorValue(certificateDirectory,
new int[] {0x30, 0xA1, 0x30, 0x30, 0x04}, "EF.CD");
if (file.length != 2) {
String message = "EF.CD: certificate reference is "
+ file.length + " bytes, expected 2";
LoggingUtil.Companion.errorLog(TAG, message, null);
throw new SmartCardReaderException(message);
}

byte[] path = concatenate(type == CertificateType.SIGNING ? ADF2 : ADF1, file);
certificateFiles.put(type, path);
return path;
}

@Override
protected byte getAuthKeyRef() throws SmartCardReaderException {
return keyReference(CertificateType.AUTHENTICATION);
}

@Override
protected byte getSignKeyRef() throws SmartCardReaderException {
return keyReference(CertificateType.SIGNING);
}

private byte keyReference(CertificateType type) throws SmartCardReaderException {
Byte cached = keyReferences.get(type);
if (cached != null) {
return cached;
}

byte[] privateKeyDirectory = readDirectory(type, TAG_PRIVATE_KEY_DIRECTORY, "EF.PrKD");
List<TLV> keys = TLV.parseAll(privateKeyDirectory);
if (keys.isEmpty()) {
String message = "EF.PrKD: no private key record";
LoggingUtil.Companion.errorLog(TAG, message, null);
throw new SmartCardReaderException(message);
}
TLV key = keys.get(0);
if (key.getTag() != TAG_PRIVATE_EC_KEY) {
String message = "EF.PrKD: private key is not an EC key";
LoggingUtil.Companion.errorLog(TAG, message, null);
throw new NotSupportedException(message);
}

byte reference = extractKeyReference(key);
if (reference == 0) {
reference = defaultKeyReference(type);
}
keyReferences.put(type, reference);
return reference;
}

private byte[] readDirectory(CertificateType type, int tag, String file)
throws SmartCardReaderException {
if (type == CertificateType.SIGNING) {
selectQSCDAid();
} else {
selectOberthurAid();
}
byte[] objects = readEf(EF_OD);
return readEf(directoryReference(objects, tag, file));
}

private static byte defaultKeyReference(CertificateType type) {
return type == CertificateType.SIGNING ? (byte) 0x9E : (byte) 0x82;
}

private static byte[] directoryReference(byte[] objectDirectory, int tag, String file)
throws SmartCardReaderException {
byte[] reference = descriptorValue(objectDirectory, new int[] {tag, 0x30, 0x04}, "EF.OD");
if (reference.length != 2) {
String message = "EF.OD: " + file + " reference is "
+ reference.length + " bytes, expected 2";
LoggingUtil.Companion.errorLog(TAG, message, null);
throw new SmartCardReaderException(message);
}
return reference;
}

private byte[] readEf(byte[] fileId) throws SmartCardReaderException {
reader.transmit(0x00, 0xA4, 0x02, 0x0C, fileId, null);
return readBinaryFile();
}

private static byte[] descriptorValue(byte[] data, int[] path, String file)
throws SmartCardReaderException {
List<TLV> records = TLV.parseAll(data);
TLV record = null;
for (int tag : path) {
record = record == null ? TLV.findByTag(records, tag) : record.findByTag(tag);
if (record == null) {
String message = String.format("%s: missing PKCS#15 tag 0x%02X", file, tag);
LoggingUtil.Companion.errorLog(TAG, message, null);
throw new SmartCardReaderException(message);
}
}
return record.getValue();
}

private static byte extractKeyReference(TLV entry) {
if (entry.children == null || entry.children.size() < 2) {
return 0;
}

TLV commonKeyAttributes = entry.children.get(1);
if (commonKeyAttributes.children == null) {
return 0;
}

for (TLV child : commonKeyAttributes.children) {
if (child.getTag() == 0x02) {
byte[] value = child.getValue();
if (value.length == 2) {
return value[1];
} else if (value.length == 1) {
return value[0];
}
}
}
return 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ private byte[] readFile(int p1, byte[] bytes) throws SmartCardReaderException {
int tag = record.getTag();
if (tag == 0x80 || tag == 0x81) {
byte[] value = record.getValue();
if (value != null && value.length >= 2) {
if (value != null && value.length == 1) {
size = value[0] & 0xFF;
} else if (value != null && value.length >= 2) {
size = ((value[0] & 0xFF) << 8) | (value[1] & 0xFF);
}
}
Expand Down
Loading
Loading