@@ -615,12 +615,17 @@ static int wc_curve25519_shared_secret_nb(curve25519_key* privKey,
615615
616616 switch (privKey -> nb_ctx -> ssState ) {
617617 case 0 :
618- XMEMSET (& privKey -> nb_ctx -> o , 0 , sizeof (privKey -> nb_ctx -> o ));
619618 privKey -> nb_ctx -> ssState = 1 ;
620619 break ;
621620 case 1 :
622- ret = curve25519_nb (privKey -> nb_ctx -> o .point , privKey -> k ,
623- pubKey -> p .point , privKey -> nb_ctx );
621+ /* Write the result directly into the caller's 'out' buffer.
622+ * curve25519_nb() zeroes the non-blocking context on completion,
623+ * so any output buffer that lives inside nb_ctx (e.g.
624+ * nb_ctx->o.point) would be clobbered to zero before we could
625+ * read it. The output is little-endian; case 2 handles the
626+ * optional byte-reversal for EC25519_BIG_ENDIAN. */
627+ ret = curve25519_nb (out , privKey -> k , pubKey -> p .point ,
628+ privKey -> nb_ctx );
624629 if (ret == 0 ) {
625630 ret = FP_WOULDBLOCK ;
626631 privKey -> nb_ctx -> ssState = 2 ;
@@ -633,21 +638,27 @@ static int wc_curve25519_shared_secret_nb(curve25519_key* privKey,
633638 byte t = 0 ;
634639
635640 for (i = 0 ; i < CURVE25519_KEYSIZE ; i ++ ) {
636- t |= privKey -> nb_ctx -> o . point [i ];
641+ t |= out [i ];
637642 }
638643 if (t == 0 ) {
644+ ForceZero (out , CURVE25519_KEYSIZE );
639645 ret = ECC_OUT_OF_RANGE_E ;
646+ break ;
640647 }
641- else
648+ }
642649 #endif /* !WOLFSSL_NO_ECDHX_SHARED_ZERO_CHECK */
643- {
644- curve25519_copy_point (out , privKey -> nb_ctx -> o .point , endian );
645- * outlen = CURVE25519_KEYSIZE ;
646- ret = 0 ;
650+ if (endian == EC25519_BIG_ENDIAN ) {
651+ /* Reverse the little-endian result in place. */
652+ int i ;
653+ byte tmp ;
654+ for (i = 0 ; i < CURVE25519_KEYSIZE / 2 ; i ++ ) {
655+ tmp = out [i ];
656+ out [i ] = out [CURVE25519_KEYSIZE - 1 - i ];
657+ out [CURVE25519_KEYSIZE - 1 - i ] = tmp ;
647658 }
648- #ifndef WOLFSSL_NO_ECDHX_SHARED_ZERO_CHECK
649659 }
650- #endif
660+ * outlen = CURVE25519_KEYSIZE ;
661+ ret = 0 ;
651662 break ;
652663 }
653664
0 commit comments