Source file src/crypto/rsa/equal_test.go

     1  // Copyright 2020 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rsa_test
     6  
     7  import (
     8  	"crypto"
     9  	"crypto/rand"
    10  	"crypto/rsa"
    11  	"crypto/x509"
    12  	"testing"
    13  )
    14  
    15  func TestEqual(t *testing.T) {
    16  	private, _ := rsa.GenerateKey(rand.Reader, 512)
    17  	public := &private.PublicKey
    18  
    19  	if !public.Equal(public) {
    20  		t.Errorf("public key is not equal to itself: %v", public)
    21  	}
    22  	if !public.Equal(crypto.Signer(private).Public().(*rsa.PublicKey)) {
    23  		t.Errorf("private.Public() is not Equal to public: %q", public)
    24  	}
    25  	if !private.Equal(private) {
    26  		t.Errorf("private key is not equal to itself: %v", private)
    27  	}
    28  
    29  	enc, err := x509.MarshalPKCS8PrivateKey(private)
    30  	if err != nil {
    31  		t.Fatal(err)
    32  	}
    33  	decoded, err := x509.ParsePKCS8PrivateKey(enc)
    34  	if err != nil {
    35  		t.Fatal(err)
    36  	}
    37  	if !public.Equal(decoded.(crypto.Signer).Public()) {
    38  		t.Errorf("public key is not equal to itself after decoding: %v", public)
    39  	}
    40  	if !private.Equal(decoded) {
    41  		t.Errorf("private key is not equal to itself after decoding: %v", private)
    42  	}
    43  
    44  	other, _ := rsa.GenerateKey(rand.Reader, 512)
    45  	if public.Equal(other.Public()) {
    46  		t.Errorf("different public keys are Equal")
    47  	}
    48  	if private.Equal(other) {
    49  		t.Errorf("different private keys are Equal")
    50  	}
    51  }
    52  

View as plain text