2015-10-18 13:35:59 +08:00
|
|
|
package letsencrypt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/x509"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
2015-10-19 02:09:06 +08:00
|
|
|
func init() {
|
2015-10-28 02:53:31 +08:00
|
|
|
rsaKeySizeToUse = 128 // make tests faster; small key size OK for testing
|
2015-10-19 02:09:06 +08:00
|
|
|
}
|
|
|
|
|
2015-10-18 13:35:59 +08:00
|
|
|
func TestSaveAndLoadRSAPrivateKey(t *testing.T) {
|
|
|
|
keyFile := "test.key"
|
|
|
|
defer os.Remove(keyFile)
|
|
|
|
|
2015-10-28 02:53:31 +08:00
|
|
|
privateKey, err := rsa.GenerateKey(rand.Reader, rsaKeySizeToUse)
|
2015-10-18 13:35:59 +08:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// test save
|
|
|
|
err = saveRSAPrivateKey(privateKey, keyFile)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal("error saving private key:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// test load
|
|
|
|
loadedKey, err := loadRSAPrivateKey(keyFile)
|
|
|
|
if err != nil {
|
|
|
|
t.Error("error loading private key:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// very loaded key is correct
|
2015-10-19 02:09:06 +08:00
|
|
|
if !rsaPrivateKeysSame(privateKey, loadedKey) {
|
2015-10-18 13:35:59 +08:00
|
|
|
t.Error("Expected key bytes to be the same, but they weren't")
|
|
|
|
}
|
|
|
|
}
|
2015-10-19 02:09:06 +08:00
|
|
|
|
|
|
|
// rsaPrivateKeysSame compares the bytes of a and b and returns true if they are the same.
|
|
|
|
func rsaPrivateKeysSame(a, b *rsa.PrivateKey) bool {
|
|
|
|
return bytes.Equal(rsaPrivateKeyBytes(a), rsaPrivateKeyBytes(b))
|
|
|
|
}
|
2016-01-04 08:05:10 +08:00
|
|
|
|
|
|
|
// rsaPrivateKeyBytes returns the bytes of DER-encoded key.
|
|
|
|
func rsaPrivateKeyBytes(key *rsa.PrivateKey) []byte {
|
|
|
|
return x509.MarshalPKCS1PrivateKey(key)
|
|
|
|
}
|