-
Notifications
You must be signed in to change notification settings - Fork 9
/
rsa_private_test.go
90 lines (78 loc) · 2.52 KB
/
rsa_private_test.go
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
85
86
87
88
89
package gose
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/ThalesGroup/gose/jose"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
)
func TestRsaPrivateKey_MarshalSucceeds(t *testing.T) {
// Setup
k, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
jwk, err := JwkFromPrivateKey(k, []jose.KeyOps{jose.KeyOpsSign}, nil)
require.NoError(t, err)
signer, err := NewSigningKey(jwk, []jose.KeyOps{jose.KeyOpsSign})
require.NoError(t, err)
// Act
marshalled, err := signer.Marshal()
// Assert
require.NoError(t, err)
require.NotNil(t, marshalled)
unmarshalledJwk, err := LoadJwk(bytes.NewReader([]byte(marshalled)), nil)
require.NoError(t, err)
require.Equal(t, jwk.Alg(), unmarshalledJwk.Alg())
require.Equal(t, jwk.Ops(), unmarshalledJwk.Ops())
require.Equal(t, jwk.Kty(), unmarshalledJwk.Kty())
require.Equal(t, jwk.Kid(), unmarshalledJwk.Kid())
}
func TestRsaPrivateKey_MarshalPemSucceeds(t *testing.T) {
// Setup
k, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
jwk, err := JwkFromPrivateKey(k, []jose.KeyOps{jose.KeyOpsSign}, nil)
require.NoError(t, err)
signer, err := NewSigningKey(jwk, []jose.KeyOps{jose.KeyOpsSign})
require.NoError(t, err)
// Act
marshalled, err := signer.MarshalPem()
// Assert
require.NoError(t, err)
require.NotEmpty(t, marshalled)
block, overflow := pem.Decode([]byte(marshalled))
require.Empty(t, overflow)
require.Equal(t, block.Type, rsaPrivateKeyPemType)
recoveredKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
require.NoError(t, err)
assert.Equal(t, recoveredKey.E, k.E)
assert.Equal(t, recoveredKey.N.Cmp(k.N), 0)
assert.Equal(t, recoveredKey.D.Cmp(k.D), 0)
assert.Equal(t, recoveredKey.N.Cmp(k.N), 0)
}
func TestRsaPrivateKey_Verifier(t *testing.T) {
// Setup
k, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
jwk, err := JwkFromPrivateKey(k, []jose.KeyOps{jose.KeyOpsSign}, nil)
require.NoError(t, err)
signer, err := NewSigningKey(jwk, []jose.KeyOps{jose.KeyOpsSign})
require.NoError(t, err)
// Act
verifier, err := signer.Verifier()
// Assert
assert.NoError(t, err)
assert.NotNil(t, verifier)
assert.Equal(t, verifier.Kid(), signer.Kid())
// Sign something, then verify
testData := make([]byte, 10)
_, err = rand.Read(testData)
require.NoError(t, err)
signature, err := signer.Sign(jose.KeyOpsSign, testData)
require.NoError(t, err)
matches := verifier.Verify(jose.KeyOpsVerify, testData, signature)
assert.True(t, matches)
}