我要评分
获取效率
正确性
完整性
易理解

Obtaining/Setting Tags for SM4-GCM

The SM4-GCM algorithm uses tags for integrity check. During data encryption, a tag is generated in the final phase, and users can obtain the tag through the EVP_CIPHER_CTX_ctrl interface. During data decryption, users can set a tag using the EVP_CIPHER_CTX_ctrl interface, and in the final phase, the generated tag is compared with the set tag to achieve data integrity check.

    EVP_CIPHER_CTX* ectx = EVP_CIPHER_CTX_new();
    EVP_EncryptInit_ex(ectx, gcm, g_engine, g_key16, g_iv16);
    for (int off = 0; off < 32; off += 8) {
        EVP_EncryptUpdate(ectx, ct + totl_enc, &outl, pt + off, 8);
        totl_enc += outl;
    }
    EVP_EncryptFinal_ex(ectx, ct + totl_enc, &outl);
    totl_enc += outl;
    // get tag
    EVP_CIPHER_CTX_ctrl(ectx, EVP_CTRL_GCM_GET_TAG, 16, tag);
    EVP_CIPHER_CTX_free(ectx);
    EVP_CIPHER_CTX* dctx = EVP_CIPHER_CTX_new();
    EVP_DecryptInit_ex(dctx, gcm, g_engine, g_key16, g_iv16);
    // set tag
    EVP_CIPHER_CTX_ctrl(dctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
    for (int off = 0; off < totl_enc; off += 8) {
        EVP_DecryptUpdate(dctx, dt + totl_dec, &outl, ct + off, 8);
        totl_dec += outl;
    }
    EVP_DecryptFinal_ex(dctx, dt + totl_dec, &outl);
    totl_dec += outl;
    EVP_CIPHER_CTX_free(dctx);