ed25519_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package derhelpers
  2. import (
  3. "bytes"
  4. "encoding/pem"
  5. "testing"
  6. "golang.org/x/crypto/ed25519"
  7. )
  8. var testPubKey = `-----BEGIN PUBLIC KEY-----
  9. MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE=
  10. -----END PUBLIC KEY-----
  11. `
  12. var testPrivKey = `-----BEGIN PRIVATE KEY-----
  13. MC4CAQAwBQYDK2VwBCIEINTuctv5E1hK1bbY8fdp+K06/nwoy/HU++CXqI9EdVhC
  14. -----END PRIVATE KEY-----`
  15. func TestParseMarshalEd25519PublicKey(t *testing.T) {
  16. block, rest := pem.Decode([]byte(testPubKey))
  17. if len(rest) > 0 {
  18. t.Fatal("pem.Decode(); len(rest) > 0, want 0")
  19. }
  20. pk, err := ParseEd25519PublicKey(block.Bytes)
  21. if err != nil {
  22. t.Fatal(err)
  23. }
  24. if pkLen := len(pk.(ed25519.PublicKey)); pkLen != 32 {
  25. t.Fatalf("len(pk): got %d: want %d", pkLen, 32)
  26. }
  27. der, err := MarshalEd25519PublicKey(pk)
  28. if err != nil {
  29. t.Fatal(err)
  30. }
  31. if !bytes.Equal(der, block.Bytes) {
  32. t.Errorf("got %d bytes:\n%v \nwant %d bytes:\n%v",
  33. len(der), der, len(block.Bytes), block.Bytes)
  34. }
  35. }
  36. func TestParseMarshalEd25519PrivateKey(t *testing.T) {
  37. block, rest := pem.Decode([]byte(testPrivKey))
  38. if len(rest) > 0 {
  39. t.Fatal("pem.Decode(); len(rest) > 0, want 0")
  40. }
  41. sk, err := ParseEd25519PrivateKey(block.Bytes)
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. if skLen := len(sk.(ed25519.PrivateKey)); skLen != 64 {
  46. t.Fatalf("len(sk): got %d: want %d", skLen, 64)
  47. }
  48. der, err := MarshalEd25519PrivateKey(sk)
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. if !bytes.Equal(der, block.Bytes) {
  53. t.Errorf("got %d bytes:\n%v \nwant %d bytes:\n%v",
  54. len(der), der, len(block.Bytes), block.Bytes)
  55. }
  56. }
  57. func TestKeyPair(t *testing.T) {
  58. block, rest := pem.Decode([]byte(testPrivKey))
  59. if len(rest) > 0 {
  60. t.Fatal("pem.Decode(); len(rest) > 0, want 0")
  61. }
  62. sk, err := ParseEd25519PrivateKey(block.Bytes)
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. block, rest = pem.Decode([]byte(testPubKey))
  67. if len(rest) > 0 {
  68. t.Fatal("pem.Decode(); len(rest) > 0, want 0")
  69. }
  70. pub, err := ParseEd25519PublicKey(block.Bytes)
  71. if err != nil {
  72. t.Fatal(err)
  73. }
  74. pk := pub.(ed25519.PublicKey)
  75. pk2 := sk.(ed25519.PrivateKey).Public().(ed25519.PublicKey)
  76. if !bytes.Equal(pk, pk2) {
  77. t.Errorf("pk %d bytes:\n%v \nsk.Public() %d bytes:\n%v",
  78. len(pk), pk, len(pk2), pk2)
  79. }
  80. }