| 1 |
package examples_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto" |
| 5 |
"crypto/ecdsa" |
| 6 |
"crypto/elliptic" |
| 7 |
"crypto/rand" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/lestrrat-go/dsig" |
| 11 |
"github.com/stretchr/testify/require" |
| 12 |
) |
| 13 |
|
| 14 |
func TestRegisterECDSACurve(t *testing.T) { |
| 15 |
// Define a custom algorithm name |
| 16 |
customAlg := "CUSTOM_P256_WITH_SHA256" |
| 17 |
|
| 18 |
// Register P-256 as a "custom" algorithm (for demonstration) |
| 19 |
err := dsig.RegisterAlgorithm(customAlg, dsig.AlgorithmInfo{ |
| 20 |
Family: dsig.ECDSA, |
| 21 |
Meta: dsig.ECDSAFamilyMeta{ |
| 22 |
Hash: crypto.SHA256, |
| 23 |
}, |
| 24 |
}) |
| 25 |
require.NoError(t, err) |
| 26 |
|
| 27 |
// Test that our custom algorithm now works |
| 28 |
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 29 |
require.NoError(t, err) |
| 30 |
|
| 31 |
payload := []byte("test message") |
| 32 |
|
| 33 |
// Sign with our custom algorithm |
| 34 |
sig, err := dsig.Sign(privKey, customAlg, payload, nil) |
| 35 |
require.NoError(t, err, "Should be able to sign with registered custom algorithm") |
| 36 |
|
| 37 |
// Verify with our custom algorithm |
| 38 |
err = dsig.Verify(&privKey.PublicKey, customAlg, payload, sig) |
| 39 |
require.NoError(t, err, "Should be able to verify with registered custom algorithm") |
| 40 |
|
| 41 |
// Test with different curve - this will work but may not be interoperable |
| 42 |
// with systems expecting P-256 for this algorithm name |
| 43 |
p384Key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) |
| 44 |
require.NoError(t, err) |
| 45 |
|
| 46 |
// This will work at the crypto level but may not be what you want for interoperability |
| 47 |
sig2, err := dsig.Sign(p384Key, customAlg, payload, nil) |
| 48 |
require.NoError(t, err, "Sign works with any ECDSA key at crypto level") |
| 49 |
|
| 50 |
// Verify will work too |
| 51 |
err = dsig.Verify(&p384Key.PublicKey, customAlg, payload, sig2) |
| 52 |
require.NoError(t, err, "Verify works with matching curve") |
| 53 |
|
| 54 |
// Cross-curve verification will fail naturally |
| 55 |
err = dsig.Verify(&privKey.PublicKey, customAlg, payload, sig2) |
| 56 |
require.Error(t, err, "Cross-curve verification fails naturally") |
| 57 |
} |