// SM2 standard test vectors. // // Vectors are taken from GM/T 0003.5-2012 Appendix A.2 (signature example on // the sm2p256v1 recommended curve). Passing these proves the implementation is // interoperable with other SM2 stacks, not merely self-consistent. package crypto import ( "bytes" "encoding/hex" "math/big" "strings" "testing" ) func mustHex(t *testing.T, s string) []byte { t.Helper() b, err := hex.DecodeString(strings.ReplaceAll(s, " ", "")) if err != nil { t.Fatalf("bad hex literal: %v", err) } return b } const ( vecPrivD = "3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8" vecPubX = "09F9DF311E5421A150DD7D161E4BC5C672179FAD1833FC076BB08FF356F35020" vecPubY = "CCEA490CE26775A52DC6EA718CC1AA600AED05FBF35E084A6632F6072DA9AD13" vecMsg = "message digest" vecSigR = "F5A03B0648D2C4630EEAC513E1BB81A15944DA3827D5B74143AC7EACEEE720B3" vecSigS = "B1B6AA29DF212FD8763182BC0D421CA1BB9038FD1F7F42D4840B69C485BBC1AA" ) // TestSM2PublicKeyDerivationVector checks that [dA]G matches the published // public key, i.e. the curve arithmetic and base point are correct. func TestSM2PublicKeyDerivationVector(t *testing.T) { d := mustHex(t, vecPrivD) x, y := SM2P256V1.ScalarBaseMult(d) wantX := new(big.Int).SetBytes(mustHex(t, vecPubX)) wantY := new(big.Int).SetBytes(mustHex(t, vecPubY)) if x.Cmp(wantX) != 0 { t.Errorf("SM2 [dA]G x mismatch:\n got %064X\nwant %064X", x, wantX) } if y.Cmp(wantY) != 0 { t.Errorf("SM2 [dA]G y mismatch:\n got %064X\nwant %064X", y, wantY) } } // TestSM2ComputeZAStructure checks the structural properties of ZA that are // easy to get wrong. The value itself is validated indirectly but far more // strictly by TestSM2VerifyStandardVector: if ENTL, the default ID, or the // xA/yA inputs were wrong, the reference signature would not verify. func TestSM2ComputeZAStructure(t *testing.T) { // GB/T 32918.2-2016 fixes the default ID at 16 bytes, ENTL = 0x0080. if len(SM2UserID) != 16 || string(SM2UserID) != "1234567812345678" { t.Errorf("SM2UserID should be the 16-byte default ID, got %q", SM2UserID) } pubX := new(big.Int).SetBytes(mustHex(t, vecPubX)) pubY := new(big.Int).SetBytes(mustHex(t, vecPubY)) za := SM2ComputeZA(SM2P256V1Params, SM2UserID, pubX, pubY) if len(za) != 32 { t.Fatalf("ZA should be 32 bytes, got %d", len(za)) } // ZA must depend on the public key: a different key must give a different ZA. other, err := GenerateSM2Key() if err != nil { t.Fatalf("failed to generate key: %v", err) } zaOther := SM2ComputeZA(SM2P256V1Params, SM2UserID, other.PublicKey.X, other.PublicKey.Y) if bytes.Equal(za, zaOther) { t.Error("ZA does not depend on the public key (xA/yA missing from the hash input)") } // ZA must depend on the ID. zaAltID := SM2ComputeZA(SM2P256V1Params, []byte("8765432187654321"), pubX, pubY) if bytes.Equal(za, zaAltID) { t.Error("ZA does not depend on the user ID") } } // TestSM2VerifyStandardVector verifies the reference (r, s) pair. A signature // produced by any conformant SM2 implementation must validate here. func TestSM2VerifyStandardVector(t *testing.T) { pub := &SM2PublicKey{ CurveParams: *SM2P256V1Params, X: new(big.Int).SetBytes(mustHex(t, vecPubX)), Y: new(big.Int).SetBytes(mustHex(t, vecPubY)), } sig := append(mustHex(t, vecSigR), mustHex(t, vecSigS)...) if !SM2Verify(pub, []byte(vecMsg), sig) { t.Error("SM2: failed to verify GM/T 0003.5-2012 A.2 reference signature") } } // TestSM2SignVerifyRoundTripWithVectorKey signs with the reference private key // and verifies with the reference public key. func TestSM2SignVerifyRoundTripWithVectorKey(t *testing.T) { priv, err := ParseSM2PrivateKey(mustHex(t, vecPrivD)) if err != nil { t.Fatalf("SM2: failed to parse reference private key: %v", err) } wantX := new(big.Int).SetBytes(mustHex(t, vecPubX)) if priv.PublicKey.X.Cmp(wantX) != 0 { t.Fatal("SM2: derived public key does not match the reference vector") } sig, err := SM2Sign(priv, []byte(vecMsg)) if err != nil { t.Fatalf("SM2: sign failed: %v", err) } if !SM2Verify(priv.PublicKey, []byte(vecMsg), sig) { t.Error("SM2: freshly generated signature failed verification") } // A different message must not validate. if SM2Verify(priv.PublicKey, []byte("message digest!"), sig) { t.Error("SM2: signature validated against the wrong message") } } // TestSM3StandardVectors checks SM3 against GB/T 32905-2016 examples. func TestSM3StandardVectors(t *testing.T) { cases := []struct { in string want string }{ {"abc", "66C7F0F462EEEDD9D1F2D46BDC10E4E24167C4875CF2F7A2297DA02B8F4BA8E0"}, { "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd", "DEBE9FF92275B8A138604889C18E5A4D6FDB70E5387E5765293DCBA39C0C5732", }, } for _, c := range cases { got := SM3([]byte(c.in)) want := mustHex(t, c.want) if !bytes.Equal(got, want) { t.Errorf("SM3(%q) mismatch:\n got %X\nwant %X", c.in, got, want) } } } // TestSM4StandardVector checks the SM4 block cipher against GB/T 32907-2016. func TestSM4StandardVector(t *testing.T) { key := mustHex(t, "0123456789ABCDEFFEDCBA9876543210") plain := mustHex(t, "0123456789ABCDEFFEDCBA9876543210") want := mustHex(t, "681EDF34D206965E86B3E94F536E4246") block, err := NewSM4(key) if err != nil { t.Fatalf("SM4: failed to create cipher: %v", err) } got := make([]byte, 16) block.Encrypt(got, plain) if !bytes.Equal(got, want) { t.Errorf("SM4 encrypt mismatch:\n got %X\nwant %X", got, want) } back := make([]byte, 16) block.Decrypt(back, got) if !bytes.Equal(back, plain) { t.Errorf("SM4 decrypt mismatch:\n got %X\nwant %X", back, plain) } } // TestSM4MillionIterationVector runs the second official GB/T 32907-2016 // example: encrypting the plaintext 1,000,000 times with the same key. func TestSM4MillionIterationVector(t *testing.T) { if testing.Short() { t.Skip("skipping 1e6-iteration SM4 vector in short mode") } key := mustHex(t, "0123456789ABCDEFFEDCBA9876543210") buf := mustHex(t, "0123456789ABCDEFFEDCBA9876543210") want := mustHex(t, "595298C7C6FD271F0402F804C33D3F66") block, err := NewSM4(key) if err != nil { t.Fatalf("SM4: failed to create cipher: %v", err) } for i := 0; i < 1000000; i++ { block.Encrypt(buf, buf) } if !bytes.Equal(buf, want) { t.Errorf("SM4 1e6-iteration mismatch:\n got %X\nwant %X", buf, want) } } // TestSM4GCMDetectsTamperingBeyondFirstBlock is a regression test for a GHASH // that only authenticated the first 16 bytes. Any byte of the ciphertext, at // any offset, must be covered by the tag. func TestSM4GCMDetectsTamperingBeyondFirstBlock(t *testing.T) { key := mustHex(t, "0123456789ABCDEFFEDCBA9876543210") nonce := mustHex(t, "000102030405060708090A0B") plaintext := []byte("the quick brown fox jumps over the lazy dog, twice over in fact") aad := []byte("associated-data") gcm, err := NewSM4GCM(key, nonce) if err != nil { t.Fatalf("SM4-GCM: %v", err) } sealed := gcm.Seal(nil, nonce, plaintext, aad) // Sanity: it must decrypt cleanly first. got, err := gcm.Open(nil, nonce, sealed, aad) if err != nil { t.Fatalf("SM4-GCM: unexpected open failure: %v", err) } if !bytes.Equal(got, plaintext) { t.Fatal("SM4-GCM: round-trip mismatch") } // Flip one bit at every ciphertext offset; all must be rejected. for i := 0; i < len(sealed); i++ { tampered := append([]byte(nil), sealed...) tampered[i] ^= 0x01 if _, err := gcm.Open(nil, nonce, tampered, aad); err == nil { t.Errorf("SM4-GCM: tampering at byte %d was not detected", i) } } // Modified AAD must also be rejected. if _, err := gcm.Open(nil, nonce, sealed, []byte("associated-datb")); err == nil { t.Error("SM4-GCM: AAD tampering was not detected") } // A different nonce must be rejected. otherNonce := mustHex(t, "0102030405060708090A0B0C") if _, err := gcm.Open(nil, otherNonce, sealed, aad); err == nil { t.Error("SM4-GCM: wrong nonce was not detected") } } // TestSM4GCMNonceIsNotReused guards against the fixed zero-nonce bug: two // encryptions of the same plaintext under the same key must differ. func TestSM4GCMNonceIsNotReused(t *testing.T) { cs := GetCipherSuiteByType(CipherSuiteGM) key := mustHex(t, "0123456789ABCDEFFEDCBA9876543210") plaintext := []byte("repeat me") a, err := cs.Encrypt(key, plaintext, nil) if err != nil { t.Fatalf("encrypt: %v", err) } b, err := cs.Encrypt(key, plaintext, nil) if err != nil { t.Fatalf("encrypt: %v", err) } if bytes.Equal(a, b) { t.Error("GM suite reuses a fixed nonce: identical plaintexts produced identical ciphertexts") } for _, ct := range [][]byte{a, b} { out, err := cs.Decrypt(key, ct, nil) if err != nil { t.Fatalf("decrypt: %v", err) } if !bytes.Equal(out, plaintext) { t.Error("GM suite round-trip mismatch") } } } // TestHKDFSM3LongOutputIsNotRepeated guards against the old implementation that // filled long outputs by repeating a single 32-byte block. func TestHKDFSM3LongOutputIsNotRepeated(t *testing.T) { cs := GetCipherSuiteByType(CipherSuiteGM) out, err := cs.DeriveKey([]byte("salt"), []byte("input key material"), "test", 96) if err != nil { t.Fatalf("DeriveKey: %v", err) } if len(out) != 96 { t.Fatalf("expected 96 bytes, got %d", len(out)) } if bytes.Equal(out[0:32], out[32:64]) || bytes.Equal(out[32:64], out[64:96]) { t.Error("HKDF-SM3 repeats its first block instead of expanding") } // Determinism. again, err := cs.DeriveKey([]byte("salt"), []byte("input key material"), "test", 96) if err != nil { t.Fatalf("DeriveKey: %v", err) } if !bytes.Equal(out, again) { t.Error("HKDF-SM3 is not deterministic") } // Different info must give different output. other, err := cs.DeriveKey([]byte("salt"), []byte("input key material"), "other", 96) if err != nil { t.Fatalf("DeriveKey: %v", err) } if bytes.Equal(out, other) { t.Error("HKDF-SM3 ignores the info parameter") } }