crypto_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package crypto
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "testing"
  7. "time"
  8. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  9. "github.com/ethereum/go-ethereum/common"
  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 TestSha256(t *testing.T) {
  20. msg := []byte("abc")
  21. exp, _ := hex.DecodeString("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
  22. checkhash(t, "Sha256", Sha256, msg, exp)
  23. }
  24. func TestRipemd160(t *testing.T) {
  25. msg := []byte("abc")
  26. exp, _ := hex.DecodeString("8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")
  27. checkhash(t, "Ripemd160", Ripemd160, msg, exp)
  28. }
  29. func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
  30. sum := f(msg)
  31. if bytes.Compare(exp, sum) != 0 {
  32. t.Errorf("hash %s returned wrong result.\ngot: %x\nwant: %x", name, sum, exp)
  33. }
  34. }
  35. func BenchmarkSha3(b *testing.B) {
  36. a := []byte("hello world")
  37. amount := 1000000
  38. start := time.Now()
  39. for i := 0; i < amount; i++ {
  40. Sha3(a)
  41. }
  42. fmt.Println(amount, ":", time.Since(start))
  43. }
  44. func Test0Key(t *testing.T) {
  45. t.Skip()
  46. key := common.Hex2Bytes("1111111111111111111111111111111111111111111111111111111111111111")
  47. p, err := secp256k1.GeneratePubKey(key)
  48. addr := Sha3(p[1:])[12:]
  49. fmt.Printf("%x\n", p)
  50. fmt.Printf("%v %x\n", err, addr)
  51. }
  52. func TestInvalidSign(t *testing.T) {
  53. _, err := Sign(make([]byte, 1), nil)
  54. if err == nil {
  55. t.Errorf("expected sign with hash 1 byte to error")
  56. }
  57. _, err = Sign(make([]byte, 33), nil)
  58. if err == nil {
  59. t.Errorf("expected sign with hash 33 byte to error")
  60. }
  61. }