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

     1  package pkcs7
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/ecdsa"
     6  	"encoding/pem"
     7  	"math/big"
     8  	"testing"
     9  
    10  	"github.com/emmansun/gmsm/pkcs"
    11  	"github.com/emmansun/gmsm/sm2"
    12  	"github.com/emmansun/gmsm/smx509"
    13  )
    14  
    15  // from https://www.gmcert.org/
    16  var smSignedEvelopedTestData = `-----BEGIN PKCS7-----
    17  MIIDwwYKKoEcz1UGAQQCBKCCA7MwggOvAgEBMYGfMIGcAgEBMAwAAAIIAs64zJDL
    18  T8UwCwYJKoEcz1UBgi0DBHwwegIhAPbXLhqtkA/HeYKgPeZNPP4kT2/PqS7K8NiB
    19  vAFCBsf+AiEA4m9ZyghfFUaE1K4kre9T/R7Td4hVQPij9GOloRykKJ8EIMJ/zBGe
    20  WaqgtCUFu99S3Wovtd6+jN1tDkTJPWgZ6uu1BBCobCvaWMr0Of+Z686i/wVrMQww
    21  CgYIKoEcz1UBgxEwWQYKKoEcz1UGAQQCATAJBgcqgRzPVQFogEDM1pUC/MDTCRCQ
    22  uZiIxZYZzNaVAvzA0wkQkLmYiMWWGUnT7MvXe2M2khckxgU+ZMVBNDpf4EFl6+C2
    23  PRPcy8ROoIIB4jCCAd4wggGDoAMCAQICCALODAD8KSAXMAoGCCqBHM9VAYN1MEIx
    24  CzAJBgNVBAYTAkNOMQ8wDQYDVQQIDAbmtZnmsZ8xDzANBgNVBAcMBuadreW3njER
    25  MA8GA1UECgwI5rWL6K+VQ0EwHhcNMjExMjIzMDg0ODMzWhcNMzExMjIzMDg0ODMz
    26  WjBCMQswCQYDVQQGEwJDTjEPMA0GA1UECAwG5rWZ5rGfMQ8wDQYDVQQHDAbmna3l
    27  t54xETAPBgNVBAoMCOa1i+ivlUNBMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE
    28  SrOgeWQcu+dzrGUniH7/M0nG4ol5C4wfj5cPmFr6HrEZKmBnvzKo6/K65k4auohF
    29  rm2CumYkEFeeJCpXL2tx7aNjMGEwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF
    30  MAMBAf8wHQYDVR0OBBYEFDaT4xTnRQn61e/qLxIt06GWPMKkMB8GA1UdIwQYMBaA
    31  FDaT4xTnRQn61e/qLxIt06GWPMKkMAoGCCqBHM9VAYN1A0kAMEYCIQCw4bSylc4l
    32  IV203nQ6L0QDUgnbugidDAMO1m5d7wFhjgIhAMwly3Bd9gzOQM3vTKqVH0H2D2kU
    33  y2JDcEl5cPy1GBOhMYG4MIG1AgEBME4wQjELMAkGA1UEBhMCQ04xDzANBgNVBAgM
    34  Bua1meaxnzEPMA0GA1UEBwwG5p2t5beeMREwDwYDVQQKDAjmtYvor5VDQQIIAs4M
    35  APwpIBcwCgYIKoEcz1UBgxEwCwYJKoEcz1UBgi0BBEcwRQIgR7STVlgH/yy4k93+
    36  h3KRFN+dWEVeOJ7G1lRRSNXihnkCIQCHxZvmdUcv38SBCgZp+qxnpm2a+C1/tWKV
    37  d/A8tW8dnw==
    38  -----END PKCS7-----
    39  `
    40  
    41  var encCert = `-----BEGIN CERTIFICATE-----
    42  MIICPTCCAeOgAwIBAgIIAs64zJDLT8UwCgYIKoEcz1UBg3UwQjELMAkGA1UEBhMC
    43  Q04xDzANBgNVBAgMBua1meaxnzEPMA0GA1UEBwwG5p2t5beeMREwDwYDVQQKDAjm
    44  tYvor5VDQTAeFw0yMzAyMjIxMjIwMzNaFw0yNDAyMjIxMjIwMzNaMH0xCzAJBgNV
    45  BAYTAkNOMQ8wDQYDVQQIDAbmtZnmsZ8xDzANBgNVBAcMBuadreW3njEVMBMGA1UE
    46  CgwM5rWL6K+V5py65p6EMRUwEwYDVQQLDAzmtYvor5Xnu4Tnu4cxHjAcBgNVBAMM
    47  Fea1i+ivleacjeWKoeWZqOWQjeensDBZMBMGByqGSM49AgEGCCqBHM9VAYItA0IA
    48  BGqelO/A74LrAZvxFopkSz9lpjygTF1ffslhB0BzwxQ5jMx1D4912Swb6foMe+0k
    49  bq9V2i3Kn2HrzSTAcj+G+9ujgYcwgYQwDgYDVR0PAQH/BAQDAgM4MBMGA1UdJQQM
    50  MAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFDd41c6+e9aahmQD
    51  PdC8YSXfwYgUMB8GA1UdIwQYMBaAFDaT4xTnRQn61e/qLxIt06GWPMKkMA8GA1Ud
    52  EQQIMAaHBH8AAAEwCgYIKoEcz1UBg3UDSAAwRQIgMZBhweovXaHVNSlLv0rTEYnT
    53  GRSsTKmrkCDrxQdaWVUCIQCqeAiXqEnwcdOb6DTFxKF2E2htppt7H4y1K8UVmF7s
    54  eg==
    55  -----END CERTIFICATE-----
    56  `
    57  
    58  var signCert = `-----BEGIN CERTIFICATE-----
    59  MIICPTCCAeOgAwIBAgIIAs64zJDLTNQwCgYIKoEcz1UBg3UwQjELMAkGA1UEBhMC
    60  Q04xDzANBgNVBAgMBua1meaxnzEPMA0GA1UEBwwG5p2t5beeMREwDwYDVQQKDAjm
    61  tYvor5VDQTAeFw0yMzAyMjIxMjIwMzNaFw0yNDAyMjIxMjIwMzNaMH0xCzAJBgNV
    62  BAYTAkNOMQ8wDQYDVQQIDAbmtZnmsZ8xDzANBgNVBAcMBuadreW3njEVMBMGA1UE
    63  CgwM5rWL6K+V5py65p6EMRUwEwYDVQQLDAzmtYvor5Xnu4Tnu4cxHjAcBgNVBAMM
    64  Fea1i+ivleacjeWKoeWZqOWQjeensDBZMBMGByqGSM49AgEGCCqBHM9VAYItA0IA
    65  BL4bEPQAKg3aEjsXsnEm4tSFOetUMYzUpLJyYKc0isNwiu8fNBZAihjDOVzQ3FQf
    66  BeZXJdxvbdC5s22m1E81mwSjgYcwgYQwDgYDVR0PAQH/BAQDAgbAMBMGA1UdJQQM
    67  MAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFBGRF+xJjaBurdse
    68  flfRaPUcBjFWMB8GA1UdIwQYMBaAFDaT4xTnRQn61e/qLxIt06GWPMKkMA8GA1Ud
    69  EQQIMAaHBH8AAAEwCgYIKoEcz1UBg3UDSAAwRQIhAKfa/H/f2OgTXhipfEPXPiHb
    70  nZFJyugnvKFkrijK8Qp5AiARlYEA2FR21H43/e/qu2lrp+ZUeYk3ve8nMd3yua9L
    71  Ag==
    72  -----END CERTIFICATE-----
    73  `
    74  
    75  var signKey = `-----BEGIN PRIVATE KEY-----
    76  MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQg1FlRx/WjmIFZ5dV4
    77  ghl1JwHIfMdGKLvYdPd1akXUCQSgCgYIKoEcz1UBgi2hRANCAAS+GxD0ACoN2hI7
    78  F7JxJuLUhTnrVDGM1KSycmCnNIrDcIrvHzQWQIoYwzlc0NxUHwXmVyXcb23QubNt
    79  ptRPNZsE
    80  -----END PRIVATE KEY-----
    81  `
    82  
    83  var expectedEncKey = `-----BEGIN PRIVATE KEY-----
    84  MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgyhwdf0K3AnMCLEbG
    85  B1yMjJLLlfQkGE53dvCPttt1BkCgCgYIKoEcz1UBgi2hRANCAARqnpTvwO+C6wGb
    86  8RaKZEs/ZaY8oExdX37JYQdAc8MUOYzMdQ+PddksG+n6DHvtJG6vVdotyp9h680k
    87  wHI/hvvb
    88  -----END PRIVATE KEY-----
    89  `
    90  
    91  func TestParseSignedEvnvelopedData(t *testing.T) {
    92  	var block *pem.Block
    93  	block, rest := pem.Decode([]byte(smSignedEvelopedTestData))
    94  	if len(rest) != 0 {
    95  		t.Fatal("unexpected remaining PEM block during decode")
    96  	}
    97  	p7Data, err := Parse(block.Bytes)
    98  	if err != nil {
    99  		t.Fatal(err)
   100  	}
   101  
   102  	if len(p7Data.Certificates) != 1 {
   103  		t.Fatal("should only one certificate")
   104  	}
   105  
   106  	recipients, err := p7Data.GetRecipients()
   107  	if err != nil {
   108  		t.Fatal(err)
   109  	}
   110  	if len(recipients) != 1 {
   111  		t.Fatal("should only one recipient")
   112  	}
   113  
   114  	block, rest = pem.Decode([]byte(signKey))
   115  	if len(rest) != 0 {
   116  		t.Fatal("unexpected remaining PEM block during decode")
   117  	}
   118  	signPriv, err := smx509.ParsePKCS8PrivateKey(block.Bytes)
   119  	if err != nil {
   120  		t.Fatal(err)
   121  	}
   122  	sm2SignPriv, ok := signPriv.(*sm2.PrivateKey)
   123  	if !ok {
   124  		t.Fatal("not expected key type")
   125  	}
   126  
   127  	signCertificate, err := smx509.ParseCertificatePEM([]byte(signCert))
   128  	if err != nil {
   129  		t.Fatal(err)
   130  	}
   131  
   132  	if !sm2SignPriv.PublicKey.Equal(signCertificate.PublicKey) {
   133  		t.Fatal("not one key pair")
   134  	}
   135  
   136  	encKeyBytes, err := p7Data.DecryptAndVerifyOnlyOne(signPriv, func() error {
   137  		return p7Data.Verify()
   138  	})
   139  	if err != nil {
   140  		t.Fatal(err)
   141  	}
   142  
   143  	block, rest = pem.Decode([]byte(expectedEncKey))
   144  	if len(rest) != 0 {
   145  		t.Fatal("unexpected remaining PEM block during decode")
   146  	}
   147  	encPriv, err := smx509.ParsePKCS8PrivateKey(block.Bytes)
   148  	if err != nil {
   149  		t.Fatal(err)
   150  	}
   151  	sm2EncPriv, ok := encPriv.(*sm2.PrivateKey)
   152  	if !ok {
   153  		t.Fatal("not expected key type")
   154  	}
   155  	if new(big.Int).SetBytes(encKeyBytes).Cmp(sm2EncPriv.D) != 0 {
   156  		t.Fatalf("the priv key is not same, got %x, expected %x", encKeyBytes, sm2EncPriv.D.Bytes())
   157  	}
   158  }
   159  
   160  func TestCreateSignedEvnvelopedDataSM(t *testing.T) {
   161  	rootCert, err := createTestCertificateByIssuer("PKCS7 Test Root CA", nil, smx509.SM2WithSM3, true)
   162  	if err != nil {
   163  		t.Fatal(err)
   164  	}
   165  	recipient, err := createTestCertificateByIssuer("PKCS7 Test Recipient", rootCert, smx509.SM2WithSM3, false)
   166  	if err != nil {
   167  		t.Fatal(err)
   168  	}
   169  	encryptKey, err := createTestCertificateByIssuer("PKCS7 Test Encrypt Key", rootCert, smx509.SM2WithSM3, false)
   170  	if err != nil {
   171  		t.Fatal(err)
   172  	}
   173  	privKey := make([]byte, 32)
   174  	sm2Key, ok := (*encryptKey.PrivateKey).(*sm2.PrivateKey)
   175  	if !ok {
   176  		t.Fatal("should be sm2 private key")
   177  	}
   178  	sm2Key.D.FillBytes(privKey)
   179  
   180  	testCipers := []pkcs.Cipher{pkcs.SM4ECB, pkcs.SM4CBC, pkcs.SM4GCM}
   181  	for _, cipher := range testCipers {
   182  		saed, err := NewSMSignedAndEnvelopedData(privKey, cipher)
   183  		if err != nil {
   184  			t.Fatal(err)
   185  		}
   186  		err = saed.AddSigner(rootCert.Certificate, *rootCert.PrivateKey)
   187  		if err != nil {
   188  			t.Fatal(err)
   189  		}
   190  		err = saed.AddRecipient(recipient.Certificate)
   191  		if err != nil {
   192  			t.Fatal(err)
   193  		}
   194  		result, err := saed.Finish()
   195  		if err != nil {
   196  			t.Fatal(err)
   197  		}
   198  
   199  		// fmt.Printf("%x\n", result)
   200  
   201  		// parse, decrypt, verify
   202  		p7Data, err := Parse(result)
   203  		if err != nil {
   204  			t.Fatal(err)
   205  		}
   206  		encKeyBytes, err := p7Data.DecryptAndVerify(recipient.Certificate, *recipient.PrivateKey, func() error {
   207  			return p7Data.Verify()
   208  		})
   209  		if err != nil {
   210  			t.Fatal(err)
   211  		}
   212  		if !bytes.Equal(encKeyBytes, privKey) {
   213  			t.Fatal("not same private key")
   214  		}
   215  	}
   216  }
   217  
   218  func TestCreateSignedEvnvelopedData(t *testing.T) {
   219  	rootCert, err := createTestCertificateByIssuer("PKCS7 Test Root CA", nil, smx509.ECDSAWithSHA256, true)
   220  	if err != nil {
   221  		t.Fatal(err)
   222  	}
   223  	recipient, err := createTestCertificateByIssuer("PKCS7 Test Recipient", rootCert, smx509.SHA256WithRSA, false)
   224  	if err != nil {
   225  		t.Fatal(err)
   226  	}
   227  	unsupportRecipient, err := createTestCertificateByIssuer("PKCS7 Test Unsupport Recipient", rootCert, smx509.ECDSAWithSHA256, false)
   228  	if err != nil {
   229  		t.Fatal(err)
   230  	}
   231  
   232  	encryptKey, err := createTestCertificateByIssuer("PKCS7 Test Encrypt Key", rootCert, smx509.ECDSAWithSHA256, false)
   233  	if err != nil {
   234  		t.Fatal(err)
   235  	}
   236  	privKey := make([]byte, 32)
   237  	ecdsaKey, ok := (*encryptKey.PrivateKey).(*ecdsa.PrivateKey)
   238  	if !ok {
   239  		t.Fatal("should be ecdsa private key")
   240  	}
   241  	ecdsaKey.D.FillBytes(privKey)
   242  
   243  	testCipers := []pkcs.Cipher{pkcs.AES256CBC, pkcs.AES256GCM}
   244  	for _, cipher := range testCipers {
   245  		saed, err := NewSignedAndEnvelopedData(privKey, cipher)
   246  		if err != nil {
   247  			t.Fatal(err)
   248  		}
   249  		saed.SetDigestAlgorithm(OIDDigestAlgorithmSHA256)
   250  		err = saed.AddSigner(rootCert.Certificate, *rootCert.PrivateKey)
   251  		if err != nil {
   252  			t.Fatal(err)
   253  		}
   254  		err = saed.AddRecipient(recipient.Certificate)
   255  		if err != nil {
   256  			t.Fatal(err)
   257  		}
   258  		if err = saed.AddRecipient(unsupportRecipient.Certificate); err.Error() != "pkcs7: only supports RSA/SM2 key" {
   259  			t.Fatal("not expected error message")
   260  		}
   261  
   262  		result, err := saed.Finish()
   263  		if err != nil {
   264  			t.Fatal(err)
   265  		}
   266  
   267  		// fmt.Printf("%x\n", result)
   268  
   269  		// parse, decrypt, verify
   270  		p7Data, err := Parse(result)
   271  		if err != nil {
   272  			t.Fatal(err)
   273  		}
   274  
   275  		recipients, err := p7Data.GetRecipients()
   276  		if err != nil {
   277  			t.Fatal(err)
   278  		}
   279  		if len(recipients) != 1 {
   280  			t.Fatal("should only one recipient")
   281  		}
   282  
   283  		if recipients[0].SerialNumber.Cmp(recipient.Certificate.SerialNumber) != 0 {
   284  			t.Errorf("Recipient serial number does not match.\n\tExpected:%s\n\tActual:%s", recipient.Certificate.SerialNumber, recipients[0].SerialNumber)
   285  		}
   286  		
   287  		if !bytes.Equal(recipients[0].RawIssuer, recipient.Certificate.RawIssuer) {
   288  			t.Errorf("Recipient issuer name does not match.\n\tExpected:%x\n\tActual:%x", recipient.Certificate.RawIssuer, recipients[0].RawIssuer)
   289  		}
   290  
   291  		encKeyBytes, err := p7Data.DecryptAndVerify(recipient.Certificate, *recipient.PrivateKey, func() error {
   292  			return p7Data.Verify()
   293  		})
   294  		if err != nil {
   295  			t.Fatal(err)
   296  		}
   297  		if !bytes.Equal(encKeyBytes, privKey) {
   298  			t.Fatal("not same private key")
   299  		}
   300  	}
   301  }