TEE非对称加解密算法RSA加密和解密开发实例

/**
 * 自动分配存放秘钥对象
 *
 */
TEE_Result lge_utils_generate_keypair(TEE_ObjectHandle * rsa_key_obj)
{
    TEE_Result ret;
    ret = TEE_AllocateTransientObject(TEE_TYPE_RSA_KEYPAIR, RSA_KEY_SIZE, rsa_key_obj);
    if (ret != TEE_SUCCESS) {
        EMSG("Fail to allocate rsa key pair object, ret 0x%xn", ret);
        return ret;
    }
    ret = TEE_GenerateKey(*rsa_key_obj, RSA_KEY_SIZE, NULL, 0);
    if (ret != TEE_SUCCESS) {
        EMSG("Fail to generate rsa key, ret 0x%xn", ret);
        return ret;
    }
}

/**
 * 
 *
 */
TEE_Result lge_utils_rsa_encrypt(TEE_ObjectHandle rsa_key_obj, uint8_t *msg_buffer, size_t msg_len, uint8_t *encrypted_buffer, size_t *enc_len)
{
    TEE_Result ret;
    TEE_OperationHandle oper_enc = NULL;
    ret = TEE_AllocateOperation(&oper_enc, TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512, TEE_MODE_ENCRYPT, RSA_KEY_SIZE);
    if (ret != TEE_SUCCESS) {
        EMSG("Fail to allocate rsa encrypt operation, ret 0x%xn", ret);
        return ret;
    }
    ret = TEE_SetOperationKey(oper_enc, rsa_key_obj);
    if (ret != TEE_SUCCESS) {
        EMSG("Fail to set rsa encrypt key, ret 0x%xn", ret);
        TEE_FreeOperation(oper_enc);
        return ret;
    }
    ret = TEE_AsymmetricEncrypt(oper_enc, NULL, 0, msg_buffer, msg_len, encrypted_buffer, enc_len);
    if (ret != TEE_SUCCESS)
        EMSG("Fail to do rsa encrypt, ret 0x%xn", ret);
    EMSG("TEE_AsymmetricEncrypt success");
    TEE_FreeOperation(oper_enc);
    return ret;
}
/**
 * 
 *
 */
TEE_Result lge_utils_rsa_decrypt(TEE_ObjectHandle rsa_key_obj, uint8_t *msg_buffer, size_t msg_len, uint8_t *decrypted_buffer, size_t *dec_len)
{
    TEE_Result ret;
    TEE_OperationHandle oper_enc = NULL;
    ret = TEE_AllocateOperation(&oper_enc, TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512, TEE_MODE_DECRYPT, RSA_KEY_SIZE);
    if (ret != TEE_SUCCESS) {
        EMSG("Fail to allocate rsa encrypt operation, ret 0x%xn", ret);
        return ret;
    }
    ret = TEE_SetOperationKey(oper_enc, rsa_key_obj);
    if (ret != TEE_SUCCESS) {
        EMSG("Fail to set rsa encrypt key, ret 0x%xn", ret);
        TEE_FreeOperation(oper_enc);
        return ret;
    }
    ret = TEE_AsymmetricDecrypt(oper_enc, NULL, 0, msg_buffer, msg_len, decrypted_buffer, dec_len);
    if (ret != TEE_SUCCESS)
        EMSG("Fail to do rsa encrypt, ret 0x%xn", ret);
    EMSG("dec_len %d",*dec_len);
    EMSG("TEE_AsymmetricDecrypt success");
    TEE_FreeOperation(oper_enc);
    return ret;
}

  

posted @ 2023-01-06 17:13  颜小雀  阅读(468)  评论(8编辑  收藏  举报