github.com/emmansun/gmsm@v0.29.1/pkcs7/encrypt_test.go (about)

     1  package pkcs7
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  
     7  	"github.com/emmansun/gmsm/pkcs"
     8  )
     9  
    10  func TestEncryptUsingPSK(t *testing.T) {
    11  	ciphers := []pkcs.Cipher{
    12  		pkcs.DESCBC,
    13  		pkcs.SM4GCM,
    14  		pkcs.AES128GCM,
    15  	}
    16  
    17  	for _, cipher := range ciphers {
    18  		plaintext := []byte("Hello Secret World!")
    19  		var key []byte
    20  
    21  		switch cipher.KeySize() {
    22  		case 8:
    23  			key = []byte("64BitKey")
    24  		case 16:
    25  			key = []byte("128BitKey4AESGCM")
    26  		}
    27  		ciphertext, err := EncryptUsingPSK(cipher, plaintext, key)
    28  		if err != nil {
    29  			t.Fatal(err)
    30  		}
    31  
    32  		p7, _ := Parse(ciphertext)
    33  		_, err = p7.GetRecipients()
    34  		if err != ErrNotEnvelopedData {
    35  			t.Errorf("expected ErrNotEnvelopedData, got %v", err)
    36  		}
    37  		result, err := p7.DecryptUsingPSK(key)
    38  		if err != nil {
    39  			t.Fatalf("cannot Decrypt encrypted result: %s", err)
    40  		}
    41  		if !bytes.Equal(plaintext, result) {
    42  			t.Errorf("encrypted data does not match plaintext:\n\tExpected: %s\n\tActual: %s", plaintext, result)
    43  		}
    44  	}
    45  }
    46  
    47  func TestEncryptSMUsingPSK(t *testing.T) {
    48  	ciphers := []pkcs.Cipher{
    49  		pkcs.DESCBC,
    50  		pkcs.SM4GCM,
    51  		pkcs.AES128GCM,
    52  	}
    53  
    54  	for _, cipher := range ciphers {
    55  		plaintext := []byte("Hello Secret World!")
    56  		var key []byte
    57  
    58  		switch cipher.KeySize() {
    59  		case 8:
    60  			key = []byte("64BitKey")
    61  		case 16:
    62  			key = []byte("128BitKey4AESGCM")
    63  		}
    64  		ciphertext, err := EncryptSMUsingPSK(cipher, plaintext, key)
    65  		if err != nil {
    66  			t.Fatal(err)
    67  		}
    68  
    69  		p7, _ := Parse(ciphertext)
    70  		result, err := p7.DecryptUsingPSK(key)
    71  		if err != nil {
    72  			t.Fatalf("cannot Decrypt encrypted result: %s", err)
    73  		}
    74  		if !bytes.Equal(plaintext, result) {
    75  			t.Errorf("encrypted data does not match plaintext:\n\tExpected: %s\n\tActual: %s", plaintext, result)
    76  		}
    77  	}
    78  }