crypto_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package crypto
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "testing"
  7. "time"
  8. "github.com/ethereum/go-ethereum/common"
  9. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  10. )
  11. // These tests are sanity checks.
  12. // They should ensure that we don't e.g. use Sha3-224 instead of Sha3-256
  13. // and that the sha3 library uses keccak-f permutation.
  14. func TestSha3(t *testing.T) {
  15. msg := []byte("abc")
  16. exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
  17. checkhash(t, "Sha3-256", func(in []byte) []byte { return Sha3(in) }, msg, exp)
  18. }
  19. func TestSha3Hash(t *testing.T) {
  20. msg := []byte("abc")
  21. exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
  22. checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Sha3Hash(in); return h[:] }, msg, exp)
  23. }
  24. func TestSha256(t *testing.T) {
  25. msg := []byte("abc")
  26. exp, _ := hex.DecodeString("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
  27. checkhash(t, "Sha256", Sha256, msg, exp)
  28. }
  29. func TestRipemd160(t *testing.T) {
  30. msg := []byte("abc")
  31. exp, _ := hex.DecodeString("8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")
  32. checkhash(t, "Ripemd160", Ripemd160, msg, exp)
  33. }
  34. func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
  35. sum := f(msg)
  36. if bytes.Compare(exp, sum) != 0 {
  37. t.Errorf("hash %s returned wrong result.\ngot: %x\nwant: %x", name, sum, exp)
  38. }
  39. }
  40. func BenchmarkSha3(b *testing.B) {
  41. a := []byte("hello world")
  42. amount := 1000000
  43. start := time.Now()
  44. for i := 0; i < amount; i++ {
  45. Sha3(a)
  46. }
  47. fmt.Println(amount, ":", time.Since(start))
  48. }
  49. func Test0Key(t *testing.T) {
  50. t.Skip()
  51. key := common.Hex2Bytes("1111111111111111111111111111111111111111111111111111111111111111")
  52. p, err := secp256k1.GeneratePubKey(key)
  53. addr := Sha3(p[1:])[12:]
  54. fmt.Printf("%x\n", p)
  55. fmt.Printf("%v %x\n", err, addr)
  56. }
  57. func TestInvalidSign(t *testing.T) {
  58. _, err := Sign(make([]byte, 1), nil)
  59. if err == nil {
  60. t.Errorf("expected sign with hash 1 byte to error")
  61. }
  62. _, err = Sign(make([]byte, 33), nil)
  63. if err == nil {
  64. t.Errorf("expected sign with hash 33 byte to error")
  65. }
  66. }