### SM4 SBOX GFNI Implementation Example Source: https://github.com/emmansun/gmsm/wiki/SM4-with-GFNI Example code for SM4 S-box implementation using GFNI instructions. This approach utilizes single instructions for Affine Transformation and its inverse, offering potential performance benefits. ```go package main import ( "fmt" "testing" ) func main() { fmt.Println("Hello, World!") } func TestSM4GFNI(t *testing.T) { // Placeholder for actual test logic assert := testing.T{} assert.Helper() // Example: assert.Equal(t, expected, actual, "Test failed") } ``` -------------------------------- ### Example Stealth Address Generation (Go) Source: https://github.com/emmansun/gmsm/wiki/stealth-addresses-(隐身地址) Illustrates the generation of a stealth address using ECDH in Go. This snippet is part of the reference implementation tests. ```go func TestGenerateStealthAddress(t *testing.T) { privateKey, _ := hexutil.Decode("0x1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f809") publicKey, _ := hexutil.Decode("0x02a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f809") stealthAddress, err := GenerateStealthAddress(privateKey, publicKey) if err != nil { t := { "message": "Failed to generate stealth address", "error": err.Error(), } panic(t.Errorf("%v", t)) } fmt.Printf("Stealth Address: %s\n", hexutil.Encode(stealthAddress)) } ``` -------------------------------- ### HSMPrivateKey Sign() Method Implementation Source: https://github.com/emmansun/gmsm/blob/develop/docs/sm2-en.md Example implementation of the Sign() method for an HSM private key. It handles SM2-specific signing options and delegates the actual signing to the HSM. Requires 'crypto/ecdsa' and 'github.com/emmansun/gmsm/sm2'. ```go func (h *HSMPrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { // Check if opts is SM2-specific if sm2Opts, ok := opts.(*sm2.SM2SignerOption); ok && sm2Opts.ForceGMSign { // Treat digest as raw message, calculate SM2 hash hash, err := sm2.CalculateSM2Hash( h.Public().(*ecdsa.PublicKey), digest, sm2Opts.UID, ) if err != nil { return nil, err } // Call HSM API to sign the hash return h.hsmSignHash(hash) } // Treat digest as pre-computed hash return h.hsmSignHash(digest) } ``` -------------------------------- ### EC-ElGamal Encryption Example Source: https://github.com/emmansun/gmsm/blob/develop/docs/sm2-en.md Illustrates the use of EC-ElGamal with SM2 for partially homomorphic encryption, supporting addition on encrypted data. ```go // Electronic voting: Add encrypted votes without decryption encryptedVote1 := Encrypt(publicKey, 1) // Vote "yes" encryptedVote2 := Encrypt(publicKey, 0) // Vote "no" encryptedTotal := Add(encryptedVote1, encryptedVote2) totalVotes := Decrypt(privateKey, encryptedTotal) // Result: 1 ``` -------------------------------- ### SM4 SBOX AESNI Implementation Example Source: https://github.com/emmansun/gmsm/wiki/SM4-with-GFNI Example code demonstrating SM4 S-box implementation using AESNI instructions. This typically involves multiple instructions for affine transformations and optional Shift Rows Inverse. ```go package main import ( "fmt" "testing" ) func main() { fmt.Println("Hello, World!") } func TestSM4(t *testing.T) { // Placeholder for actual test logic tassert := testing.T{} assert.Helper() // Example: assert.Equal(t, expected, actual, "Test failed") } ``` -------------------------------- ### SM3 Message DWORD Loading and XOR (AVX) Source: https://github.com/emmansun/gmsm/wiki/SM3性能优化 This example illustrates loading message DWORDs and performing XOR operations for SM3, potentially handling multiple DWORDs from the stack. ```assembly VMOVDQU XDWORD0, (_XFER + 0*32)(SP)(SRND*1) VPXOR XDWORD0, XDWORD1, XFER VMOVDQU XFER, (_XFER + 1*32)(SP)(SRND*1) ``` -------------------------------- ### TLS 1.3 Hybrid Key Exchange Client Setup Source: https://github.com/emmansun/gmsm/blob/develop/docs/pqc.md Initializes a hybrid key exchange object for TLS 1.3 and generates client key shares, including a hybrid share and a fallback ECDH share. ```go import "github.com/emmansun/gmsm/tls13" // 创建混合密钥交换对象 ke, err := tls13.NewKeyExchange(tls13.X25519MLKEM768) // 生成 ClientHello 密钥共享 // clientKeyShares[0] 为混合密钥共享,clientKeyShares[1] 为纯 ECDH 后备 priv, clientKeyShares, err := ke.KeyShares(rand.Reader) // 发送 clientKeyShares[0].Data 到服务器(在 ClientHello 中) // 服务器响应包含 serverKeyShare // 从服务器响应中计算共享密钥 sharedSecret, err := ke.ClientSharedSecret(priv, serverKeyShare.Data) ``` -------------------------------- ### SM2 EncryptUtil Example Source: https://github.com/emmansun/gmsm/blob/develop/docs/cfca.md Example usage of EncryptUtil for SM2 encryption, defaulting to ASN.1 encoding format. ```java EncryptUtil.encrypt ``` -------------------------------- ### Get SLH-DSA Parameter Sets Source: https://github.com/emmansun/gmsm/blob/develop/docs/pqc.md Shows how to obtain SLH-DSA parameter sets. Parameters can be directly referenced via package variables, looked up by name, or by their OID. ```Go import "github.com/emmansun/gmsm/slhdsa" // 通过包级变量直接引用 params := &slhdsa.SLHDSA128SmallSHA2 // 通过名称查找 params, ok := slhdsa.GetParameterSet("SLH-DSA-SHA2-128s") // 通过 OID 查找 params, ok = slhdsa.GetParameterSetByOID(oid) ``` -------------------------------- ### TLS 1.3 Hybrid Key Exchange Server Setup Source: https://github.com/emmansun/gmsm/blob/develop/docs/pqc.md Initializes a hybrid key exchange object and calculates the server's shared secret using the client's key share data. ```go ke, err := tls13.NewKeyExchange(tls13.X25519MLKEM768) // 从客户端密钥共享计算服务器共享密钥 sharedSecret, serverKeyShare, err := ke.ServerSharedSecret(rand.Reader, clientKeyShare) // serverKeyShare.Data 放入 ServerHello 返回客户端 ``` -------------------------------- ### HSMPrivateKey Public() Method Implementation Source: https://github.com/emmansun/gmsm/blob/develop/docs/sm2-en.md Example implementation of the Public() method for an HSM private key. It should return the associated public key, which is typically retrieved from the HSM or stored during initialization. ```go func (h *HSMPrivateKey) Public() crypto.PublicKey { // Return the public key associated with this private key // This should be retrieved from the HSM or stored during initialization return h.publicKey } ``` -------------------------------- ### SM2 EncryptFileBySM2 Example Source: https://github.com/emmansun/gmsm/blob/develop/docs/cfca.md Example usage of EncryptFileBySM2 for SM2 file encryption, defaulting to C1C3C2 format without the 0x04 prefix. ```java EncryptUtil.encryptFileBySM2 ``` -------------------------------- ### HSMPrivateKey Decrypt() Method Implementation Source: https://github.com/emmansun/gmsm/blob/develop/docs/sm2-en.md Example implementation of the Decrypt() method for an HSM private key. It delegates the decryption operation to the HSM's SDK/API. ```go func (h *HSMPrivateKey) Decrypt(rand io.Reader, msg []byte, opts crypto.DecrypterOpts) ([]byte, error) { // Call SDF/SKF API to perform decryption // Example: SDF_InternalDecrypt_ECC(sessionHandle, keyIndex, ciphertext) plaintext, err := h.sdkClient.Decrypt(h.keyHandle, msg) if err != nil { return nil, fmt.Errorf("HSM decryption failed: %w", err) } return plaintext, nil } ``` -------------------------------- ### ML-KEM Serialization Source: https://github.com/emmansun/gmsm/blob/develop/docs/pqc-en.md Handles serialization for ML-KEM keys. Provides methods to get the seed, full expanded key, or encapsulation key bytes, and to restore an encapsulation key from bytes. ```go // Decapsulation key seed := dk.Seed() // 64 bytes — recommended storage format expanded := dk.Bytes() // Full expanded format // Encapsulation key (for distribution to the peer) ekBytes := dk.EncapsulationKey().Bytes() // Restore an encapsulation key from bytes ek, err = mlkem.NewEncapsulationKey768(ekBytes) ``` -------------------------------- ### Run ML-KEM Benchmarks Source: https://github.com/emmansun/gmsm/blob/develop/mlkem/README.md Runs benchmarks for the ML-KEM package on the native hardware. The -bench=. flag runs all benchmarks, and -benchtime=3s sets the benchmark duration to 3 seconds. ```shell go test -bench=. -benchtime=3s ./mlkem/ ``` -------------------------------- ### SM2 EncryptMessageBySM2 Example Source: https://github.com/emmansun/gmsm/blob/develop/docs/cfca.md Example usage of EncryptMessageBySM2 for SM2 encryption, defaulting to C1C3C2 format without the 0x04 prefix. ```java EncryptUtil.encryptMessageBySM2 ``` -------------------------------- ### Configure PKCS12 Options Source: https://github.com/emmansun/gmsm/blob/develop/docs/pkcs12.md Configuration options for PKCS12 operations, specifying algorithms for MAC, certificate, key, KDF, encryption, and message authentication, along with iteration counts and salt length. ```go { macAlgorithm: oidPBMAC1, certAlgorithm: oidPBES2, keyAlgorithm: oidPBES2, kdfPrf: oidHmacWithSM3, encryptionScheme: oidSM4CBC, messageAuthScheme: oidHmacWithSM3, macIterations: 2048, encryptionIterations: 2048, saltLen: 16, rand: rand.Reader, } ``` -------------------------------- ### SM3 KDF Performance Benchmarks Source: https://github.com/emmansun/gmsm/wiki/SM2加解密性能 Performance benchmarks for the KDF (Key Derivation Function) using SM3, with varying input Z length (zLen) and desired key length (kLen). Demonstrates how KDF performance scales with kLen. ```go goos: windows goarch: amd64 pkg: github.com/emmansun/gmsm/sm3 cpu: Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz BenchmarkKdfWithSM3 BenchmarkKdfWithSM3/zLen=32-kLen=32 BenchmarkKdfWithSM3/zLen=32-kLen=32-6 5110834 232.9 ns/op 32 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=32-kLen=64 BenchmarkKdfWithSM3/zLen=32-kLen=64-6 2580963 463.4 ns/op 96 B/op 2 allocs/op BenchmarkKdfWithSM3/zLen=32-kLen=128 BenchmarkKdfWithSM3/zLen=32-kLen=128-6 1305332 897.0 ns/op 224 B/op 3 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=32 BenchmarkKdfWithSM3/zLen=64-kLen=32-6 2992752 399.6 ns/op 32 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=64 BenchmarkKdfWithSM3/zLen=64-kLen=64-6 1893337 638.8 ns/op 96 B/op 2 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=128 BenchmarkKdfWithSM3/zLen=64-kLen=128-6 1000000 1102 ns/op 224 B/op 3 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=256 BenchmarkKdfWithSM3/zLen=64-kLen=256-6 574406 1982 ns/op 480 B/op 4 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=512 BenchmarkKdfWithSM3/zLen=64-kLen=512-6 302526 3704 ns/op 992 B/op 5 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=1024 BenchmarkKdfWithSM3/zLen=64-kLen=1024-6 155256 7910 ns/op 3296 B/op 7 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=8192 BenchmarkKdfWithSM3/zLen=64-kLen=8192-6 19880 60780 ns/op 34272 B/op 13 allocs/op ``` -------------------------------- ### Scheme Two: Shift, Add, and Subtract Reduction (First Round) Source: https://github.com/emmansun/gmsm/wiki/SM2-WWMM-(2) This code demonstrates the first reduction step for Scheme Two, which utilizes shifts, additions, and subtractions. It's noted that this scheme might not be as advantageous as Scheme One when MULXQ/ADCXQ/ADOXQ are available. ```asm // First reduction step MOVQ acc0, AX MULQ p256ordK0<>(SB) MOVQ AX, t0 // Y = t0 = (k0 * acc0) mod 2^64 // 处理的一个加法,以释放acc0 MOVQ p256ord<>+0x00(SB), AX MULQ t0 ADDQ AX, acc0 // (carry1, acc0) = acc0 + L(t0 * ord0),acc0 可以被释放了。 ADCQ $0, DX // DX = carry1 + H(t0 * ord0) MOVQ DX, t1 // t1 = carry1 + H(t0 * ord0) // 处理减法部分: [acc0, acc3, acc2, acc1] - [0, 0x100000000, 1, 0] * t0 // 处理减法 MOVQ t0, acc0 // acc0 = t0 MOVQ t0, AX MOVQ t0, DX SHLQ $32, AX SHRQ $32, DX SUBQ t0, acc2 SBBQ AX, acc3 SBBQ DX, acc0 // 处理加法 MOVQ p256ord<>+0x08(SB), AX MULQ t0 ADDQ t1, acc1 // (carry2, acc1) = acc1 + t1 ADCQ $0, DX // DX = carry2 + H(t0*ord1) ADDQ AX, acc1 // (carry3, acc1) = acc1 + t1 + L(t0*ord1) ADCQ DX, acc2 ADCQ $0, acc3 ADCQ $0, acc0 ``` -------------------------------- ### Key Generation Source: https://github.com/emmansun/gmsm/blob/develop/docs/pqc-en.md Provides examples for generating SLH-DSA private keys randomly and obtaining the corresponding public key. ```APIDOC ## Key Generation ### Description Generate randomly a private key using a provided random reader and obtain the public key from the generated private key. ### Go Code Examples ```go import "crypto/rand" import "github.com/emmansun/gmsm/slhdsa" // Generate randomly sk, err := params.GenerateKey(rand.Reader) // Obtain the public key pk := sk.Public().(*slhdsa.PublicKey) // or equivalently pk = sk.PublicKey() ``` ``` -------------------------------- ### X.509 Certificate with SLH-DSA Source: https://github.com/emmansun/gmsm/blob/develop/docs/pqc.md Example of creating an X.509 certificate template using SLH-DSA signature and public key algorithms as defined by RFC 9909. ```go template := &smx509.Certificate{ SignatureAlgorithm: smx509.SLHDSASHA2128s, PublicKeyAlgorithm: smx509.PKSLHDSASHA2128s, // ... } sk, _ := slhdsa.SLHDSA128SmallSHA2.GenerateKey(rand.Reader) certDER, err := smx509.CreateCertificate(rand.Reader, template, template, sk.Public(), sk) ``` -------------------------------- ### Scheme One: Multiplication and Addition Reduction (First Round) Source: https://github.com/emmansun/gmsm/wiki/SM2-WWMM-(2) This pseudocode demonstrates the first reduction step using multiplication and addition. It involves multiple multiply and add operations to reduce the intermediate product. ```asm // T = [acc0, acc1, acc2, acc3, acc4, acc5, y_ptr, x_ptr] // First reduction step MOVQ acc0, AX MULQ ·np+0x00(SB) MOVQ AX, t0 // Y // Calculate next T = T+Y*P MOVQ ·p2+0x00(SB), AX MULQ t0 ADDQ AX, acc0 // acc0 is free now ADCQ $0, DX MOVQ DX, t1 // carry XORQ acc0, acc0 MOVQ ·p2+0x08(SB), AX MULQ t0 ADDQ t1, acc1 ADCQ $0, DX ADDQ AX, acc1 ADCQ $0, DX MOVQ DX, t1 // carry MOVQ ·p2+0x10(SB), AX MULQ t0 ADDQ t1, acc2 ADCQ $0, DX ADDQ AX, acc2 ADCQ $0, DX MOVQ DX, t1 // carry MOVQ ·p2+0x18(SB), AX MULQ t0 ADDQ t1, acc3 ADCQ $0, DX ADDQ AX, acc3 ADCQ DX, acc0 ``` -------------------------------- ### Scheme One: Optimized Reduction with MULXQ/ADCXQ/ADOXQ (First Round) Source: https://github.com/emmansun/gmsm/wiki/SM2-WWMM-(2) This code snippet shows the first reduction step optimized using MULXQ, ADOXQ, and ADCXQ instructions. This approach aims to reduce the number of addition operations. ```asm // First reduction step MOVQ acc0, DX MULXQ ·np+0x00(SB), DX, AX MULXQ ·p2+0x00(SB), AX, t0 ADOXQ AX, acc0 // (carry1, acc0) = acc0 + t0 * ord0 MULXQ ·p2+0x08(SB), AX, BX ADCXQ t0, AX ADOXQ AX, acc1 MULXQ ·p2+0x10(SB), AX, t0 ADCXQ BX, AX ADOXQ AX, acc2 MULXQ ·p2+0x18(SB), AX, acc0 ADCXQ t0, AX ADOXQ AX, acc3 MOVQ $0, t0 ADCXQ t0, acc0 ADOXQ t0, acc0 ``` -------------------------------- ### Run Loong64 Specific ML-DSA Benchmarks Source: https://github.com/emmansun/gmsm/blob/develop/mldsa/README.md Executes benchmarks specifically for the Loong64 architecture (likely including LASX optimizations) for the ML-DSA package, running each benchmark for 3 seconds. ```shell go test -bench=BenchmarkLoong64 -benchtime=3s ./mldsa/ ``` -------------------------------- ### Run All ML-DSA Benchmarks Source: https://github.com/emmansun/gmsm/blob/develop/mldsa/README.md Executes all benchmarks for the ML-DSA package with a benchmark time of 3 seconds per benchmark. This provides a comprehensive performance overview. ```shell go test -bench=. -benchtime=3s ./mldsa/ ``` -------------------------------- ### EC-ElGamal Partial Homomorphic Encryption Example Source: https://github.com/emmansun/gmsm/blob/develop/docs/sm2.md Demonstrates the use of EC-ElGamal based on the SM2 curve for partially homomorphic encryption, supporting addition and scalar multiplication on encrypted data. Suitable for applications like electronic voting. ```go // 电子投票:无需解密即可累加加密的投票 encryptedVote1 := Encrypt(publicKey, 1) // 投票 "赞成" encryptedVote2 := Encrypt(publicKey, 0) // 投票 "反对" encryptedTotal := Add(encryptedVote1, encryptedVote2) totalVotes := Decrypt(privateKey, encryptedTotal) // 结果: 1 ``` -------------------------------- ### KDF with SM3 Benchmarks (AVX2 Parallelization) Source: https://github.com/emmansun/gmsm/wiki/SM2加解密性能 These benchmarks evaluate the performance of KDF with SM3, specifically focusing on the impact of AVX2 8-way parallelization and varying key and Z lengths. Results show performance scaling with data size. ```text goos: windows goarch: amd64 pkg: github.com/emmansun/gmsm/sm3 cpu: Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz BenchmarkKdfWithSM3 BenchmarkKdfWithSM3/zLen=32-kLen=32 BenchmarkKdfWithSM3/zLen=32-kLen=32-6 5110020 229.9 ns/op 32 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=32-kLen=64 BenchmarkKdfWithSM3/zLen=32-kLen=64-6 2790901 423.9 ns/op 64 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=32-kLen=128 BenchmarkKdfWithSM3/zLen=32-kLen=128-6 2514219 467.8 ns/op 128 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=32 BenchmarkKdfWithSM3/zLen=64-kLen=32-6 3024373 399.9 ns/op 32 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=64 BenchmarkKdfWithSM3/zLen=64-kLen=64-6 2027554 596.3 ns/op 64 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=128 BenchmarkKdfWithSM3/zLen=64-kLen=128-6 1744693 691.4 ns/op 128 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=256 BenchmarkKdfWithSM3/zLen=64-kLen=256-6 1397571 811.7 ns/op 256 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=512 BenchmarkKdfWithSM3/zLen=64-kLen=512-6 862700 1385 ns/op 512 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=1024 BenchmarkKdfWithSM3/zLen=64-kLen=1024-6 507590 2364 ns/op 1024 B/op 1 allocs/op BenchmarkKdfWithSM3/zLen=64-kLen=8192 BenchmarkKdfWithSM3/zLen=64-kLen=8192-6 70632 17524 ns/op 8192 B/op 1 allocs/op ``` -------------------------------- ### Build ML-KEM with Default SIMD Assembly Source: https://github.com/emmansun/gmsm/blob/develop/mlkem/README.md Builds the ML-KEM package using default SIMD assembly optimizations if supported by the target architecture. ```shell go build ./mlkem/ ``` -------------------------------- ### SM2 Scalar Multiplication using Lookup Table (amd64/arm64) Source: https://github.com/emmansun/gmsm/wiki/SM2性能优化(续) This Go code demonstrates the generation of a lookup table for base scalar multiplication, a technique used for optimizing performance on amd64 and arm64 architectures. It references a specific file for the generation method. ```Go package sm2 import ( "fmt" "math/big" ) // Point represents a point on the elliptic curve. type Point struct { X, Y *big.Int } // CurveParams defines the parameters for an elliptic curve. type CurveParams struct { P *big.Int N *big.Int G *Point } // PrecomputedTable holds precomputed points for scalar multiplication. type PrecomputedTable struct { Points [][]*Point } // GenerateP256Table generates a lookup table for SM2 scalar multiplication. // This function's implementation is detailed in gen_p256_table.go. func GenerateP256Table(curve *CurveParams) (*PrecomputedTable, error) { // The actual table generation logic would be here or in a separate file. // This is a placeholder to indicate the function's purpose. fmt.Println("Generating P256 lookup table...") // Example: Initialize with dummy data table := &PrecomputedTable{ Points: make([][]*Point, 8), // Example window size } for i := range table.Points { table.Points[i] = make([]*Point, 1<<4) // Example window size } return table, nil } // ScalarMultWithTable performs scalar multiplication using a precomputed table. func (t *PrecomputedTable) ScalarMultWithTable(k *big.Int, curve *CurveParams) (*Point, error) { // Implementation using the lookup table would go here. fmt.Println("Performing scalar multiplication with table...") return nil, fmt.Errorf("ScalarMultWithTable not implemented") } ``` -------------------------------- ### Build ML-KEM with Pure-Go Fallback Source: https://github.com/emmansun/gmsm/blob/develop/mlkem/README.md Builds the ML-KEM package using the pure Go implementation, disabling SIMD assembly. This is useful for unsupported platforms or when assembly is not desired. ```shell go build -tags=purego ./mlkem/ ``` -------------------------------- ### Run ARM64 Specific ML-DSA Benchmarks Source: https://github.com/emmansun/gmsm/blob/develop/mldsa/README.md Executes benchmarks specifically for the ARM64 architecture (likely including NEON optimizations) for the ML-DSA package, running each benchmark for 3 seconds. ```shell go test -bench=BenchmarkARM64 -benchtime=3s ./mldsa/ ``` -------------------------------- ### SM3 Benchmark Results (Normal ASM) Source: https://github.com/emmansun/gmsm/wiki/SM3性能优化 Performance benchmark for SM3 hashing on 1K block size using normal assembly instructions on a specific Intel CPU. ```go goos: windows goarch: amd64 pkg: github.com/emmansun/gmsm/sm3 cpu: Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz BenchmarkHash1K BenchmarkHash1K-6 314943 3955 ns/op 258.88 MB/s 0 B/op 0 allocs/op ``` -------------------------------- ### Construct Public Key from Raw Coordinates Source: https://github.com/emmansun/gmsm/blob/develop/docs/sm2-en.md Creates an SM2 public key from uncompressed point coordinates (0x04 || X || Y). Verifies by marshaling back to the original format. ```go func ExampleNewPublicKey() { // Uncompressed point: 0x04 || X || Y keypoints, _ := hex.DecodeString( "048356e642a40ebd18d29ba3532fbd9f3bbee8f027c3f6f39a5ba2f870369f9988" "981f5efe55d1c5cdf6c0ef2b070847a14f7fdf4272a8df09c442f3058af94ba1") pub, err := sm2.NewPublicKey(keypoints) if err != nil { log.Fatalf("Failed to create public key: %v", err) } // Verify by marshaling back marshaled := elliptic.Marshal(sm2.P256(), pub.X, pub.Y) fmt.Printf("%x\n", marshaled) // Output: 048356e642a40ebd18d29ba3532fbd9f3bbee8f027c3f6f39a5ba2f870369f9988981f5efe55d1c5cdf6c0ef2b070847a14f7fdf4272a8df09c442f3058af94ba1 } ``` -------------------------------- ### Sign and Verify Content with ML-DSA using CMS Source: https://github.com/emmansun/gmsm/blob/develop/docs/pqc.md Demonstrates signing content with an ML-DSA key and then verifying the signature using the CMS (PKCS#7) format. The OIDs used are the same as in RFC 9881. ```Go import "github.com/emmansun/gmsm/pkcs7" // 使用 ML-DSA 密钥签名 p7, err := pkcs7.NewSignedData(content) err = p7.AddSigner(cert, key65, pkcs7.SignerInfoConfig{}) signedData, err := p7.Finish() // 验签 p7, err = pkcs7.Parse(signedData) err = p7.Verify() ``` -------------------------------- ### SM3 Benchmark Results (Pure Go) Source: https://github.com/emmansun/gmsm/wiki/SM3性能优化 Performance benchmark for SM3 hashing on 1K block size using pure Go implementation on a specific Intel CPU. ```go goos: windows goarch: amd64 pkg: github.com/emmansun/gmsm/sm3 cpu: Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz BenchmarkHash1K BenchmarkHash1K-6 233209 4699 ns/op 217.91 MB/s 0 B/op 0 allocs/op ``` -------------------------------- ### SM2 Optimization using NEON instructions (arm64) Source: https://github.com/emmansun/gmsm/wiki/SM2性能优化(续) This snippet represents the optimization of SELECT and MOVE operations using NEON instructions for the arm64 architecture in SM2 implementations. It refers to a discussion thread for more context. ```Go package sm2 import ( "fmt" "math/big" ) // PerformNeonSelectMove simulates NEON instruction usage for SELECT/MOVE. // This would typically be part of assembly code for arm64. func PerformNeonSelectMove(a, b *big.Int, condition bool) (*big.Int, error) { fmt.Println("Simulating NEON instructions for SELECT/MOVE...") // In a real scenario, this would involve arm64 assembly. // Placeholder logic: result := new(big.Int) if condition { result.Set(a) } else { result.Set(b) } return result, nil } ``` -------------------------------- ### Generate Optimized Inverse Operation with addchain Source: https://github.com/emmansun/gmsm/wiki/SM2性能优化(续) This snippet is related to generating optimized inverse operations for SM2 using the addchain tool. It highlights the use of code templates to ensure consistency and correctness, similar to Go's approach for multiple curves. ```Go package sm2 import ( "fmt" "math/big" ) // Inverse calculates the modular multiplicative inverse of 'a' modulo 'n'. // This function is intended to be generated or optimized by tools like addchain. func Inverse(a, n *big.Int) (*big.Int, error) { // Placeholder for optimized inverse calculation. // In a real implementation, this would use optimized algorithms. result := new(big.Int) if result.ModInverse(a, n) == nil { return nil, fmt.Errorf("inverse does not exist") } return result, nil } ``` -------------------------------- ### Create Signed and Enveloped Data Structure Source: https://github.com/emmansun/gmsm/blob/develop/docs/pkcs7.md Use NewSignedAndEnvelopedData or NewSMSignedAndEnvelopedData to initialize the SignedAndEnvelopedData structure, which includes the data encryption process. ```go NewSignedAndEnvelopedData() NewSMSignedAndEnvelopedData() ``` -------------------------------- ### Final Exponentiation - Easy Part Source: https://github.com/emmansun/gmsm/blob/develop/internal/sm9/bn256/README.md The easy part of the final exponentiation computes the (p^6-1)(p^2+1) power. This involves a Frobenius operation, an inverse, and another Frobenius operation. ```Go t1 = FrobeniusP6(in) · in⁻¹ // in^(p^6 - 1), FrobeniusP6 = Conjugate t1 = FrobeniusP2(t1) · t1 // t1^(p^2 + 1) ``` -------------------------------- ### Run AMD64 Specific ML-DSA Benchmarks Source: https://github.com/emmansun/gmsm/blob/develop/mldsa/README.md Executes benchmarks specifically for the AMD64 architecture (likely including AVX2 optimizations) for the ML-DSA package, running each benchmark for 3 seconds. ```shell go test -bench=BenchmarkAMD64 -benchtime=3s ./mldsa/ ``` -------------------------------- ### ppc64le VMX Shift-4 Barrett Reduction Strategy Source: https://github.com/emmansun/gmsm/blob/develop/mlkem/README.md Illustrates the shift-4 trick used in Barrett reduction for ppc64le VMX to avoid 32-bit overflow during intermediate products. This method is crucial due to the absence of a native signed 16-bit multiply-high instruction. ```assembly shift-4 Barrett: P = coeff × zeta (16-bit × 16-bit → 32-bit, max q² ≈ 11M) P' = P >> 4 (max ≈ 692K, fits in uint32) Q = (P' × 5039) >> 20 (quotient estimate, equivalent to P × 5039 >> 24) r = P - Q × q (remainder ∈ [0, 2q)) ``` -------------------------------- ### SM2 Optimization using MULX instruction (amd64) Source: https://github.com/emmansun/gmsm/wiki/SM2性能优化(续) This snippet is a placeholder representing the use of the MULX instruction for optimization on the amd64 architecture in SM2 implementations. It references a specific commit for the actual implementation details. ```Go package sm2 import ( "fmt" "math/big" ) // PerformMulX simulates the use of the MULX instruction for optimization. // This would typically be part of assembly code for amd64. func PerformMulX(a, b, m *big.Int) (*big.Int, error) { fmt.Println("Simulating MULX instruction for multiplication...") // In a real scenario, this would involve assembly. // Placeholder for the result of (a * b) % m using MULX. result := new(big.Int) result.Mul(a, b) result.Mod(result, m) return result, nil } ``` -------------------------------- ### ARM64 Assembly for Modular Arithmetic Source: https://github.com/emmansun/gmsm/wiki/SM2-WWMM This snippet demonstrates ARM64 assembly instructions for performing modular addition and multiplication with carry handling. It was part of an implementation that was later rolled back due to complexity in carry/borrow management. ```assembly UMULH const3, acc0, hlp1 // hlp1 = H(acc0*p3), 事实上不能用hlp1, 这个寄存器被p256PointAddAsm方法全局使用 ADC $0, acc4 // acc4 = carry3 + acc4 ADDS acc0, acc1, acc1 // (carry4, acc1) = acc0 + acc1 + L(acc0*p1) ADCS y0, acc2, acc2 // (carry5, acc2) = carry4 + acc2 + L(acc0*p2) + H(acc0*p1) ADCS hlp0, acc3, acc3 // (carry6, acc3) = carry5 + acc3 + L(acc0*p3) + H(acc0*p2) ADC $0, hlp1, acc0 // acc0 = carry6 + H(acc0*p3) ``` -------------------------------- ### SM3 Benchmark Results (AVX2) Source: https://github.com/emmansun/gmsm/wiki/SM3性能优化 Performance benchmark for SM3 hashing on 1K block size using AVX2 instructions on a specific Intel CPU. ```go goos: windows goarch: amd64 pkg: github.com/emmansun/gmsm/sm3 cpu: Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz BenchmarkHash1K BenchmarkHash1K-6 404881 2663 ns/op 384.53 MB/s 0 B/op 0 allocs/op ``` -------------------------------- ### Print All AES S-Boxes Source: https://github.com/emmansun/gmsm/wiki/Efficient-Software-Implementations-of-ZUC Iterates through different basis configurations for AES, generates the corresponding S-boxes, and prints them. Requires helper functions like get_all_WZY and gen_X. ```python def print_all_aes_sbox(): result_list = get_all_WZY(aesf) for i, v in enumerate(result_list): X = gen_X(aesf, v[0], v[1], v[2], v[3], v[4], v[5]) X_inv = gen_X_inv(X) print_sbox(AES_SBOX(X, X_inv)) print() ``` -------------------------------- ### Reading Random Bytes using io.Reader Source: https://github.com/emmansun/gmsm/blob/develop/docs/rand.md Demonstrates how to read random bytes from the `rand.Reader` which implements the `io.Reader` interface. This is a common way to obtain random data for various cryptographic purposes. ```go import ( "io" "github.com/emmansun/gmsm/rand" ) buf := make([]byte, 32) n, err := io.ReadFull(rand.Reader, buf) if err != nil { panic(err) } ``` -------------------------------- ### Build ML-DSA with Pure-Go Fallback Source: https://github.com/emmansun/gmsm/blob/develop/mldsa/README.md Builds the ML-DSA package using a pure Go implementation, disabling SIMD assembly optimizations. Use this tag when assembly is not supported or for debugging. ```shell go build -tags=purego ./mldsa/ ``` -------------------------------- ### Sign Message with Default SM2 Options Source: https://github.com/emmansun/gmsm/blob/develop/docs/sm2-en.md Signs a message using the default SM2 options, which include the standard Z value calculation based on the default UID. Requires a private key and the message to be signed. ```go func ExamplePrivateKey_Sign() { toSign := []byte("ShangMi SM2 Sign Standard") // Load or generate private key privKey, _ := hex.DecodeString( "6c5a0a0b2eed3cbec3e4f1252bfe0e28c504a1c6bf1999eebb0af9ef0f8e6c85") testkey, err := sm2.NewPrivateKey(privKey) if err != nil { log.Fatalf("Failed to create private key: %v", err) } // Sign with default SM2 options (includes Z value calculation) sig, err := testkey.Sign(rand.Reader, toSign, sm2.DefaultSM2SignerOpts) if err != nil { fmt.Fprintf(os.Stderr, "Error from signing: %s\n", err) return } fmt.Printf("Signature: %x\n", sig) } ``` -------------------------------- ### AEAD Interface in Go Cipher Package Source: https://github.com/emmansun/gmsm/blob/develop/docs/sm4.md Illustrates the AEAD interface from Go's cipher package, highlighting its Seal and Open methods for authenticated encryption. It explains the behavior regarding destination slice ('dst') and its capacity for reuse. ```go // AEAD is a cipher mode providing authenticated encryption with associated // data. For a description of the methodology, see // https://en.wikipedia.org/wiki/Authenticated_encryption. type AEAD interface { // NonceSize returns the size of the nonce that must be passed to Seal // and Open. NonceSize() int // Overhead returns the maximum difference between the lengths of a // plaintext and its ciphertext. Overhead() int // Seal encrypts and authenticates plaintext, authenticates the // additional data and appends the result to dst, returning the updated // slice. The nonce must be NonceSize() bytes long and unique for all // time, for a given key. // // To reuse plaintext's storage for the encrypted output, use plaintext[:0] // as dst. Otherwise, the remaining capacity of dst must not overlap plaintext. Seal(dst, nonce, plaintext, additionalData []byte) []byte // Open decrypts and authenticates ciphertext, authenticates the // additional data and, if successful, appends the resulting plaintext // to dst, returning the updated slice. The nonce must be NonceSize() // bytes long and both it and the additional data must match the // value passed to Seal. // // To reuse ciphertext's storage for the decrypted output, use ciphertext[:0] // as dst. Otherwise, the remaining capacity of dst must not overlap plaintext. // // Even if the function fails, the contents of dst, up to its capacity, // may be overwritten. Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) } ``` -------------------------------- ### SM3 Benchmark Results (SSE) Source: https://github.com/emmansun/gmsm/wiki/SM3性能优化 Performance benchmark for SM3 hashing on 1K block size using SSE (SSSE3 SSE2) instructions on a specific Intel CPU. ```go goos: windows goarch: amd64 pkg: github.com/emmansun/gmsm/sm3 cpu: Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz BenchmarkHash1K BenchmarkHash1K-6 390361 2936 ns/op 348.83 MB/s 0 B/op 0 allocs/op ``` -------------------------------- ### SHA256 Benchmark Results (Normal ASM) Source: https://github.com/emmansun/gmsm/wiki/SM3性能优化 Performance benchmark for SHA256 hashing on 1K block size using normal assembly instructions on a specific Intel CPU. ```go goos: windows goarch: amd64 pkg: github.com/emmansun/gmsm/sha256 cpu: Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz BenchmarkHash1K BenchmarkHash1K-6 260756 4525 ns/op 226.30 MB/s 0 B/op 0 allocs/op ``` -------------------------------- ### SM3 Hashing Performance Benchmarks Source: https://github.com/emmansun/gmsm/wiki/SM2加解密性能 Performance metrics for SM3 hashing with different input data lengths (1K and 8K). Shows throughput in MB/s and indicates zero allocations for these benchmarks. ```go goos: windows goarch: amd64 pkg: github.com/emmansun/gmsm/sm3 cpu: Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz BenchmarkHash1K BenchmarkHash1K-6 418222 2805 ns/op 365.01 MB/s 0 B/op 0 allocs/op BenchmarkHash8K BenchmarkHash8K-6 57502 20781 ns/op 394.21 MB/s 0 B/op 0 allocs/op ```