F-11204: encode RSA DER key before the PKCS#8 size query

pull/265/head
Chris Conlon 2026-08-24 16:45:24 -06:00
parent 2d4e0a8c97
commit ee2c2eeed6
2 changed files with 32 additions and 17 deletions

View File

@ -561,23 +561,6 @@ JNIEXPORT jbyteArray JNICALL Java_com_wolfssl_wolfcrypt_Rsa_wc_1RsaPrivateKeyToP
}
}
/* Get PKCS#8 output size, into pkcs8Sz */
if (ret == 0) {
ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, derKey, derKeySz, algoID,
curveOID, oidSz);
if (ret == LENGTH_ONLY_E) {
pkcs8 = (byte*)XMALLOC(pkcs8Sz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (pkcs8 == NULL) {
ret = MEMORY_E;
}
else {
XMEMSET(pkcs8, 0, pkcs8Sz);
pkcs8BufSz = pkcs8Sz;
ret = 0;
}
}
}
if (ret == 0) {
/* Allocate temp buffer to hold DER encoded key */
derKey = (byte*)XMALLOC(derKeySz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
@ -599,6 +582,23 @@ JNIEXPORT jbyteArray JNICALL Java_com_wolfssl_wolfcrypt_Rsa_wc_1RsaPrivateKeyToP
}
}
/* Get PKCS#8 output size, into pkcs8Sz. */
if (ret == 0) {
ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, derKey, derKeySz, algoID,
curveOID, oidSz);
if (ret == LENGTH_ONLY_E) {
pkcs8 = (byte*)XMALLOC(pkcs8Sz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (pkcs8 == NULL) {
ret = MEMORY_E;
}
else {
XMEMSET(pkcs8, 0, pkcs8Sz);
pkcs8BufSz = pkcs8Sz;
ret = 0;
}
}
}
/* Create PKCS#8 from DER key */
if (ret == 0) {
ret = wc_CreatePKCS8Key(pkcs8, &pkcs8Sz, derKey, derKeySz,

View File

@ -423,6 +423,21 @@ public class RsaTest {
pub.releaseNativeStruct();
}
@Test
public void rsaPrivateKeyToPkcs8RoundTrip() {
Rsa key = makeKeyWithRetry(2048, 65537, rng);
byte[] pkcs8 = key.privateKeyEncodePKCS8();
assertNotNull(pkcs8);
assertTrue(pkcs8.length > 0);
key.releaseNativeStruct();
/* PKCS8 output must decode back into a usable private key */
Rsa decoded = new Rsa();
decoded.decodePrivateKeyPKCS8(pkcs8);
decoded.releaseNativeStruct();
}
@Test
public void publicKeyDecodeAndEncodeWithByteBuffer() {
Rsa key = new Rsa();