test(sm2): add semantics vectors for public key decoding and PKE decryption

PublicKeyDecode pins the SEC 1 contract: G, 2G and (n-1)G decode to their coordinates, while compressed, hybrid and infinity encodings, 64- and 66-byte inputs, x or y equal to the field prime, and points off the curve in either coordinate are rejected.

PkeDecrypt builds ciphertexts from the GB/T 32918.4 equations with fixed nonces - its own KDF and C3 wiring - instead of calling Encrypt, so a wiring bug cannot become the expected value. Valid cases cover both splice orders, compressed C1, the ASN.1 form and plaintexts from 1 to 100 bytes; invalid cases flip C2 and C3, use an off-curve C1, truncate at 65 and 66 bytes, mismatch the splice order, and carry the issue #560 sample, now the single source of truth for that regression.

The consumer also asserts that a failure returns neither a key nor a plaintext, and that no case panics.

Regenerate with: go test ./internal/cryptotest/sm2vectors -run TestVectorsUpToDate -update
This commit is contained in:
Sun Yimin committed 2026-10-21 10:35:49 +08:00
1 parent 5b2d5c13a8
commit c7d9a02409
4 files changed
+632 -28

No files matched your search

+290
View File
@@ -14,8 +14,10 @@
package sm2vectors
import (
"bytes"
"crypto/elliptic"
"encoding/asn1"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
@@ -355,6 +357,276 @@ func buildVerifySM2() ([]vectors.Case, error) {
return cases, nil
}
// issue560Key and issue560Ciphertext are the sample from the failure report
// in issue #560. The ciphertext was produced by the pre-fix ADX/BMI2
// encryption path, so its shared point is already wrong and no private key can
// recover a plaintext.
const (
issue560Key = "339f68c658653c4172dadf19b375613a3e8af3ece001d82f7c6678694e9fff83"
issue560Ciphertext = "041982b3dffcfe9a66a51530925dcf390d267325cf12958373e54d236fe6acd9" +
"28a68414663325b43aa77d41ee2895d7a9a43942c1255b1dd045ed63c264d9d" +
"b3e46eab559da5b4" +
"bc61082947c615ddc966d9b5d901cb9d42205f26267c4f86bc0804a8fb146ef9452b2c4e21b1e719979"
)
// uncompressedPoint returns the SEC 1 uncompressed encoding of (x, y).
func uncompressedPoint(x, y *big.Int) []byte {
out := make([]byte, 65)
out[0] = 4
x.FillBytes(out[1:33])
y.FillBytes(out[33:])
return out
}
// buildPublicKeyDecode pins the SEC 1 decoding contract: a 65-byte
// uncompressed point is checked against the field range and the curve
// equation, and every other encoding is rejected.
func buildPublicKeyDecode() ([]vectors.Case, error) {
params := curve().Params()
p := params.P
one := big.NewInt(1)
zero := new(big.Int)
two := newSigner(big.NewInt(2))
minusOne := newSigner(new(big.Int).Sub(params.N, big.NewInt(1)))
offCurveY := new(big.Int).Xor(params.Gy, big.NewInt(1))
valid := []struct {
comment string
pub []byte
x, y *big.Int
}{
{"base point G", uncompressedPoint(params.Gx, params.Gy), params.Gx, params.Gy},
{"2G", uncompressedPoint(two.px, two.py), two.px, two.py},
{"(n-1)G", uncompressedPoint(minusOne.px, minusOne.py), minusOne.px, minusOne.py},
}
invalid := []struct {
comment string
pub []byte
}{
{"compressed even prefix", append([]byte{2}, fixed32(params.Gx)...)},
{"compressed odd prefix", append([]byte{3}, fixed32(params.Gx)...)},
{"hybrid prefix 06", append([]byte{6}, uncompressedPoint(params.Gx, params.Gy)[1:]...)},
{"hybrid prefix 07", append([]byte{7}, uncompressedPoint(params.Gx, params.Gy)[1:]...)},
{"point at infinity", []byte{0}},
{"truncated to 64 bytes", uncompressedPoint(params.Gx, params.Gy)[:64]},
{"trailing byte", append(uncompressedPoint(params.Gx, params.Gy), 0)},
{"x equals the field prime", uncompressedPoint(p, params.Gy)},
{"y equals the field prime", uncompressedPoint(params.Gx, p)},
{"zero coordinates", uncompressedPoint(zero, zero)},
{"y off the curve", uncompressedPoint(params.Gx, offCurveY)},
{"x off the curve", uncompressedPoint(one, params.Gy)},
}
var cases []vectors.Case
id := 0
for _, c := range valid {
id++
cases = append(cases, vectors.Case{
TCID: id,
Comment: c.comment,
Result: "valid",
Pub: hex.EncodeToString(c.pub),
X: hex.EncodeToString(fixed32(c.x)),
Y: hex.EncodeToString(fixed32(c.y)),
})
}
for _, c := range invalid {
id++
cases = append(cases, vectors.Case{
TCID: id,
Comment: c.comment,
Result: "invalid",
Pub: hex.EncodeToString(c.pub),
})
}
return cases, nil
}
// kdf implements the GB/T 32918.4 key derivation function: SM3 over the
// shared point encoding and a big-endian counter starting at one.
func kdf(z []byte, keyLen int) []byte {
out := make([]byte, 0, keyLen+sm3.Size)
var counter [4]byte
for i := uint32(1); len(out) < keyLen; i++ {
binary.BigEndian.PutUint32(counter[:], i)
h := sm3.New()
h.Write(z)
h.Write(counter[:])
out = append(out, h.Sum(nil)...)
}
return out[:keyLen]
}
func allZero(b []byte) bool {
var v byte
for _, c := range b {
v |= c
}
return v == 0
}
// encrypt derives the GB/T 32918.4 ciphertext for msg with nonce k. It does
// not call the code under test: C1 = kG, t = KDF(x2||y2), C2 = msg xor t and
// C3 = SM3(x2||msg||y2).
func (s *signer) encrypt(k *big.Int, msg []byte, compressed bool) (c1, c2, c3 []byte, err error) {
if len(msg) == 0 {
return nil, nil, nil, fmt.Errorf("empty plaintext")
}
x1, y1 := curve().ScalarBaseMult(k.Bytes())
x2, y2 := curve().ScalarMult(s.px, s.py, k.Bytes())
t := kdf(append(fixed32(x2), fixed32(y2)...), len(msg))
if allZero(t) {
return nil, nil, nil, fmt.Errorf("degenerate kdf output")
}
c2 = make([]byte, len(msg))
for i := range msg {
c2[i] = msg[i] ^ t[i]
}
h := sm3.New()
h.Write(fixed32(x2))
h.Write(msg)
h.Write(fixed32(y2))
c3 = h.Sum(nil)
if compressed {
prefix := byte(2)
if y1.Bit(0) == 1 {
prefix = 3
}
c1 = append([]byte{prefix}, fixed32(x1)...)
} else {
c1 = uncompressedPoint(x1, y1)
}
return c1, c2, c3, nil
}
// splice assembles the ciphertext parts in the requested order. ASN.1 uses
// the SEQUENCE { x1, y1, C3, C2 } form of GB/T 32918.4.
func splice(ordering string, c1, c2, c3 []byte) ([]byte, error) {
out := make([]byte, 0, len(c1)+len(c2)+len(c3))
switch ordering {
case "C1C3C2":
out = append(out, c1...)
out = append(out, c3...)
out = append(out, c2...)
case "C1C2C3":
out = append(out, c1...)
out = append(out, c2...)
out = append(out, c3...)
case "ASN1":
return asn1.Marshal(struct {
X, Y *big.Int
C3, C2 []byte
}{new(big.Int).SetBytes(c1[1:33]), new(big.Int).SetBytes(c1[33:]), c3, c2})
default:
return nil, fmt.Errorf("unknown ordering %q", ordering)
}
return out, nil
}
// buildPkeDecrypt pins decryption: the plaintext is recovered from C1, C2 and
// C3 exactly as GB/T 32918.4 specifies, and any alteration is a clean error.
func buildPkeDecrypt() ([]vectors.Case, error) {
recipient := newSigner(keyFixed)
priv := hex.EncodeToString(fixed32(keyFixed))
samples := []struct {
tcID int
comment string
msg []byte
nonce *big.Int
compressed bool
ordering string
}{
{1, "32-byte plaintext, C1C3C2", bytes.Repeat([]byte{0x11}, 32), big.NewInt(7), false, "C1C3C2"},
{2, "1-byte plaintext, C1C3C2", []byte{0x00}, big.NewInt(11), false, "C1C3C2"},
{3, "33-byte plaintext, C1C2C3", bytes.Repeat([]byte{0x33}, 33), big.NewInt(13), false, "C1C2C3"},
{4, "31-byte plaintext, C1C2C3", bytes.Repeat([]byte{0x55}, 31), big.NewInt(17), false, "C1C2C3"},
{5, "100-byte plaintext, compressed C1", bytes.Repeat([]byte{0x77}, 100), big.NewInt(19), true, "C1C3C2"},
{6, "ASN.1 encoding", bytes.Repeat([]byte{0x99}, 32), big.NewInt(23), false, "ASN1"},
}
var cases []vectors.Case
for _, s := range samples {
c1, c2, c3, err := recipient.encrypt(s.nonce, s.msg, s.compressed)
if err != nil {
return nil, fmt.Errorf("tc%d: %w", s.tcID, err)
}
ct, err := splice(s.ordering, c1, c2, c3)
if err != nil {
return nil, err
}
cases = append(cases, vectors.Case{
TCID: s.tcID,
Comment: s.comment,
Result: "valid",
Priv: priv,
Ciphertext: hex.EncodeToString(ct),
Ordering: s.ordering,
Expected: hex.EncodeToString(s.msg),
})
}
msg := bytes.Repeat([]byte{0x11}, 32)
c1, c2, c3, err := recipient.encrypt(big.NewInt(7), msg, false)
if err != nil {
return nil, err
}
base, err := splice("C1C3C2", c1, c2, c3)
if err != nil {
return nil, err
}
wrongOrder, err := splice("C1C2C3", c1, c2, c3)
if err != nil {
return nil, err
}
tamperedC3 := append([]byte(nil), base...)
tamperedC3[len(c1)] ^= 1
tamperedC2 := append([]byte(nil), base...)
tamperedC2[len(tamperedC2)-1] ^= 1
badPoint := append(uncompressedPoint(curve().Params().Gx, new(big.Int).Xor(curve().Params().Gy, big.NewInt(1))), c3...)
badPoint = append(badPoint, c2...)
badPrefix := append([]byte(nil), base...)
badPrefix[0] = 5
invalid := []struct {
tcID int
comment string
priv string
ct []byte
ordering string
}{
{7, "C3 altered in the low bit", priv, tamperedC3, "C1C3C2"},
{8, "C2 altered in the low bit", priv, tamperedC2, "C1C3C2"},
{9, "C1 off the curve", priv, badPoint, "C1C3C2"},
{10, "truncated to 65 bytes", priv, base[:65], "C1C3C2"},
{11, "truncated to 66 bytes", priv, base[:66], "C1C3C2"},
{12, "empty ciphertext", priv, nil, "C1C3C2"},
{13, "C1C2C3 decoded as C1C3C2", priv, wrongOrder, "C1C3C2"},
{14, "unsupported C1 prefix", priv, badPrefix, "C1C3C2"},
{15, "issue 560 corrupted ciphertext", issue560Key, mustHex(issue560Ciphertext), "C1C3C2"},
}
for _, c := range invalid {
cases = append(cases, vectors.Case{
TCID: c.tcID,
Comment: c.comment,
Result: "invalid",
Priv: c.priv,
Ciphertext: hex.EncodeToString(c.ct),
Ordering: c.ordering,
})
}
return cases, nil
}
func mustHex(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic("sm2vectors: invalid hex constant: " + err.Error())
}
return b
}
// BuildSuite builds the SM2 semantics suite. The output is deterministic;
// TestVectorsUpToDate regenerates it and compares it with the committed file.
func BuildSuite() (*vectors.Suite, error) {
@@ -366,6 +638,14 @@ func BuildSuite() (*vectors.Suite, error) {
if err != nil {
return nil, err
}
decoding, err := buildPublicKeyDecode()
if err != nil {
return nil, err
}
pke, err := buildPkeDecrypt()
if err != nil {
return nil, err
}
suite := &vectors.Suite{
Schema: vectors.SemanticsSchema,
Algorithm: "sm2p256v1",
@@ -381,6 +661,16 @@ func BuildSuite() (*vectors.Suite, error) {
Comment: "sm2.VerifyASN1WithSM2(pub, uid, msg, sig). e is recomputed from ZA and msg; an empty uid means the GM/T 0009 default identifier.",
Tests: withZA,
},
{
Type: "PublicKeyDecode",
Comment: "sm2.ParseUncompressedPublicKey. Only the 65-byte uncompressed form is accepted; the cases cover the field range, the curve equation and every rejected SEC 1 prefix.",
Tests: decoding,
},
{
Type: "PkeDecrypt",
Comment: "sm2.Decrypt and PrivateKey.Decrypt. Ciphertexts are built from the GB/T 32918.4 equations with fixed nonces, not by calling Encrypt, so a KDF or C3 wiring error cannot become the expected value.",
Tests: pke,
},
},
}
if err := suite.Validate(); err != nil {
+233
View File
@@ -254,6 +254,239 @@
"result": "invalid"
}
]
},
{
"type": "PublicKeyDecode",
"comment": "sm2.ParseUncompressedPublicKey. Only the 65-byte uncompressed form is accepted; the cases cover the field range, the curve equation and every rejected SEC 1 prefix.",
"tests": [
{
"tcId": 1,
"comment": "base point G",
"pub": "0432c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",
"x": "32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7",
"y": "bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",
"result": "valid"
},
{
"tcId": 2,
"comment": "2G",
"pub": "0456cefd60d7c87c000d58ef57fa73ba4d9c0dfa08c08a7331495c2e1da3f2bd5231b7e7e6cc8189f668535ce0f8eaf1bd6de84c182f6c8e716f780d3a970a23c3",
"x": "56cefd60d7c87c000d58ef57fa73ba4d9c0dfa08c08a7331495c2e1da3f2bd52",
"y": "31b7e7e6cc8189f668535ce0f8eaf1bd6de84c182f6c8e716f780d3a970a23c3",
"result": "valid"
},
{
"tcId": 3,
"comment": "(n-1)G",
"pub": "0432c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c743c8c95c0b098863a642311c9496deac2f56788239d5b8c0fd20cd1adec60f5f",
"x": "32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7",
"y": "43c8c95c0b098863a642311c9496deac2f56788239d5b8c0fd20cd1adec60f5f",
"result": "valid"
},
{
"tcId": 4,
"comment": "compressed even prefix",
"pub": "0232c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7",
"result": "invalid"
},
{
"tcId": 5,
"comment": "compressed odd prefix",
"pub": "0332c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7",
"result": "invalid"
},
{
"tcId": 6,
"comment": "hybrid prefix 06",
"pub": "0632c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",
"result": "invalid"
},
{
"tcId": 7,
"comment": "hybrid prefix 07",
"pub": "0732c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",
"result": "invalid"
},
{
"tcId": 8,
"comment": "point at infinity",
"pub": "00",
"result": "invalid"
},
{
"tcId": 9,
"comment": "truncated to 64 bytes",
"pub": "0432c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0",
"result": "invalid"
},
{
"tcId": 10,
"comment": "trailing byte",
"pub": "0432c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a000",
"result": "invalid"
},
{
"tcId": 11,
"comment": "x equals the field prime",
"pub": "04fffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffffbc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",
"result": "invalid"
},
{
"tcId": 12,
"comment": "y equals the field prime",
"pub": "0432c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7fffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffff",
"result": "invalid"
},
{
"tcId": 13,
"comment": "zero coordinates",
"pub": "0400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"result": "invalid"
},
{
"tcId": 14,
"comment": "y off the curve",
"pub": "0432c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a1",
"result": "invalid"
},
{
"tcId": 15,
"comment": "x off the curve",
"pub": "040000000000000000000000000000000000000000000000000000000000000001bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",
"result": "invalid"
}
]
},
{
"type": "PkeDecrypt",
"comment": "sm2.Decrypt and PrivateKey.Decrypt. Ciphertexts are built from the GB/T 32918.4 equations with fixed nonces, not by calling Encrypt, so a KDF or C3 wiring error cannot become the expected value.",
"tests": [
{
"tcId": 1,
"comment": "32-byte plaintext, C1C3C2",
"expected": "1111111111111111111111111111111111111111111111111111111111111111",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "04ddf092555409c19dfdbe86a75c139906a80198337744ee78cd27e384d9fcaf15847d18ffb38e87065cd6b6e9c12d2922037937707d6a49a2223b949657e52bc18d10ae926bafd926fa40e89ed700885732df7dbfcc66dcac223356740d89b01074bd589433ca8e273ae92940bf60bb7d39100d33cd557e418b9c4b098073743a",
"ordering": "C1C3C2",
"result": "valid"
},
{
"tcId": 2,
"comment": "1-byte plaintext, C1C3C2",
"expected": "00",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "0404b3cb10c9c6d8e27c1aab770f67f543125dcdd589c2ff82668c74d78ce20ace63516355287e39fe4918e5c02e2b0b930c94816e63c4bc72739a8fd805174a4bff6e247eaec6b76e698c3f492fe176285d34a50e48833adfe29f225a7ae9e8d508",
"ordering": "C1C3C2",
"result": "valid"
},
{
"tcId": 3,
"comment": "33-byte plaintext, C1C2C3",
"expected": "333333333333333333333333333333333333333333333333333333333333333333",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "04952072d6ff9c65bdfa804513275f58aa7bea65c6421e189e2b834f1d509b9cd0e6bb9804458bb70f1a473f8d9748f23858d1434ae934ba7503891e105e009b0001b7a41a38d5baa996d2579cdc03324de080ade4f24e3290a3265b12ec7ea5a0faf0e36fff62e0a227a9cf199a27902fb7859475f03b986c3d4e313a7a8a01dc93",
"ordering": "C1C2C3",
"result": "valid"
},
{
"tcId": 4,
"comment": "31-byte plaintext, C1C2C3",
"expected": "55555555555555555555555555555555555555555555555555555555555555",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "04dd18aa4aec26eac41c993f01115c57f7bf5113ab85b5ed4436969f8b77125e6a161e5851969da8223361493f76fac50f6cce6001d7c0b853e0180d54d4ae22211a89f23e3e3299811512af2e6ebf1f9a409ac14f19391a14410885d27ba2314a1132a215461e309583eef4dd86cf4f32e87e4bb58813dc2a5eb6ef3aabcb4c",
"ordering": "C1C2C3",
"result": "valid"
},
{
"tcId": 5,
"comment": "100-byte plaintext, compressed C1",
"expected": "77777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "03a68b2ec49d1921d0e2e0586bb5dc9419f7c96c55940a47261323f252e493952a73e32909db4832c71b581ed581c28b0ab9d18721816d92aee5e5192a4d6a82ca1daeed359b1d23933b00e4ee56fb6b916f433540de66922f1fe9b68e57831ceb26d46a4f0ab74a22a63fbe75ad38b958e42d41dfc9f204a7d3ab65fe02fb60033b86615ef509f45678405114a032983917bbd0a289396bdd7c72140f17cae101563de092",
"ordering": "C1C3C2",
"result": "valid"
},
{
"tcId": 6,
"comment": "ASN.1 encoding",
"expected": "9999999999999999999999999999999999999999999999999999999999999999",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "30818a022100ac8df677299e828815c07a8c04226fe3bb570a9f430ea7f64dbb2fcd069d45db022100aef82cf361db1c7130c43be69b23cc140e9b9643d766da337bd8b7c847718ce50420e5847f6d91dedcdb4adc96c103229d7e3d3c58da8da524a8baa9a9393c4762900420d27beb0f22640f1934d6b9d1037ae8a19570b1e40d3e85eec836a8a19923f4cc",
"ordering": "ASN1",
"result": "valid"
},
{
"tcId": 7,
"comment": "C3 altered in the low bit",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "04ddf092555409c19dfdbe86a75c139906a80198337744ee78cd27e384d9fcaf15847d18ffb38e87065cd6b6e9c12d2922037937707d6a49a2223b949657e52bc18c10ae926bafd926fa40e89ed700885732df7dbfcc66dcac223356740d89b01074bd589433ca8e273ae92940bf60bb7d39100d33cd557e418b9c4b098073743a",
"ordering": "C1C3C2",
"result": "invalid"
},
{
"tcId": 8,
"comment": "C2 altered in the low bit",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "04ddf092555409c19dfdbe86a75c139906a80198337744ee78cd27e384d9fcaf15847d18ffb38e87065cd6b6e9c12d2922037937707d6a49a2223b949657e52bc18d10ae926bafd926fa40e89ed700885732df7dbfcc66dcac223356740d89b01074bd589433ca8e273ae92940bf60bb7d39100d33cd557e418b9c4b098073743b",
"ordering": "C1C3C2",
"result": "invalid"
},
{
"tcId": 9,
"comment": "C1 off the curve",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "0432c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a18d10ae926bafd926fa40e89ed700885732df7dbfcc66dcac223356740d89b01074bd589433ca8e273ae92940bf60bb7d39100d33cd557e418b9c4b098073743a",
"ordering": "C1C3C2",
"result": "invalid"
},
{
"tcId": 10,
"comment": "truncated to 65 bytes",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "04ddf092555409c19dfdbe86a75c139906a80198337744ee78cd27e384d9fcaf15847d18ffb38e87065cd6b6e9c12d2922037937707d6a49a2223b949657e52bc1",
"ordering": "C1C3C2",
"result": "invalid"
},
{
"tcId": 11,
"comment": "truncated to 66 bytes",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "04ddf092555409c19dfdbe86a75c139906a80198337744ee78cd27e384d9fcaf15847d18ffb38e87065cd6b6e9c12d2922037937707d6a49a2223b949657e52bc18d",
"ordering": "C1C3C2",
"result": "invalid"
},
{
"tcId": 12,
"comment": "empty ciphertext",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ordering": "C1C3C2",
"result": "invalid"
},
{
"tcId": 13,
"comment": "C1C2C3 decoded as C1C3C2",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "04ddf092555409c19dfdbe86a75c139906a80198337744ee78cd27e384d9fcaf15847d18ffb38e87065cd6b6e9c12d2922037937707d6a49a2223b949657e52bc174bd589433ca8e273ae92940bf60bb7d39100d33cd557e418b9c4b098073743a8d10ae926bafd926fa40e89ed700885732df7dbfcc66dcac223356740d89b010",
"ordering": "C1C3C2",
"result": "invalid"
},
{
"tcId": 14,
"comment": "unsupported C1 prefix",
"priv": "3945208f7b2144b13f36e38ac6d39f95889393692860b51a42fb81ef4df7c5b8",
"ciphertext": "05ddf092555409c19dfdbe86a75c139906a80198337744ee78cd27e384d9fcaf15847d18ffb38e87065cd6b6e9c12d2922037937707d6a49a2223b949657e52bc18d10ae926bafd926fa40e89ed700885732df7dbfcc66dcac223356740d89b01074bd589433ca8e273ae92940bf60bb7d39100d33cd557e418b9c4b098073743a",
"ordering": "C1C3C2",
"result": "invalid"
},
{
"tcId": 15,
"comment": "issue 560 corrupted ciphertext",
"priv": "339f68c658653c4172dadf19b375613a3e8af3ece001d82f7c6678694e9fff83",
"ciphertext": "041982b3dffcfe9a66a51530925dcf390d267325cf12958373e54d236fe6acd928a68414663325b43aa77d41ee2895d7a9a43942c1255b1dd045ed63c264d9db3e46eab559da5b4bc61082947c615ddc966d9b5d901cb9d42205f26267c4f86bc0804a8fb146ef9452b2c4e21b1e719979",
"ordering": "C1C3C2",
"result": "invalid"
}
]
}
]
}
+109
View File
@@ -5,8 +5,10 @@
package sm2
import (
"bytes"
"crypto/ecdsa"
"encoding/hex"
"errors"
"fmt"
"math/big"
"testing"
@@ -26,6 +28,8 @@ func TestSemanticsVectors(t *testing.T) {
}
t.Run("VerifyDigest", func(t *testing.T) { testVerifyDigestVectors(t, suite) })
t.Run("VerifySM2", func(t *testing.T) { testVerifySM2Vectors(t, suite) })
t.Run("PublicKeyDecode", func(t *testing.T) { testPublicKeyDecodeVectors(t, suite) })
t.Run("PkeDecrypt", func(t *testing.T) { testPkeDecryptVectors(t, suite) })
}
func testVerifyDigestVectors(t *testing.T, suite *vectors.Suite) {
@@ -66,6 +70,99 @@ func testVerifySM2Vectors(t *testing.T, suite *vectors.Suite) {
}
}
func testPublicKeyDecodeVectors(t *testing.T, suite *vectors.Suite) {
group, err := suite.Group("PublicKeyDecode")
if err != nil {
t.Fatal(err)
}
for _, tc := range group.Tests {
t.Run(fmt.Sprintf("tc%d", tc.TCID), func(t *testing.T) {
data := semanticsHex(t, tc, "pub", tc.Pub)
var pub *ecdsa.PublicKey
err := semanticsCallErr(t, tc, func() error {
var err error
pub, err = ParseUncompressedPublicKey(data)
return err
})
if tc.Result == "invalid" {
if err == nil {
t.Fatalf("ParseUncompressedPublicKey() = (%x, %x), want an error: %s", pub.X, pub.Y, tc.Comment)
}
if pub != nil {
t.Fatalf("ParseUncompressedPublicKey() returned a key along with %v", err)
}
return
}
if err != nil {
t.Fatalf("ParseUncompressedPublicKey() error: %v: %s", err, tc.Comment)
}
wantX := semanticsInt(t, tc, "x", tc.X)
wantY := semanticsInt(t, tc, "y", tc.Y)
if pub.X.Cmp(wantX) != 0 || pub.Y.Cmp(wantY) != 0 {
t.Fatalf("ParseUncompressedPublicKey() = (%x, %x), want (%x, %x)", pub.X, pub.Y, wantX, wantY)
}
})
}
}
func testPkeDecryptVectors(t *testing.T, suite *vectors.Suite) {
group, err := suite.Group("PkeDecrypt")
if err != nil {
t.Fatal(err)
}
for _, tc := range group.Tests {
t.Run(fmt.Sprintf("tc%d", tc.TCID), func(t *testing.T) {
priv := semanticsPrivateKey(t, tc)
ct := semanticsOptionalHex(t, "ciphertext", tc.Ciphertext)
var plaintext []byte
err := semanticsCallErr(t, tc, func() error {
var err error
switch tc.Ordering {
case "", "C1C3C2":
plaintext, err = Decrypt(priv, ct)
case "C1C2C3":
plaintext, err = priv.Decrypt(nil, ct, NewPlainDecrypterOpts(C1C2C3))
case "ASN1":
plaintext, err = priv.Decrypt(nil, ct, ASN1DecrypterOpts)
default:
t.Fatalf("unknown ordering %q", tc.Ordering)
}
return err
})
if tc.Result == "invalid" {
if err == nil {
t.Fatalf("Decrypt() = %x, want an error: %s", plaintext, tc.Comment)
}
if len(plaintext) != 0 {
t.Fatalf("Decrypt() returned %x along with %v", plaintext, err)
}
// Everything past the initial length check must collapse into
// ErrDecryption, so callers cannot tell the failure apart.
if len(ct) > 65 && !errors.Is(err, ErrDecryption) {
t.Fatalf("Decrypt() error = %v, want ErrDecryption", err)
}
return
}
if err != nil {
t.Fatalf("Decrypt() error: %v: %s", err, tc.Comment)
}
if want := semanticsHex(t, tc, "expected", tc.Expected); !bytes.Equal(plaintext, want) {
t.Fatalf("Decrypt() = %x, want %x", plaintext, want)
}
})
}
}
func semanticsPrivateKey(t *testing.T, tc vectors.Case) *PrivateKey {
t.Helper()
d := semanticsInt(t, tc, "priv", tc.Priv)
priv := new(PrivateKey)
priv.D = d
priv.Curve = P256()
priv.X, priv.Y = priv.ScalarBaseMult(d.Bytes())
return priv
}
func semanticsPublicKey(t *testing.T, tc vectors.Case) *ecdsa.PublicKey {
t.Helper()
pub, err := ParseUncompressedPublicKey(semanticsHex(t, tc, "pub", tc.Pub))
@@ -100,6 +197,18 @@ func semanticsInt(t *testing.T, tc vectors.Case, name, value string) *big.Int {
return new(big.Int).SetBytes(semanticsHex(t, tc, name, value))
}
// semanticsCallErr runs one vector call that reports an error and turns a
// panic into a test failure that names the case.
func semanticsCallErr(t *testing.T, tc vectors.Case, call func() error) (err error) {
t.Helper()
defer func() {
if p := recover(); p != nil {
t.Fatalf("tc%d panicked: %v", tc.TCID, p)
}
}()
return call()
}
// semanticsCall runs one vector call and turns a panic into a test failure
// that names the case.
func semanticsCall(t *testing.T, tc vectors.Case, call func() bool) (got bool) {
-28
View File
@@ -331,34 +331,6 @@ func TestInvalidCiphertext(t *testing.T) {
}
}
// TestIssue560CorruptedCiphertextRejected pins the decryption sample from
// issue #560. The ciphertext was produced by the pre-fix AMD64 ADX/BMI2
// encryption path, whose carry-tail defect corrupted the shared point, so no
// private key can recover a plaintext: the C3 check must fail. The behaviour
// under test is a clean ErrDecryption on every code path, never a panic or a
// garbage plaintext.
func TestIssue560CorruptedCiphertextRejected(t *testing.T) {
key, err := hex.DecodeString("339f68c658653c4172dadf19b375613a3e8af3ece001d82f7c6678694e9fff83")
if err != nil {
t.Fatal(err)
}
ciphertext, err := hex.DecodeString("041982b3dffcfe9a66a51530925dcf390d267325cf12958373e54d236fe6acd9" +
"28a68414663325b43aa77d41ee2895d7a9a43942c1255b1dd045ed63c264d9db3e46eab559da5b4" +
"bc61082947c615ddc966d9b5d901cb9d42205f26267c4f86bc0804a8fb146ef9452b2c4e21b1e719979")
if err != nil {
t.Fatal(err)
}
priv := new(PrivateKey)
priv.D = new(big.Int).SetBytes(key)
priv.Curve = P256()
priv.X, priv.Y = priv.ScalarBaseMult(key)
if plaintext, err := Decrypt(priv, ciphertext); err != ErrDecryption {
t.Fatalf("Decrypt() = %x, %v; want ErrDecryption", plaintext, err)
}
}
func benchmarkEncrypt(b *testing.B, curve elliptic.Curve, plaintext []byte) {
r := bufio.NewReaderSize(rand.Reader, 1<<15)
priv, err := ecdsa.GenerateKey(curve, r)