diff --git a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/Idemia.java b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/Idemia.java index ff34998..36e9ced 100644 --- a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/Idemia.java +++ b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/Idemia.java @@ -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) { @@ -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); diff --git a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/IdemiaWithPace.java b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/IdemiaWithPace.java index 17c6308..9fc7e63 100644 --- a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/IdemiaWithPace.java +++ b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/IdemiaWithPace.java @@ -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; @@ -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}); @@ -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}); @@ -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}); @@ -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 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 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. */ diff --git a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/LatviaIdemiaWithPace.java b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/LatviaIdemiaWithPace.java index 2574df1..120892f 100644 --- a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/LatviaIdemiaWithPace.java +++ b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/LatviaIdemiaWithPace.java @@ -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; @@ -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; @@ -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 certificateFiles = + new EnumMap<>(CertificateType.class); + private final Map keyReferences = + new EnumMap<>(CertificateType.class); + LatviaIdemiaWithPace(NfcSmartCardReader reader) { super(reader); - authKeyRef = (byte) 0x82; - signKeyRef = (byte) 0x9E; } @Override @@ -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 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 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; + } } diff --git a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/Thales.java b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/Thales.java index a20b8de..93c2ab2 100644 --- a/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/Thales.java +++ b/libs/id-card-lib/src/main/java/ee/ria/DigiDoc/idcard/Thales.java @@ -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); } } diff --git a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaDescriptorTest.java b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaDescriptorTest.java new file mode 100644 index 0000000..0aa7c08 --- /dev/null +++ b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaDescriptorTest.java @@ -0,0 +1,155 @@ +// SPDX-FileCopyrightText: 2026 Stagnation OÜ +// SPDX-License-Identifier: LGPL-2.1-or-later + +package ee.ria.DigiDoc.idcard; + +import static com.google.common.truth.Truth.assertThat; +import static ee.ria.DigiDoc.idcard.ApduReplayReader.bytes; +import static ee.ria.DigiDoc.idcard.ApduReplayReader.ok; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import ee.ria.DigiDoc.smartcardreader.SmartCardReaderException; + +import org.bouncycastle.util.encoders.Hex; +import org.junit.jupiter.api.Test; + +public final class LatviaIdemiaDescriptorTest { + + private static final String SEL_MAIN_AID = + "00a4040c10a000000077010800070000fe00000100"; + + private static final String CERT = "3003020101"; + + private static final String SIGNATURE = "a1b2c3d4"; + + @Test + public void certificate_usesTheFileIdFromEfCd() throws Exception { + var fixture = ReplayFixture.lv() + .with(r -> { + TestPkcs15.loadCertificateDirectory( + r, CertificateType.AUTHENTICATION, "3402"); + r.expect(SEL_MAIN_AID, ok()); + r.expect("00a4090c04adf13402", ok()); + TestPkcs15.loadFileRead(r, CERT); + }) + .tunnel(); + + byte[] certificate = fixture.token.certificate(CertificateType.AUTHENTICATION); + + assertThat(Hex.toHexString(certificate)).isEqualTo(CERT); + fixture.assertAllConsumed(); + } + + @Test + public void authenticate_usesTheKeyReferenceFromEfPrKd() throws Exception { + var fixture = ReplayFixture.lv() + .with(r -> { + TestPkcs15.loadPrivateKeyDirectory( + r, CertificateType.AUTHENTICATION, "81"); + r.expect(TestApdus.SEL_OBERTHUR_AID, ok()); + r.expect("00200001" + "0c" + TestPins.PIN1_PADDED_FF, ok()); + r.expect("002241a4" + "06" + "800104" + "840181", ok()); + r.expect("00880000" + "30" + TestApdus.CAPTURED_AUTH_HASH + "00", + bytes(SIGNATURE)); + }) + .tunnel(); + + byte[] signature = fixture.token.authenticate( + TestPins.PIN1, Hex.decode(TestApdus.CAPTURED_AUTH_HASH)); + + assertThat(Hex.toHexString(signature)).isEqualTo(SIGNATURE); + fixture.assertAllConsumed(); + } + + @Test + public void authenticate_efPrKdCarriesNoKeyReference_fallsBackToSlotTwo() throws Exception { + String efPrKdWithoutKeyRef = "a009" + "30020500" + "3003" + "040101"; + + var fixture = ReplayFixture.lv() + .with(r -> { + TestPkcs15.loadRawPrivateKeyDirectory( + r, CertificateType.AUTHENTICATION, efPrKdWithoutKeyRef); + r.expect(TestApdus.SEL_OBERTHUR_AID, ok()); + r.expect("00200001" + "0c" + TestPins.PIN1_PADDED_FF, ok()); + r.expect("002241a4" + "06" + "800104" + "840182", ok()); + r.expect("00880000" + "30" + TestApdus.CAPTURED_AUTH_HASH + "00", + bytes(SIGNATURE)); + }) + .tunnel(); + + byte[] signature = fixture.token.authenticate( + TestPins.PIN1, Hex.decode(TestApdus.CAPTURED_AUTH_HASH)); + + assertThat(Hex.toHexString(signature)).isEqualTo(SIGNATURE); + fixture.assertAllConsumed(); + } + + @Test + public void authenticate_nonEcPrivateKey_isRejectedBeforeThePinIsSent() throws Exception { + String efPrKdNonEc = "300d" + "30020500" + "3007" + "040101" + "0202" + "0082"; + + var fixture = ReplayFixture.lv() + .with(r -> TestPkcs15.loadRawPrivateKeyDirectory( + r, CertificateType.AUTHENTICATION, efPrKdNonEc)) + .tunnel(); + + assertThrows(NotSupportedException.class, () -> fixture.token.authenticate( + TestPins.PIN1, Hex.decode(TestApdus.CAPTURED_AUTH_HASH))); + fixture.assertAllConsumed(); + } + + @Test + public void certificate_doesNotReadThePrivateKeyDirectory() throws Exception { + var fixture = ReplayFixture.lv() + .with(r -> { + TestPkcs15.loadCertificateDirectory( + r, CertificateType.AUTHENTICATION, "3401"); + r.expect(SEL_MAIN_AID, ok()); + r.expect("00a4090c04adf13401", ok()); + TestPkcs15.loadFileRead(r, CERT); + }) + .tunnel(); + + byte[] certificate = fixture.token.certificate(CertificateType.AUTHENTICATION); + + assertThat(Hex.toHexString(certificate)).isEqualTo(CERT); + fixture.assertAllConsumed(); + } + + @Test + public void descriptor_missingCertificateDirectoryEntry_fails() throws Exception { + String efOdWithoutCertificates = "a006300404024001"; + + var fixture = ReplayFixture.lv() + .with(r -> { + r.expect(TestApdus.SEL_OBERTHUR_AID, ok()); + r.expect(TestPkcs15.SEL_EF_OD, ok()); + TestPkcs15.loadFileRead(r, efOdWithoutCertificates); + }) + .tunnel(); + + assertThrows(SmartCardReaderException.class, + () -> fixture.token.certificate(CertificateType.AUTHENTICATION)); + fixture.assertAllConsumed(); + } + + @Test + public void certificateFile_isReadOncePerCertificateType() throws Exception { + var fixture = ReplayFixture.lv() + .with(r -> { + TestPkcs15.loadCertificateDirectory( + r, CertificateType.AUTHENTICATION, "3401"); + for (int i = 0; i < 2; i++) { + r.expect(SEL_MAIN_AID, ok()); + r.expect("00a4090c04adf13401", ok()); + TestPkcs15.loadFileRead(r, CERT); + } + }) + .tunnel(); + + fixture.token.certificate(CertificateType.AUTHENTICATION); + fixture.token.certificate(CertificateType.AUTHENTICATION); + + fixture.assertAllConsumed(); + } +} diff --git a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPersonalDataReplayTest.java b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPersonalDataReplayTest.java index a313cf6..17085ac 100644 --- a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPersonalDataReplayTest.java +++ b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPersonalDataReplayTest.java @@ -85,6 +85,8 @@ static void loadPersonalDataTranscript(ApduReplayReader r) { // READ BINARY EF 0x5001 — Latvian personal code "326305-17052" UTF-8 r.expect("00b0000000", okPadded("3332363330352d313730353280000000")); + TestPkcs15.loadCertificateDirectory(r, CertificateType.AUTHENTICATION, "3401"); + // certificate(AUTHENTICATION) — selectMainAid() again r.expect("00a4040c10a000000077010800070000fe00000100", okPadded("")); // SELECT EF.AACE (auth cert) via P1=0x09, data=AD F1 34 01 diff --git a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPersonalDataTest.java b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPersonalDataTest.java index 2ec029f..38425eb 100644 --- a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPersonalDataTest.java +++ b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPersonalDataTest.java @@ -20,6 +20,7 @@ import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.util.encoders.Hex; import org.junit.jupiter.api.Test; import org.mockito.MockMakers; @@ -186,8 +187,8 @@ private static NfcSmartCardReader stubReaderFor(String personalCode, byte[] cert /** * Stub a reader that responds to the small set of APDUs personalData() - * issues. Tracks selected EF to disambiguate the two READ BINARY contexts - * (personal-code file vs auth certificate). + * issues. Tracks selected EF to disambiguate the three READ BINARY contexts + * (personal-code file, PKCS#15 directory, auth certificate). */ private static NfcSmartCardReader stubReaderForRawBytes(byte[] efPayload, byte[] certDer) { NfcSmartCardReader reader = mock(NfcSmartCardReader.class, @@ -195,6 +196,8 @@ private static NfcSmartCardReader stubReaderForRawBytes(byte[] efPayload, byte[] final boolean[] inCertContext = {false}; final int[] certReadCallNo = {0}; + final boolean[] inPkcs15Context = {false}; + final byte[][] pkcs15Payload = {null}; try { when(reader.transmit(anyInt(), anyInt(), anyInt(), anyInt(), any(), any())) @@ -210,10 +213,20 @@ private static NfcSmartCardReader stubReaderForRawBytes(byte[] efPayload, byte[] if (cla == 0x00 && ins == 0xA4) { // P1 = 0x09 path is how certificate() locates the auth cert. inCertContext[0] = (p1 == 0x09); + pkcs15Payload[0] = p1 == 0x02 ? pkcs15Directory(data) : null; + inPkcs15Context[0] = pkcs15Payload[0] != null; return new byte[0]; } // READ BINARY: branch on which file we last selected. if (cla == 0x00 && ins == 0xB0) { + if (inPkcs15Context[0]) { + byte[] payload = pkcs15Payload[0]; + if (payload == null) { + throw new ApduResponseException((byte) 0x6B, (byte) 0x00); + } + pkcs15Payload[0] = null; + return payload; + } if (inCertContext[0]) { certReadCallNo[0]++; if (certReadCallNo[0] == 1) { @@ -232,4 +245,17 @@ private static NfcSmartCardReader stubReaderForRawBytes(byte[] efPayload, byte[] } return reader; } + + private static byte[] pkcs15Directory(byte[] fileId) { + if (fileId == null || fileId.length != 2) { + return null; + } + String id = Hex.toHexString(fileId); + return switch (id) { + case "5031" -> Hex.decode(TestPkcs15.EF_OD); + case "4003" -> Hex.decode(TestPkcs15.efCd("3401")); + case "4001" -> Hex.decode(TestPkcs15.efPrKd("82")); + default -> null; + }; + } } diff --git a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPinRetryReplayTest.java b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPinRetryReplayTest.java index 22ccb8a..fa3599b 100644 --- a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPinRetryReplayTest.java +++ b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaPinRetryReplayTest.java @@ -38,6 +38,8 @@ public void verifyPin1_failure_translatesToCodeVerificationException( int sw1, int sw2, int expectedRetries) throws Exception { var fixture = ReplayFixture.lv() .with(r -> { + TestPkcs15.loadPrivateKeyDirectory( + r, CertificateType.AUTHENTICATION, "82"); r.expect(SEL_OBERTHUR_AID, ok()); r.expect("00200001" + "0c" + TestPins.WRONG_PIN1_PADDED_FF, err(sw1, sw2)); diff --git a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaSignFlowReplayTest.java b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaSignFlowReplayTest.java index af287ac..c679879 100644 --- a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaSignFlowReplayTest.java +++ b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/LatviaIdemiaSignFlowReplayTest.java @@ -46,6 +46,8 @@ public final class LatviaIdemiaSignFlowReplayTest { public void authenticate_replaysLvAuthSignFlow_returnsCapturedSignature() throws Exception { var fixture = ReplayFixture.lv() .with(r -> { + TestPkcs15.loadPrivateKeyDirectory( + r, CertificateType.AUTHENTICATION, "82"); r.expect(TestApdus.SEL_OBERTHUR_AID, ok()); r.expect("00200001" + "0c" + TestPins.PIN1_PADDED_FF, ok()); // MSE SET AT (P2=0xA4) — LV 3-byte template + auth key 0x82. @@ -67,6 +69,8 @@ public void authenticate_replaysLvAuthSignFlow_returnsCapturedSignature() throws public void calculateSignature_replaysLvDocumentSignFlow_returnsCapturedSignature() throws Exception { var fixture = ReplayFixture.lv() .with(r -> { + TestPkcs15.loadPrivateKeyDirectory( + r, CertificateType.SIGNING, "9e"); r.expect(TestApdus.SEL_QSCD_AID, ok()); r.expect("00200085" + "0c" + TestPins.PIN2_PADDED_FF, ok()); // MSE SET DST (P2=0xB6) — sign template + sign key 0x9E. diff --git a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/TestPkcs15.java b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/TestPkcs15.java new file mode 100644 index 0000000..c96eaa9 --- /dev/null +++ b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/TestPkcs15.java @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: 2026 Stagnation OÜ +// SPDX-License-Identifier: LGPL-2.1-or-later + +package ee.ria.DigiDoc.idcard; + +import static ee.ria.DigiDoc.idcard.ApduReplayReader.bytes; +import static ee.ria.DigiDoc.idcard.ApduReplayReader.err6B00; +import static ee.ria.DigiDoc.idcard.ApduReplayReader.ok; + +final class TestPkcs15 { + + private TestPkcs15() {} + + static final String SEL_EF_OD = "00a4020c025031"; + static final String SEL_EF_PRKD = "00a4020c024001"; + static final String SEL_EF_CD = "00a4020c024003"; + + static final String EF_OD = "a006300404024001a406300404024003"; + + static String efCd(String certificateFileId) { + return "300e" + "30020500" + "a108" + "3006" + "3004" + "0402" + certificateFileId; + } + + static String efPrKd(String keyReference) { + return "a00d" + "30020500" + "3007" + "040101" + "0202" + "00" + keyReference; + } + + static void loadCertificateDirectory(ApduReplayReader r, CertificateType type, + String certificateFileId) { + loadRawCertificateDirectory(r, type, efCd(certificateFileId)); + } + + static void loadRawCertificateDirectory(ApduReplayReader r, CertificateType type, + String efCd) { + loadObjectDirectory(r, type); + r.expect(SEL_EF_CD, ok()); + loadFileRead(r, efCd); + } + + static void loadPrivateKeyDirectory(ApduReplayReader r, CertificateType type, + String keyReference) { + loadRawPrivateKeyDirectory(r, type, efPrKd(keyReference)); + } + + static void loadRawPrivateKeyDirectory(ApduReplayReader r, CertificateType type, + String efPrKd) { + loadObjectDirectory(r, type); + r.expect(SEL_EF_PRKD, ok()); + loadFileRead(r, efPrKd); + } + + static void loadObjectDirectory(ApduReplayReader r, CertificateType type) { + r.expect(type == CertificateType.SIGNING + ? TestApdus.SEL_QSCD_AID : TestApdus.SEL_OBERTHUR_AID, ok()); + r.expect(SEL_EF_OD, ok()); + loadFileRead(r, EF_OD); + } + + static void loadFileRead(ApduReplayReader r, String payload) { + r.expect("00b0000000", bytes(payload)); + r.expect(readAt(payload.length() / 2), err6B00()); + } + + static String readAt(int offset) { + return String.format("00b0%04x00", offset); + } +} diff --git a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/ThalesCodeManagementTest.java b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/ThalesCodeManagementTest.java index d6b811e..47512a5 100644 --- a/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/ThalesCodeManagementTest.java +++ b/libs/id-card-lib/src/test/java/ee/ria/DigiDoc/idcard/ThalesCodeManagementTest.java @@ -242,6 +242,22 @@ public void certificate_authentication_selectsAuthCertEfAndReadsBody() throws Ex CommandStubReader.assertHeader(read, 0x00, 0xB0, 0x00, 0x00); } + @Test + public void certificate_singleByteSizeDo_readsExactlyThatManyBytes() throws Exception { + byte[] fci = Hex.decode("6203800105"); + byte[] certBody = new byte[] {0x30, 0x03, 0x01, 0x02, 0x03}; + CommandStubReader stub = new CommandStubReader() + .respondTo(0x00, 0xA4, fci) + .respondTo(0x00, 0xB0, certBody); + ThalesWithPace token = new ThalesWithPace(stub.build()); + + byte[] cert = token.certificate(CertificateType.AUTHENTICATION); + + assertThat(cert).isEqualTo(certBody); + assertThat(stub.captured).hasSize(2); + CommandStubReader.assertHeader(stub.captured.get(1), 0x00, 0xB0, 0x00, 0x00); + } + @Test public void certificate_signing_routesToSigningCertEf() throws Exception { byte[] fci = Hex.decode("620480020003");