【问题标题】:How to AES GCM Encrypt / Decrypt using LibTom如何使用 LibTom 进行 AES GCM 加密/解密
【发布时间】:2019-01-04 23:05:28
【问题描述】:

LibTom 是一个出色的综合库,用于 C/C++ 中的加密和数学运算。

https://www.libtom.net/LibTomCrypt/

文档是从编写库的开发人员的角度编写的,因此有些示例不太清楚。

我花了一些时间弄清楚如何使用这个库执行 AES 加密和解密,并想在这里分享我的解决方案:

【问题讨论】:

    标签: encryption aes-gcm libtomcrypt


    【解决方案1】:

    AES 加密

    int key_len = 32; // 256-bit key
    int iv_len = 16;
    unsigned long taglen;
    unsigned char tag[16];
    
    int enc_len;
    unsigned char *enc_text;
    
    register_cipher(&aes_desc);
    
    enc_len = pt_len + 16; // Plain text + Tag length
    
    enc_text = (unsigned char*)calloc(enc_len + 1, 1);
    
    // For GCM there is no need to use the "adata" parameters, pass in NULL
    int err = gcm_memory(find_cipher("aes"), (const unsigned char*) in_key, key_len, (const unsigned char*) in_iv, iv_len, NULL, NULL, plain_text, pt_len, enc_text, tag, &taglen, GCM_ENCRYPT);
    
    // This is what took a while to figure out: the tag has to be manually appended to the encrypted text string
    memcpy(enc_text + pt_len, tag, taglen);
    

    AES 解密

    int key_len = 32; // 256-bit key
    int iv_len = 16;
    unsigned long taglen;
    unsigned char tag[16];
    
    int pt_len;
    unsigned char *plain_text;
    
    register_cipher(&aes_desc);
    
    plain_text = (unsigned char*)calloc(enc_len, 1);
    
    // For GCM there is no need to use the "adata" parameters, pass in NULL
    err = gcm_memory(find_cipher("aes"), (const unsigned char*) in_key, key_len, (const unsigned char*) in_iv, iv_len, NULL, NULL, plain_text, enc_text_len, enc_text, tag, &taglen, GCM_DECRYPT);
    
    pt_len = enc_text_len - 16; // Subtract taglen
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 2016-04-23
      • 2016-03-03
      • 2015-02-18
      • 1970-01-01
      • 2023-01-31
      • 2021-02-23
      相关资源
      最近更新 更多