Go icon indicating copy to clipboard operation
Go copied to clipboard

fix(cipher/diffiehellman): use valid random private keys in key-exchange test

Open rajpreetcodes opened this issue 6 months ago • 1 comments

Description of Change

The Diffie-Hellman key-exchange test produced its "random" private keys by calling rsa.GenerateKey(rand.Reader, 31) and reading .D.Int64().

Go 1.24 introduced a minimum RSA key size of 1024 bits, so rsa.GenerateKey with a 31-bit size now returns the error rsa: key too small and a nil key. The test ignored that error (alicePrvKey, _ := ...) and then dereferenced the nil key (alicePrvKey.D.Int64()), producing a nil-pointer panic:

--- FAIL: TestDiffieHellmanKeyExchange/Test_2:_Key_Exchange
panic: runtime error: invalid memory address or nil pointer dereference
    .../diffiehellmankeyexchange_test.go:28

Because the CI workflow uses setup-go with go-version: '^1.18' (which resolves to the latest Go release), this breaks the build on Go ≥ 1.24.

This change generates the private keys directly with crypto/rand in the valid Diffie-Hellman range [1, primeNumber-1], removing the RSA dependency. It also makes the test more meaningful: the old .D.Int64() value could be negative, which sent modularExponentiation down a degenerate path where the equality assertion held even for invalid inputs.

Verification:

  • go test ./cipher/diffiehellman/ passes (ran with -count=20, not flaky)
  • go test ./... is green
  • go vet ./... clean
  • gofmt clean

Checklist

  • [x] Added description of change
  • [x] Added file name matches File name guidelines
  • [x] Added tests and example, test must pass
  • [x] Added documentation so that the program is self-explanatory and educational - GoDoc guidelines
  • [x] Relevant documentation/comments is changed or added
  • [x] PR title follows semantic commit guidelines
  • [x] Search previous suggestions before making a new one, as yours may be a duplicate.
  • [x] I acknowledge that all my contributions will be made under the project's license.

Notes: Fixes a nil-pointer panic in the Diffie-Hellman key-exchange test on Go ≥ 1.24 (rsa: key too small).

rajpreetcodes avatar May 25 '26 20:05 rajpreetcodes

Not up to standards ⛔

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer TIP This summary will be updated as you push new changes.

codacy-production[bot] avatar May 25 '26 20:05 codacy-production[bot]