github.com/lestrrat-go/jwx/v2@v2.0.21/x25519/x25519_test.go (about)

     1  package x25519_test
     2  
     3  import (
     4  	"encoding/hex"
     5  	"testing"
     6  
     7  	"github.com/lestrrat-go/jwx/v2/x25519"
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestGenerateKey(t *testing.T) {
    12  	t.Run("x25519.GenerateKey(nil)", func(t *testing.T) {
    13  		_, _, err := x25519.GenerateKey(nil)
    14  		if !assert.NoError(t, err, `x25519.GenerateKey should work even if argument is nil`) {
    15  			return
    16  		}
    17  	})
    18  	t.Run("x25519.NewKeyFromSeed(wrongSeedLength)", func(t *testing.T) {
    19  		dummy := make([]byte, x25519.SeedSize-1)
    20  		_, err := x25519.NewKeyFromSeed(dummy)
    21  		if !assert.Error(t, err, `wrong seed size should result in error`) {
    22  			return
    23  		}
    24  	})
    25  }
    26  
    27  func TestNewKeyFromSeed(t *testing.T) {
    28  	// These test vectors are from RFC7748 Section 6.1
    29  	const alicePrivHex = `77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a`
    30  	const alicePubHex = `8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a`
    31  	const bobPrivHex = `5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb`
    32  	const bobPubHex = `de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f`
    33  
    34  	alicePrivSeed, err := hex.DecodeString(alicePrivHex)
    35  	if !assert.NoError(t, err, `alice seed decoded`) {
    36  		return
    37  	}
    38  	alicePriv, err := x25519.NewKeyFromSeed(alicePrivSeed)
    39  	if !assert.NoError(t, err, `alice private key`) {
    40  		return
    41  	}
    42  
    43  	alicePub := alicePriv.Public().(x25519.PublicKey)
    44  	if !assert.Equal(t, hex.EncodeToString(alicePub), alicePubHex, `alice public key`) {
    45  		return
    46  	}
    47  
    48  	bobPrivSeed, err := hex.DecodeString(bobPrivHex)
    49  	if !assert.NoError(t, err, `bob seed decoded`) {
    50  		return
    51  	}
    52  	bobPriv, err := x25519.NewKeyFromSeed(bobPrivSeed)
    53  	if !assert.NoError(t, err, `bob private key`) {
    54  		return
    55  	}
    56  
    57  	bobPub := bobPriv.Public().(x25519.PublicKey)
    58  	if !assert.Equal(t, hex.EncodeToString(bobPub), bobPubHex, `bob public key`) {
    59  		return
    60  	}
    61  
    62  	if !assert.True(t, bobPriv.Equal(bobPriv), `bobPriv should equal bobPriv`) {
    63  		return
    64  	}
    65  	if !assert.True(t, bobPub.Equal(bobPub), `bobPub should equal bobPub`) {
    66  		return
    67  	}
    68  	if !assert.False(t, bobPriv.Equal(bobPub), `bobPriv should NOT equal bobPub`) {
    69  		return
    70  	}
    71  	if !assert.False(t, bobPub.Equal(bobPriv), `bobPub should NOT equal bobPriv`) {
    72  		return
    73  	}
    74  }