@@ -625,12 +625,17 @@ static int wc_curve25519_shared_secret_nb(curve25519_key* privKey,
625625
626626 switch (privKey -> nb_ctx -> ssState ) {
627627 case 0 :
628- XMEMSET (& privKey -> nb_ctx -> o , 0 , sizeof (privKey -> nb_ctx -> o ));
629628 privKey -> nb_ctx -> ssState = 1 ;
630629 break ;
631630 case 1 :
632- ret = curve25519_nb (privKey -> nb_ctx -> o .point , privKey -> k ,
633- pubKey -> p .point , privKey -> nb_ctx );
631+ /* Write the result directly into the caller's 'out' buffer.
632+ * curve25519_nb() zeroes the non-blocking context on completion,
633+ * so any output buffer that lives inside nb_ctx (e.g.
634+ * nb_ctx->o.point) would be clobbered to zero before we could
635+ * read it. The output is little-endian; case 2 handles the
636+ * optional byte-reversal for EC25519_BIG_ENDIAN. */
637+ ret = curve25519_nb (out , privKey -> k , pubKey -> p .point ,
638+ privKey -> nb_ctx );
634639 if (ret == 0 ) {
635640 ret = FP_WOULDBLOCK ;
636641 privKey -> nb_ctx -> ssState = 2 ;
@@ -643,21 +648,27 @@ static int wc_curve25519_shared_secret_nb(curve25519_key* privKey,
643648 byte t = 0 ;
644649
645650 for (i = 0 ; i < CURVE25519_KEYSIZE ; i ++ ) {
646- t |= privKey -> nb_ctx -> o . point [i ];
651+ t |= out [i ];
647652 }
648653 if (t == 0 ) {
654+ ForceZero (out , CURVE25519_KEYSIZE );
649655 ret = ECC_OUT_OF_RANGE_E ;
656+ break ;
650657 }
651- else
658+ }
652659 #endif /* !WOLFSSL_NO_ECDHX_SHARED_ZERO_CHECK */
653- {
654- curve25519_copy_point (out , privKey -> nb_ctx -> o .point , endian );
655- * outlen = CURVE25519_KEYSIZE ;
656- ret = 0 ;
660+ if (endian == EC25519_BIG_ENDIAN ) {
661+ /* Reverse the little-endian result in place. */
662+ int i ;
663+ byte tmp ;
664+ for (i = 0 ; i < CURVE25519_KEYSIZE / 2 ; i ++ ) {
665+ tmp = out [i ];
666+ out [i ] = out [CURVE25519_KEYSIZE - 1 - i ];
667+ out [CURVE25519_KEYSIZE - 1 - i ] = tmp ;
657668 }
658- #ifndef WOLFSSL_NO_ECDHX_SHARED_ZERO_CHECK
659669 }
660- #endif
670+ * outlen = CURVE25519_KEYSIZE ;
671+ ret = 0 ;
661672 break ;
662673 }
663674
0 commit comments