Skip to content

Commit

Permalink
test: Update crypto/smtongsuo_test.go with SM2/RSA encryption tests
Browse files Browse the repository at this point in the history
* Add comprehensive test cases for Tongsuo\_EncryptBySm2 function
  - Implement test case for valid encryption and decryption using SM2 algorithm
  - Include test case for invalid ciphertext check
  - Test SM2 encryption and RSA decryption compatibility
  - Verify invalid ciphertext check for RSA decryption
  • Loading branch information
Laisky committed Mar 28, 2024
1 parent d81a576 commit 187c234
Showing 1 changed file with 50 additions and 13 deletions.
63 changes: 50 additions & 13 deletions crypto/smtongsuo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -708,21 +708,58 @@ func TestTongsuo_EncryptBySm2(t *testing.T) {
ins, err := NewTongsuo("/usr/local/bin/tongsuo")
require.NoError(t, err)

prikeyPem, err := ins.NewPrikey(ctx)
require.NoError(t, err)
plaintext := []byte("Hello, World!")

pubkeyPem, err := ins.Prikey2Pubkey(ctx, prikeyPem)
require.NoError(t, err)
t.Run("sm2", func(t *testing.T) {
prikeyPem, err := ins.NewPrikey(ctx)
require.NoError(t, err)

plaintext := []byte("Hello, World!")
pubkeyPem, err := ins.Prikey2Pubkey(ctx, prikeyPem)
require.NoError(t, err)

// encrypt by sm2 pubkey
ciphertext, err := ins.EncryptBySm2(ctx, pubkeyPem, plaintext)
require.NoError(t, err)
require.NotNil(t, ciphertext)
// encrypt by sm2 pubkey
ciphertext, err := ins.EncryptBySm2(ctx, pubkeyPem, plaintext)
require.NoError(t, err)
require.NotNil(t, ciphertext)

// decrypt by sm2 prikey
decrypted, err := ins.DecryptBySm2(ctx, prikeyPem, ciphertext)
require.NoError(t, err)
require.Equal(t, plaintext, decrypted)
// decrypt by sm2 prikey
decrypted, err := ins.DecryptBySm2(ctx, prikeyPem, ciphertext)
require.NoError(t, err)
require.Equal(t, plaintext, decrypted)

t.Run("ivalid ciphertext", func(t *testing.T) {
decrypted, err := ins.DecryptBySm2(ctx, prikeyPem,
append([]byte("halo"), ciphertext...))
require.ErrorContains(t, err, "operation error")
require.NotEqual(t, plaintext, decrypted)
})
})

t.Run("compatable with rsa", func(t *testing.T) {
prikey, err := NewRSAPrikey(RSAPrikeyBits2048)
require.NoError(t, err)
prikeyPem, err := Prikey2Pem(prikey)
require.NoError(t, err)

pubkey := Prikey2Pubkey(prikey)
pubkeyPem, err := Pubkey2Pem(pubkey)
require.NoError(t, err)

// encrypt by rsa pubkey
ciphertext, err := ins.EncryptBySm2(ctx, pubkeyPem, plaintext)
require.NoError(t, err)
require.NotNil(t, ciphertext)

// decrypt by rsa prikey
decrypted, err := ins.DecryptBySm2(ctx, prikeyPem, ciphertext)
require.NoError(t, err)
require.Equal(t, plaintext, decrypted)

t.Run("ivalid ciphertext", func(t *testing.T) {
decrypted, err := ins.DecryptBySm2(ctx, prikeyPem,
append(ciphertext, []byte("halo")...))
require.ErrorContains(t, err, "operation error")
require.NotEqual(t, plaintext, decrypted)
})
})
}

0 comments on commit 187c234

Please sign in to comment.