dh_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package codec
  2. import (
  3. "math/big"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestDiffieHellman(t *testing.T) {
  8. key1, err := GenerateKey()
  9. assert.Nil(t, err)
  10. key2, err := GenerateKey()
  11. assert.Nil(t, err)
  12. pubKey1, err := ComputeKey(key1.PubKey, key2.PriKey)
  13. assert.Nil(t, err)
  14. pubKey2, err := ComputeKey(key2.PubKey, key1.PriKey)
  15. assert.Nil(t, err)
  16. assert.Equal(t, pubKey1, pubKey2)
  17. }
  18. func TestDiffieHellman1024(t *testing.T) {
  19. old := p
  20. p, _ = new(big.Int).SetString("F488FD584E49DBCD20B49DE49107366B336C380D451D0F7C88B31C7C5B2D8EF6F3C923C043F0A55B188D8EBB558CB85D38D334FD7C175743A31D186CDE33212CB52AFF3CE1B1294018118D7C84A70A72D686C40319C807297ACA950CD9969FABD00A509B0246D3083D66A45D419F9C7CBD894B221926BAABA25EC355E92F78C7", 16)
  21. defer func() {
  22. p = old
  23. }()
  24. key1, err := GenerateKey()
  25. assert.Nil(t, err)
  26. key2, err := GenerateKey()
  27. assert.Nil(t, err)
  28. pubKey1, err := ComputeKey(key1.PubKey, key2.PriKey)
  29. assert.Nil(t, err)
  30. pubKey2, err := ComputeKey(key2.PubKey, key1.PriKey)
  31. assert.Nil(t, err)
  32. assert.Equal(t, pubKey1, pubKey2)
  33. }
  34. func TestDiffieHellmanMiddleManAttack(t *testing.T) {
  35. key1, err := GenerateKey()
  36. assert.Nil(t, err)
  37. keyMiddle, err := GenerateKey()
  38. assert.Nil(t, err)
  39. key2, err := GenerateKey()
  40. assert.Nil(t, err)
  41. const aesByteLen = 32
  42. pubKey1, err := ComputeKey(keyMiddle.PubKey, key1.PriKey)
  43. assert.Nil(t, err)
  44. src := []byte(`hello, world!`)
  45. encryptedSrc, err := EcbEncrypt(pubKey1.Bytes()[:aesByteLen], src)
  46. assert.Nil(t, err)
  47. pubKeyMiddle, err := ComputeKey(key1.PubKey, keyMiddle.PriKey)
  48. assert.Nil(t, err)
  49. decryptedSrc, err := EcbDecrypt(pubKeyMiddle.Bytes()[:aesByteLen], encryptedSrc)
  50. assert.Nil(t, err)
  51. assert.Equal(t, string(src), string(decryptedSrc))
  52. pubKeyMiddle, err = ComputeKey(key2.PubKey, keyMiddle.PriKey)
  53. assert.Nil(t, err)
  54. encryptedSrc, err = EcbEncrypt(pubKeyMiddle.Bytes()[:aesByteLen], decryptedSrc)
  55. assert.Nil(t, err)
  56. pubKey2, err := ComputeKey(keyMiddle.PubKey, key2.PriKey)
  57. assert.Nil(t, err)
  58. decryptedSrc, err = EcbDecrypt(pubKey2.Bytes()[:aesByteLen], encryptedSrc)
  59. assert.Nil(t, err)
  60. assert.Equal(t, string(src), string(decryptedSrc))
  61. }
  62. func TestKeyBytes(t *testing.T) {
  63. var empty DhKey
  64. assert.Equal(t, 0, len(empty.Bytes()))
  65. key, err := GenerateKey()
  66. assert.Nil(t, err)
  67. assert.True(t, len(key.Bytes()) > 0)
  68. }