aboutsummaryrefslogtreecommitdiff
path: root/private_key_test.go
blob: 6a40d704206304c3ef6fa048648eb39789137395 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package pki

import (
  "crypto"
  "crypto/elliptic"
  "encoding/pem"
  "testing"
)

var (
  SignatureMessage = []byte("foobar")
  SignatureHash    = crypto.SHA512
)

type (
  Loader func(raw []byte) (PublicKey, error)
)

// run the marshal test
func RunMarshalTest(pk_type string, pe Pemmer, label string, t *testing.T) ([]byte, error) {
  marsh_pem, err := pe.MarshalPem()
  if err != nil {
    t.Errorf("%s: marshal pem not working: %s", pk_type, err)
    return nil, err
  }

  block, _ := pem.Decode(marsh_pem)
  if block.Type != label {
    t.Errorf("%s: marshalled pem wrong: %s", pk_type, err)
    return nil, err
  }
  return block.Bytes, nil
}

// test other private key functions
func RunPrivateKeyTests(pk_type string, pk PrivateKey, pu PublicKey, t *testing.T) {
  signature, err := pk.Sign(SignatureMessage, SignatureHash)
  if err != nil { t.Errorf("%s: error creating a signature: %s", pk_type, err) }

  valid, err := pu.Verify(SignatureMessage, signature, SignatureHash)
  if err != nil { t.Errorf("%s: could not verify message: %s", pk_type, err) }
  if !valid { t.Errorf("%s: signature invalid, but should be valid!", pk_type) }
}

// test ecdsa private key functions
func TestEcdsaFunctions(t *testing.T) {
  pk, err := NewPrivateKeyEcdsa(elliptic.P521())
  if err != nil { t.Errorf("ecdsa: creating private key failed: %s", err) }

  block_bytes, err := RunMarshalTest("ecdsa", pk, PemLabelEcdsa, t)
  if err != nil { return }

  pk, err = LoadPrivateKeyEcdsa(block_bytes)
  if err != nil { t.Errorf("ecdsa: pem content wrong: %s", err) }

  block_bytes, err = RunMarshalTest("ecdsa-public", pk.Public(), PemLabelPublic, t)
  if err != nil { return }

  pu, err := LoadPublicKeyEcdsa(block_bytes)
  if err != nil { t.Errorf("ecdsa-public: pem content wrong: %s", err) }

  RunPrivateKeyTests("ecdsa", pk, pu, t)
}

// test rsa private key functions
func TestRsaFunctions(t *testing.T) {
  pk, err := NewPrivateKeyRsa(2048)
  if err != nil { t.Errorf("rsa: creating private key failed: %s", err) }

  block_bytes, err := RunMarshalTest("rsa", pk, PemLabelRsa, t)
  if err != nil { return }

  pk, err = LoadPrivateKeyRsa(block_bytes)
  if err != nil { t.Errorf("rsa: pem content wrong: %s", err) }


  block_bytes, err = RunMarshalTest("rsa-public", pk.Public(), PemLabelPublic, t)
  if err != nil { return }

  pu, err := LoadPublicKeyRsa(block_bytes)
  if err != nil { t.Errorf("rsa-public: pem content wrong: %s", err) }

  RunPrivateKeyTests("rsa", pk, pu, t)
}