curve25519_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package curve25519
  5. import (
  6. "bytes"
  7. "crypto/rand"
  8. "fmt"
  9. "testing"
  10. )
  11. const expectedHex = "89161fde887b2b53de549af483940106ecc114d6982daa98256de23bdf77661a"
  12. func TestBaseScalarMult(t *testing.T) {
  13. var a, b [32]byte
  14. in := &a
  15. out := &b
  16. a[0] = 1
  17. for i := 0; i < 200; i++ {
  18. ScalarBaseMult(out, in)
  19. in, out = out, in
  20. }
  21. result := fmt.Sprintf("%x", in[:])
  22. if result != expectedHex {
  23. t.Errorf("incorrect result: got %s, want %s", result, expectedHex)
  24. }
  25. }
  26. func TestTestVectors(t *testing.T) {
  27. for _, tv := range testVectors {
  28. var got [32]byte
  29. ScalarMult(&got, &tv.In, &tv.Base)
  30. if !bytes.Equal(got[:], tv.Expect[:]) {
  31. t.Logf(" in = %x", tv.In)
  32. t.Logf(" base = %x", tv.Base)
  33. t.Logf(" got = %x", got)
  34. t.Logf("expect = %x", tv.Expect)
  35. t.Fail()
  36. }
  37. }
  38. }
  39. // TestHighBitIgnored tests the following requirement in RFC 7748:
  40. //
  41. // When receiving such an array, implementations of X25519 (but not X448) MUST
  42. // mask the most significant bit in the final byte.
  43. //
  44. // Regression test for issue #30095.
  45. func TestHighBitIgnored(t *testing.T) {
  46. var s, u [32]byte
  47. rand.Read(s[:])
  48. rand.Read(u[:])
  49. var hi0, hi1 [32]byte
  50. u[31] &= 0x7f
  51. ScalarMult(&hi0, &s, &u)
  52. u[31] |= 0x80
  53. ScalarMult(&hi1, &s, &u)
  54. if !bytes.Equal(hi0[:], hi1[:]) {
  55. t.Errorf("high bit of group point should not affect result")
  56. }
  57. }
  58. func BenchmarkScalarBaseMult(b *testing.B) {
  59. var in, out [32]byte
  60. in[0] = 1
  61. b.SetBytes(32)
  62. for i := 0; i < b.N; i++ {
  63. ScalarBaseMult(&out, &in)
  64. }
  65. }