@@ -3252,22 +3252,31 @@ int SetShortInt(byte* output, word32* inOutIdx, word32 number, word32 maxIdx)
32523252 word32 idx = *inOutIdx;
32533253 word32 len;
32543254 int i;
3255+ word32 extraByte = 0;
32553256
32563257 if (number == 0)
32573258 len = 1;
32583259 else
32593260 len = BytePrecision(number);
32603261
3262+ if (number >> (WOLFSSL_BIT_SIZE * len - 1)) {
3263+ /* Need one byte of zero value not to be negative number */
3264+ extraByte = 1;
3265+ }
3266+
32613267 /* check for room for type and length bytes. */
3262- if ((idx + 2 + len) > maxIdx)
3268+ if ((idx + 2 + extraByte + len) > maxIdx)
32633269 return BUFFER_E;
32643270
32653271 /* check that MAX_SHORT_SZ allows this size of ShortInt. */
3266- if (2 + len > MAX_SHORT_SZ)
3272+ if (2 + extraByte + len > MAX_SHORT_SZ)
32673273 return ASN_PARSE_E;
32683274
32693275 output[idx++] = ASN_INTEGER;
3270- output[idx++] = (byte)len;
3276+ output[idx++] = (byte)(len + extraByte);
3277+ if (extraByte) {
3278+ output[idx++] = 0x00;
3279+ }
32713280
32723281 for (i = (int)len - 1; i >= 0; --i)
32733282 output[idx++] = (byte)(number >> (i * WOLFSSL_BIT_SIZE));
@@ -9565,6 +9574,8 @@ int wc_EncryptPKCS8Key_ex(byte* key, word32 keySz, byte* out, word32* outSz,
95659574 word32 encIdx = 0;
95669575 const byte* hmacOidBuf = NULL;
95679576 word32 hmacOidBufSz = 0;
9577+ byte tmpShort[MAX_SHORT_SZ];
9578+ word32 tmpIdx = 0;
95689579
95699580 (void)heap;
95709581
@@ -9587,9 +9598,14 @@ int wc_EncryptPKCS8Key_ex(byte* key, word32 keySz, byte* out, word32* outSz,
95879598 if (ret == 0) {
95889599 padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
95899600 (blockSz - 1));
9590- /* inner = OCT salt INT itt */
9591- innerLen = 2 + saltSz + 2 + ((itt < 256) ? 1 : ((itt < 65536) ? 2 : 3));
9592-
9601+ ret = SetShortInt(tmpShort, &tmpIdx, (word32)itt, MAX_SHORT_SZ);
9602+ if (ret > 0) {
9603+ /* inner = OCT salt INT itt */
9604+ innerLen = 2 + saltSz + (word32)ret;
9605+ ret = 0;
9606+ }
9607+ }
9608+ if (ret == 0) {
95939609 if (version != PKCS5v2) {
95949610 pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
95959611 /* pbe = OBJ pbse1 SEQ [ inner ] */
0 commit comments