Skip to content

Commit 7740fa4

Browse files
committed
Fix PQC seed-only private key PKCS#8 encoding
When a seed-only private key was imported from another provider, the key material was already represented as the RFC-defined seed CHOICE using the context-specific [0] tag. However, getEncoded() treated all non-expanded key material the same way and wrapped it again as an OCTET STRING. This produced a PKCS#8 encoding that was not equivalent to the original PKCS8EncodedKeySpec returned by the other provider. Add an isSeed flag to preserve whether the private key was imported in seed-only form. When encoding the key back to PKCS#8, seed-only keys are written using the existing encoded private key material, while expanded keys continue to use the existing OCTET STRING wrapping expected by the provider. Also add isSeedOnly() to identify RFC 9881 and RFC 9935 seed-only private key encodings imported from other providers. Per the RFC private key CHOICE definitions, ML-DSA seed keys use a 32-byte seed with the context-specific [0] tag, and ML-KEM seed keys use a 64-byte seed with the context-specific [0] tag. Signed-off-by: JinhangZhang <Jinhang.Zhang@ibm.com>
1 parent b99064d commit 7740fa4

2 files changed

Lines changed: 115 additions & 3 deletions

File tree

‎src/main/java/com/ibm/crypto/plus/provider/PQCPrivateKey.java‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ final class PQCPrivateKey extends PKCS8Key {
3333

3434
private transient boolean destroyed = false;
3535

36+
private boolean isSeed = false;
37+
3638
/**
3739
* Create a PQC private key from the key data and the algorithm name.
3840
*
@@ -46,7 +48,11 @@ final class PQCPrivateKey extends PKCS8Key {
4648
this.provider = provider;
4749
byte[] key = null;
4850
DerValue pkOct = null;
49-
51+
52+
if (isSeedOnly(this.name, keyBytes)) {
53+
this.isSeed = true;
54+
}
55+
5056
//Check to determine if the key bytes already have the Octet tag.
5157
if (OctectStringEncoded(keyBytes)) {
5258
//Remove encoding OctetString encoding.
@@ -96,6 +102,9 @@ final class PQCPrivateKey extends PKCS8Key {
96102

97103
this.name = PQCKnownOIDs.findMatch(pqcKey.getAlgorithm()).stdName();
98104
this.algid = new AlgorithmId(PQCAlgorithmId.getOID(name));
105+
if (isSeedOnly(this.name, pqcKey.getPrivateKeyBytes())) {
106+
this.isSeed = true;
107+
}
99108
} catch (Exception exception) {
100109
throw provider.providerException("Failure in PQCPrivateKey" + exception.getMessage(), exception);
101110
}
@@ -111,7 +120,9 @@ final class PQCPrivateKey extends PKCS8Key {
111120
this.provider = provider;
112121

113122
this.name = PQCKnownOIDs.findMatch(this.algid.getName()).stdName();
114-
123+
if (isSeedOnly(this.name, this.privKeyMaterial)) {
124+
this.isSeed = true;
125+
}
115126
//Check to determine if the key bytes have the Octet tag.
116127
if (!(OctectStringEncoded(this.privKeyMaterial))) {
117128
DerValue pkOct = null;
@@ -159,7 +170,11 @@ public byte[] getEncoded() {
159170
DerOutputStream bytes = new DerOutputStream();
160171
bytes.putOID(algid.getOID());
161172
tmp.write(DerValue.tag_Sequence, bytes);
162-
tmp.putOctetString(this.privKeyMaterial);
173+
if (isSeed) {
174+
tmp.write(this.privKeyMaterial);
175+
} else {
176+
tmp.putOctetString(this.privKeyMaterial);
177+
}
163178
DerValue out = DerValue.wrap(DerValue.tag_Sequence, tmp);
164179
encodedKey = out.toByteArray();
165180
tmp.close();
@@ -235,4 +250,23 @@ private boolean OctectStringEncoded(byte[] key) {
235250
}
236251
}
237252

253+
private boolean isSeedOnly(String algName, byte[] key) {
254+
if (key == null || key.length < 2) {
255+
return false;
256+
}
257+
258+
int seedLen;
259+
260+
if (algName.startsWith("ML-DSA")) {
261+
seedLen = 32;
262+
} else if (algName.startsWith("ML-KEM")) {
263+
seedLen = 64;
264+
} else {
265+
return false;
266+
}
267+
268+
return (key.length == seedLen + 2)
269+
&& ((key[0] & 0xFF) == 0x80)
270+
&& ((key[1] & 0xFF) == seedLen);
271+
}
238272
}

‎src/test/java/ibm/jceplus/junit/base/BaseTestPQCKeyInterop.java‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import java.security.PublicKey;
1717
import java.security.Signature;
1818
import java.security.spec.EncodedKeySpec;
19+
import java.security.spec.KeySpec;
1920
import java.security.spec.NamedParameterSpec;
2021
import java.security.spec.PKCS8EncodedKeySpec;
2122
import java.security.spec.X509EncodedKeySpec;
@@ -26,6 +27,7 @@
2627
import org.junit.jupiter.params.ParameterizedTest;
2728
import org.junit.jupiter.params.provider.CsvSource;
2829
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
30+
import static org.junit.jupiter.api.Assertions.assertEquals;
2931
import static org.junit.jupiter.api.Assertions.assertTrue;
3032
import static org.junit.jupiter.api.Assertions.fail;
3133
import static org.junit.jupiter.api.Assumptions.assumeFalse;
@@ -739,4 +741,80 @@ public void testMLKEMBidirectionalInteropWithNamedParameterSpec(String parameter
739741
"Keys do not match for test 2 with " + parameterSet);
740742
}
741743

744+
@ParameterizedTest
745+
@CsvSource({"ML-KEM", "ML-KEM-512", "ML-KEM-768", "ML-KEM-1024"})
746+
public void testMLKEMGetKeySpecPrivateInteropToPlus(String algorithm)
747+
throws Exception {
748+
// This is not in the FIPS provider yet.
749+
assumeFalse("OpenJCEPlusFIPS".equals(getProviderName()));
750+
751+
// This test is for SunJCE/OpenJCEPlus interop, not BC.
752+
assumeFalse(Utils.PROVIDER_BC.equals(getInteropProviderName()));
753+
754+
KeyFactory openjceplusKeyFactory = KeyFactory.getInstance(algorithm, getProviderName());
755+
KeyPairGenerator interopKpg = KeyPairGenerator.getInstance(algorithm, getInteropProviderName());
756+
KeyPair interopKeyPair = interopKpg.generateKeyPair();
757+
PrivateKey interopPrivateKey = interopKeyPair.getPrivate();
758+
KeySpec interopPrivKeySpec = new PKCS8EncodedKeySpec(interopPrivateKey.getEncoded());
759+
PrivateKey openjceplusPrivateKey = openjceplusKeyFactory.generatePrivate(interopPrivKeySpec);
760+
761+
KEM interopKem = KEM.getInstance(algorithm, getInteropProviderName());
762+
KEM.Encapsulator encapsulator =
763+
interopKem.newEncapsulator(interopKeyPair.getPublic());
764+
765+
KEM.Encapsulated encapsulated = encapsulator.encapsulate();
766+
767+
KEM openjceplusKem = KEM.getInstance(algorithm, getProviderName());
768+
KEM.Decapsulator decapsulator =
769+
openjceplusKem.newDecapsulator(openjceplusPrivateKey);
770+
771+
SecretKey openjceplusSecret =
772+
decapsulator.decapsulate(encapsulated.encapsulation());
773+
774+
assertArrayEquals(encapsulated.key().getEncoded(),
775+
openjceplusSecret.getEncoded());
776+
777+
KeySpec keySpec = openjceplusKeyFactory.getKeySpec(openjceplusPrivateKey, interopPrivKeySpec.getClass());
778+
assertEquals(interopPrivKeySpec.getClass(), keySpec.getClass());
779+
assertPrivateKeyPKCS8SpecEquals(interopPrivKeySpec, keySpec);
780+
}
781+
782+
@ParameterizedTest
783+
@CsvSource({"ML-DSA", "ML-DSA-44", "ML-DSA-65", "ML-DSA-87"})
784+
public void testMLDSAGetKeySpecPrivateInteropToPlus(String algorithm)
785+
throws Exception {
786+
// This is not in the FIPS provider yet.
787+
assumeFalse("OpenJCEPlusFIPS".equals(getProviderName()));
788+
789+
// This test is for SunJCE/OpenJCEPlus interop, not BC.
790+
assumeFalse(Utils.PROVIDER_BC.equals(getInteropProviderName2()));
791+
792+
KeyFactory openjceplusKeyFactory = KeyFactory.getInstance(algorithm, getProviderName());
793+
KeyPairGenerator interopKpg = KeyPairGenerator.getInstance(algorithm, getInteropProviderName2());
794+
KeyPair interopKeyPair = interopKpg.generateKeyPair();
795+
PrivateKey interopPrivateKey = interopKeyPair.getPrivate();
796+
KeySpec interopPrivKeySpec = new PKCS8EncodedKeySpec(interopPrivateKey.getEncoded());
797+
PrivateKey openjceplusPrivateKey = openjceplusKeyFactory.generatePrivate(interopPrivKeySpec);
798+
799+
Signature signerPlus = Signature.getInstance(algorithm, getProviderName());
800+
signerPlus.initSign(openjceplusPrivateKey);
801+
signerPlus.update(origMsg);
802+
byte[] signaturePlus = signerPlus.sign();
803+
804+
Signature verifierInterop = Signature.getInstance(algorithm, getInteropProviderName2());
805+
verifierInterop.initVerify(interopKeyPair.getPublic());
806+
verifierInterop.update(origMsg);
807+
assertTrue(verifierInterop.verify(signaturePlus), "Signature verification failed");
808+
}
809+
810+
private void assertPrivateKeyPKCS8SpecEquals(KeySpec expected, KeySpec actual) {
811+
assertEquals(PKCS8EncodedKeySpec.class, actual.getClass());
812+
813+
PKCS8EncodedKeySpec expectedSpec = (PKCS8EncodedKeySpec) expected;
814+
PKCS8EncodedKeySpec actualSpec = (PKCS8EncodedKeySpec) actual;
815+
816+
assertArrayEquals(expectedSpec.getEncoded(), actualSpec.getEncoded());
817+
assertEquals(expectedSpec.getAlgorithm(), actualSpec.getAlgorithm());
818+
assertEquals(expectedSpec.getFormat(), actualSpec.getFormat());
819+
}
742820
}

0 commit comments

Comments
 (0)