| 1 |
// Package slhdsa_test tests the SLH-DSA implementation suitable for OpenPGP, experimental. |
| 2 |
package slhdsa_test |
| 3 |
|
| 4 |
import ( |
| 5 |
"crypto/rand" |
| 6 |
"io" |
| 7 |
"testing" |
| 8 |
|
| 9 |
"github.com/ProtonMail/go-crypto/openpgp/packet" |
| 10 |
"github.com/ProtonMail/go-crypto/openpgp/slhdsa" |
| 11 |
) |
| 12 |
|
| 13 |
var algorithms = map[string]packet.PublicKeyAlgorithm{ |
| 14 |
"SLH-DSA-SHAKE-128s": packet.PubKeyAlgoSlhdsaShake128s, |
| 15 |
"SLH-DSA-SHAKE-128f": packet.PubKeyAlgoSlhdsaShake128f, |
| 16 |
"SLH-DSA-SHAKE-256s": packet.PubKeyAlgoSlhdsaShake256s, |
| 17 |
} |
| 18 |
|
| 19 |
func TestValidate(t *testing.T) { |
| 20 |
for asymmName, asymmAlgo := range algorithms { |
| 21 |
t.Run(asymmName, func(t *testing.T) { |
| 22 |
testValidateAlgo(t, asymmAlgo) |
| 23 |
}) |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
func TestSignVerify(t *testing.T) { |
| 28 |
for asymmName, asymmAlgo := range algorithms { |
| 29 |
t.Run(asymmName, func(t *testing.T) { |
| 30 |
key := testGenerateKeyAlgo(t, asymmAlgo) |
| 31 |
testSignVerifyAlgo(t, key) |
| 32 |
}) |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
func testValidateAlgo(t *testing.T, algId packet.PublicKeyAlgorithm) { |
| 37 |
key := testGenerateKeyAlgo(t, algId) |
| 38 |
if err := slhdsa.Validate(key); err != nil { |
| 39 |
t.Fatalf("valid key marked as invalid: %s", err) |
| 40 |
} |
| 41 |
|
| 42 |
bin, err := key.PublicSlhdsa.MarshalBinary() |
| 43 |
if err != nil { |
| 44 |
t.Fatal(err) |
| 45 |
} |
| 46 |
bin[5] ^= 1 |
| 47 |
key.PublicSlhdsa, err = key.Slhdsa.UnmarshalBinaryPublicKey(bin) //PublicKeyFromBytes(bin) |
| 48 |
if err != nil { |
| 49 |
t.Fatal(err) |
| 50 |
} |
| 51 |
|
| 52 |
if err := slhdsa.Validate(key); err == nil { |
| 53 |
t.Fatalf("failed to detect invalid key") |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
func testGenerateKeyAlgo(t *testing.T, algId packet.PublicKeyAlgorithm) *slhdsa.PrivateKey { |
| 58 |
scheme, err := packet.GetSlhdsaSchemeFromAlgID(algId) |
| 59 |
if err != nil { |
| 60 |
t.Errorf("error getting SLH-DSA scheme: %s", err) |
| 61 |
} |
| 62 |
|
| 63 |
priv, err := slhdsa.GenerateKey(rand.Reader, uint8(algId), scheme) |
| 64 |
if err != nil { |
| 65 |
t.Fatal(err) |
| 66 |
} |
| 67 |
|
| 68 |
return priv |
| 69 |
} |
| 70 |
|
| 71 |
func testSignVerifyAlgo(t *testing.T, priv *slhdsa.PrivateKey) { |
| 72 |
digest := make([]byte, 32) |
| 73 |
_, err := io.ReadFull(rand.Reader, digest[:]) |
| 74 |
if err != nil { |
| 75 |
t.Fatal(err) |
| 76 |
} |
| 77 |
|
| 78 |
dSig, err := slhdsa.Sign(priv, digest) |
| 79 |
if err != nil { |
| 80 |
t.Errorf("error encrypting: %s", err) |
| 81 |
} |
| 82 |
|
| 83 |
result := slhdsa.Verify(&priv.PublicKey, digest, dSig) |
| 84 |
if !result { |
| 85 |
t.Error("unable to verify message") |
| 86 |
} |
| 87 |
} |