Skip to content
Snippets Groups Projects
Commit 742dbe09 authored by David Stainton's avatar David Stainton
Browse files

Add PublicKey's Bytes and FromBytes + tests

parent 69aad094
No related branches found
No related tags found
2 merge requests!23Channels Implementation,!21Add PublicKey's Bytes and FromBytes + tests
...@@ -20,7 +20,9 @@ package rsa ...@@ -20,7 +20,9 @@ package rsa
import ( import (
"crypto" "crypto"
gorsa "crypto/rsa" gorsa "crypto/rsa"
"encoding/binary"
"io" "io"
"math/big"
"gitlab.com/xx_network/crypto/large" "gitlab.com/xx_network/crypto/large"
_ "golang.org/x/crypto/blake2b" _ "golang.org/x/crypto/blake2b"
...@@ -128,6 +130,22 @@ func (p *PrivateKey) GetE() int { ...@@ -128,6 +130,22 @@ func (p *PrivateKey) GetE() int {
return p.E return p.E
} }
// Bytes returns the PublicKey as a byte slice.
func (p *PublicKey) Bytes() []byte {
buf := make([]byte, 16)
binary.PutVarint(buf, int64(p.GetE()))
return append(buf, p.PublicKey.N.Bytes()...)
}
// FromBytes loads the given byte slice into the PublicKey.
func (p *PublicKey) FromBytes(b []byte) error {
e, _ := binary.Varint(b[:8])
p.E = int(e)
p.N = new(big.Int)
p.N.SetBytes(b[8:])
return nil
}
// GetN returns the RSA Public Key modulus // GetN returns the RSA Public Key modulus
func (p *PublicKey) GetN() *large.Int { func (p *PublicKey) GetN() *large.Int {
return large.NewIntFromBigInt(p.N) return large.NewIntFromBigInt(p.N)
......
...@@ -218,3 +218,21 @@ func TestIsValidSignature(t *testing.T) { ...@@ -218,3 +218,21 @@ func TestIsValidSignature(t *testing.T) {
"\n\t Signer's public key: %+v", len(matchingSig), serverPubKey.Size()) "\n\t Signer's public key: %+v", len(matchingSig), serverPubKey.Size())
} }
} }
func TestRSABytesFromBytes(t *testing.T) {
serverPrivKey, err := GenerateKey(rand.Reader, 4096)
if err != nil {
t.Errorf("Failed to generate private key: %+v", err)
}
serverPubKey := serverPrivKey.GetPublic()
serverPubKeyBytes := serverPubKey.Bytes()
serverPubKey2 := new(PublicKey)
err = serverPubKey2.FromBytes(serverPubKeyBytes)
if err != nil {
t.Fatal(err)
}
serverPubKey2Bytes := serverPubKey2.Bytes()
if !bytes.Equal(serverPubKeyBytes, serverPubKey2Bytes) {
t.Fatal("byte slices don't match")
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment