In the recent project, SM2 and SM4 state secret algorithms need to be implemented through C language. Here, I implement them based on GMSSL, which have been implemented in 5 environments and used in the production environment.

1. GMSSL compilation

GMSSL compilation varies in different environments, here I provide Windows 64, Arm64, Linux64, Android, HIMIX200 Hith chip environment compilation method, the portal is as follows:

Gmssl official website address

Gmssl compiler for all platforms

For those of you who are more lazy, I also provide you with a library of the five environments mentioned above. The portal is as follows:

Gmssl link library (himix200, android, arm64, linux64, windows64)

2. SM4 implementation

#include <openssl/sms4.h>

int main(void) {
    // The encryption parameter is initialized
    sms4_key_t sms4_key_enc;
    unsigned char *plain_text = { 0 };
    unsigned char *key = "01234567891234560123456789123456";
    unsigned char *iv = "0123456789123456";
    / / SM4 encryption
    memcpy(sms4_key.rk, key, 32);
    sms4_set_encrypt_key(&sms4_key, iv);
    sms4_cbc_encrypt(plain_text, enc_text, 64, sms4_key_enc.rk, iv, 1);

    // Decrypt parameter initialization
    sms4_key_t sms4_key_decrypt;
    / / SM4 decryption
    memcpy(sms4_key.rk, key, 32);
    sms4_set_decrypt_key(reinterpret_cast<sms4_key_t *>(sms4_key_decrypt->rk), iv);
    sms4_cbc_encrypt((uint8_t *) data, plaintext, 64.reinterpret_cast<const sms4_key_t *>(sms4_key_decrypt->rk), iv, 0);
    return 0;
}
Copy the code

Sms4_set_encrypt_key, SMs4_set_decrypt_key, and sms4_cbC_ENCRYPT can be implemented.

SM4 code I have extracted from GMSSL library, if you do not want to introduce GMSSL library to implement SM4 algorithm, you can directly use the following code (and use the library is the same), the portal is as follows:

SM4 Clean edition implementation (independent of any libraries)