pkg/identity: support encode and decode functionality of Peer Identity information

This commit is contained in:
aligeti 2019-08-09 15:23:29 -04:00 committed by GitHub
parent 1f837c53eb
commit 7af05177e2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 0 deletions

View File

@ -9,6 +9,7 @@ import (
"crypto"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"fmt"
"io/ioutil"
"path/filepath"
@ -527,3 +528,41 @@ func backupPath(path string) string {
pathExt,
)
}
// EncodePeerIdentity encodes the complete idenitity chain to bytes
func EncodePeerIdentity(pi *PeerIdentity) []byte {
var chain []byte
chain = append(chain, pi.Leaf.Raw...)
chain = append(chain, pi.CA.Raw...)
for _, cert := range pi.RestChain {
chain = append(chain, cert.Raw...)
}
return chain
}
// DecodePeerIdentity Decodes the bytes into complete idenitity chain
func DecodePeerIdentity(ctx context.Context, chain []byte) (_ *PeerIdentity, err error) {
defer mon.Task()(&ctx)(&err)
var certs []*x509.Certificate
for len(chain) > 0 {
var raw asn1.RawValue
var err error
chain, err = asn1.Unmarshal(chain, &raw)
if err != nil {
return nil, Error.Wrap(err)
}
cert, err := pkcrypto.CertFromDER(raw.FullBytes)
if err != nil {
return nil, Error.Wrap(err)
}
certs = append(certs, cert)
}
if len(certs) < 2 {
return nil, Error.New("not enough certificates")
}
return PeerIdentityFromChain(certs)
}

View File

@ -304,3 +304,22 @@ func TestManageableFullIdentity_Revoke(t *testing.T) {
err = rev.Verify(manageableFullIdentity.CA.Cert)
require.NoError(t, err)
}
func TestEncodeDecodePeerIdentity(t *testing.T) {
ctx := testcontext.New(t)
defer ctx.Cleanup()
peerID, err := testidentity.NewTestIdentity(ctx)
require.NoError(t, err)
pi := peerID.PeerIdentity()
// encode the peer identity
encodedPiBytes := identity.EncodePeerIdentity(pi)
assert.NotNil(t, encodedPiBytes)
// decode the peer identity
decodedPi, err := identity.DecodePeerIdentity(ctx, encodedPiBytes)
assert.NoError(t, err)
// again encode the above decoded peer identity and compare
decodedPiBytes := identity.EncodePeerIdentity(decodedPi)
assert.Equal(t, encodedPiBytes, decodedPiBytes)
}