密码库LibTomCrypt学习记录——(2.3)分组密码算法的工作模式——ECB代码示例

本文主要是介绍密码库LibTomCrypt学习记录——(2.3)分组密码算法的工作模式——ECB代码示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

以下代码实现了AES-ECB的正确性测试(标准测试数据),以及性能测试

说明:

1. 代码里面使用了一个Str2Num函数,它将测试向量中的字符串转为十六进制字节数据,可自行实现。

2. 测试向量出处为NIST SP 800-38A (Recommendation for Block Cipher  Modes of Operation:Methods and Techniques)

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

                                                          Test_ECB_AES.h

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

#include <Windows.h>
#include "tomcrypt.h"
#include "TestMode.h"
 
typedef struct NistECBTestVector_st{
    char *    name;//test vetor name
    int        keylen;
    int        msglen;
    BYTE *    key[1];    // 密钥
    BYTE *    IV[1];    // 初始化向量
    BYTE *    pt[4];    //    明文,暂时最多支持四段明文
    BYTE *    ct[4];    //    密文,暂时最多支持四段明文
    
    BYTE *    nonce[1];
    BYTE *    associated_data[1];
    BYTE *    mac[1];
} NistECBTestVector; 

    //    数据来源 
    //    NIST SP 800-38A (Recommendation for Block Cipher  Modes of Operation:Methods and Techniques).pdf
    NistECBTestVector ecb_vect[] = {
        {//vect[0] 
            /*name*/    "F.1.1 key=128 Encrypt",
            /*keylen*/    16, 
            /*msglen*/    16*4,
            /*Key*/        "2b7e151628aed2a6abf7158809cf4f3c",
            /*IV */        "",//ECB无初始化向量
            {// pt 
                "6bc1bee22e409f96e93d7e117393172a",
                "ae2d8a571e03ac9c9eb76fac45af8e51",
                "30c81c46a35ce411e5fbc1191a0a52ef",
                "f69f2445df4f9b17ad2b417be66c3710"
            },
            {//ct
                "3ad77bb40d7a3660a89ecaf32466ef97",
                "f5d3d58503b9699de785895a96fdbaaf",
                "43b1cd7f598ece23881b00e3ed030688",
                "7b0c785e27e8ad3f8223207104725dd4"
            }
        },
        //
        {//vect[1] 
            /*name*/    "F.1.2 key=128 Decrypt",
            /*keylen*/    16, 
            /*msglen*/    16*4,
            /*Key*/        "2b7e151628aed2a6abf7158809cf4f3c",
            /*IV */        "",//ECB无初始化向量
            {//ct    //解密时明文密文相反而已
                "3ad77bb40d7a3660a89ecaf32466ef97",
                "f5d3d58503b9699de785895a96fdbaaf",
                "43b1cd7f598ece23881b00e3ed030688",
                "7b0c785e27e8ad3f8223207104725dd4"
            },
            {// pt     //解密时明文密文相反而已
                "6bc1bee22e409f96e93d7e117393172a",
                "ae2d8a571e03ac9c9eb76fac45af8e51",
                "30c81c46a35ce411e5fbc1191a0a52ef",
                "f69f2445df4f9b17ad2b417be66c3710"
            }
        },
        //
        {//vect[2]
            /*name*/    "F.1.3 key=192 Encrypt",
            /*keylen*/    24, 
            /*msglen*/    16*4,
            /*Key*/        "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
            /*IV */        "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
            {// pt 
                "6bc1bee22e409f96e93d7e117393172a",
                "ae2d8a571e03ac9c9eb76fac45af8e51",
                "30c81c46a35ce411e5fbc1191a0a52ef",
                "f69f2445df4f9b17ad2b417be66c3710"
            },
            {//ct
                "bd334f1d6e45f25ff712a214571fa5cc",
                "974104846d0ad3ad7734ecb3ecee4eef",
                "ef7afd2270e2e60adce0ba2face6444e",
                "9a4b41ba738d6c72fb16691603c18e0e"
            }
        },
            //
        {//vect[3] 
            /*name*/    "F.1.4 key=192 Decrypt",
            /*keylen*/    24, 
            /*msglen*/    16*4,
            /*Key*/        "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
            /*IV */        "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
            {//ct    //解密时明文密文相反而已
                "bd334f1d6e45f25ff712a214571fa5cc",
                "974104846d0ad3ad7734ecb3ecee4eef",
                "ef7afd2270e2e60adce0ba2face6444e",
                "9a4b41ba738d6c72fb16691603c18e0e"
            },
            {// pt     //解密时明文密文相反而已
                "6bc1bee22e409f96e93d7e117393172a",
                "ae2d8a571e03ac9c9eb76fac45af8e51",
                "30c81c46a35ce411e5fbc1191a0a52ef",
                "f69f2445df4f9b17ad2b417be66c3710"
            }
        },
        // 
        {//vect[4]
            /*name*/    "F.1.5 key=256 Encrypt",
            /*keylen*/    32, 
            /*msglen*/    16*4,
            /*Key*/        "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
            /*IV */        "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
            {// pt 
                "6bc1bee22e409f96e93d7e117393172a",
                "ae2d8a571e03ac9c9eb76fac45af8e51",
                "30c81c46a35ce411e5fbc1191a0a52ef",
                "f69f2445df4f9b17ad2b417be66c3710"
            },
            {//ct
                "f3eed1bdb5d2a03c064b5a7e3db181f8",
                "591ccb10d410ed26dc5ba74a31362870",
                "b6ed21b99ca6f4f9f153e7b1beafed1d",
                "23304b7a39f9f3ff067d8d8f9e24ecc7"
            }
        },
            //
        {//vect[5] 
            /*name*/    "F.1.6 key=256 Decrypt",
            /*keylen*/    32, 
            /*msglen*/    16*4,
            /*Key*/        "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
            /*IV */        "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
            {//ct    //解密时明文密文相反而已
                "f3eed1bdb5d2a03c064b5a7e3db181f8",
                "591ccb10d410ed26dc5ba74a31362870",
                "b6ed21b99ca6f4f9f153e7b1beafed1d",
                "23304b7a39f9f3ff067d8d8f9e24ecc7"
            },
            {// pt     //解密时明文密文相反而已
                "6bc1bee22e409f96e93d7e117393172a",
                "ae2d8a571e03ac9c9eb76fac45af8e51",
                "30c81c46a35ce411e5fbc1191a0a52ef",
                "f69f2445df4f9b17ad2b417be66c3710"
            }
        }
    }; 

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

                                                          Test_ECB_AES.cpp

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

#include <Windows.h>
#include "tomcrypt.h"
#include "TestMode.h"
#include "Test_ECB_AES.h"
  
 
int Test_ECB_AES_Alg(void)
{
    int idx, err, i, res;
    BYTE buf[64];
    symmetric_ECB ctr;
    int keylen, msglen;
    BYTE key[32], IV[16], pt[64], ct[64];
    char *p_operate;
    IV[0] = 0;

    /* AES can be under rijndael or aes... try to find it */ 
    if ( register_cipher (&aes_desc) != CRYPT_OK ) {     return CRYPT_INVALID_CIPHER; }
    if ((idx = find_cipher("aes")) == -1)  {      return CRYPT_NOP; }
    printf("\nTest ECB AES Begin!\n" );
    for ( i = 0; i < (int)(sizeof(ecb_vect)/sizeof(ecb_vect[0])); i++ )
    {
        keylen = ecb_vect[i].keylen;
        msglen = ecb_vect[i].msglen;

        Str2Num(ecb_vect[i].key, 1, key);
//        ChangeText(vect[i].IV, 1, IV);
        Str2Num(ecb_vect[i].pt, 4, pt);
        Str2Num(ecb_vect[i].ct, 4, ct);

        if ((err = ecb_start(idx, key, keylen, 0, &ctr)) != CRYPT_OK)
        {
            return err;
        }

        p_operate = ecb_vect[i].name + strlen(ecb_vect[i].name) - strlen("Encrypt");
        if (strcmp( p_operate, "Encrypt") == 0 )
        {
            if ((err = ecb_encrypt( pt, buf, msglen, &ctr)) != CRYPT_OK) 
            {
                return err;
            }
        }
        else if (strcmp( p_operate, "Decrypt") == 0 )
        {
            if ((err = ecb_decrypt( pt, buf, msglen, &ctr)) != CRYPT_OK) 
            {
                return err;
            }
        }
        else
        {
            printf("Test Vetor : operate err!  %s \n",ecb_vect[i].name );
        }
        
        ecb_done(&ctr);

        res = XMEMCMP(buf, ct, msglen);
        printf("Test Vetor : %s pass ? %s \n",ecb_vect[i].name, (res == 0)?"Yes":"No" );
    }
    unregister_cipher (&aes_desc);

    printf("\nTest ECB AES Finish!\n" );
    return CRYPT_OK; 
}  
//
int Test_ECB_AES_Speed(char *p_cipher_name )//test speed

    int idx, err, i, res = 0,counter, counter_bound = 1000*1000*10;
    BYTE buf[64];
    symmetric_ECB ctr;
    int keylen, msglen, len;
    BYTE key[32], IV[16], pt[64], ct[64];
    char *p_operate;
    LARGE_INTEGER frequence, start_time, end_time, cost_time;
    double use_time;
    double speed;
//    const struct ltc_cipher_descriptor *p_alg_desc = (&aes_desc);

    QueryPerformanceFrequency( &frequence);
    IV[0] = 0;

    /* AES can be under rijndael or aes... try to find it */ 
//    if ( register_cipher (p_alg_desc) != CRYPT_OK ) {    return CRYPT_INVALID_CIPHER; }
//    if ((idx = find_cipher(p_alg_desc->name)) == -1)  {    return CRYPT_NOP; } 
    if ((idx = find_cipher(p_cipher_name)) == -1)    
    {
        printf("\nTest ECB Speed Err! Not Find Cipher %s\n", p_cipher_name );    
        return CRYPT_NOP; 
    }  

    

    printf("Test ECB Speed Begin ! Use Alg %s\n", p_cipher_name );    

    for ( i = 0; i < (int)(sizeof(ecb_vect)/sizeof(ecb_vect[0])); i++ )
    {
        keylen = ecb_vect[i].keylen;
        msglen = ecb_vect[i].msglen;
        len = cipher_descriptor[idx].block_length;
        Str2Num(ecb_vect[i].key, 1, key);
//        ChangeText(vect[i].IV, 1, IV);
        Str2Num(ecb_vect[i].pt, 4, pt);
        Str2Num(ecb_vect[i].ct, 4, ct);
        if (keylen > cipher_descriptor[idx].max_key_length)
        {
            keylen = cipher_descriptor[idx].max_key_length;//
        }
        if (keylen < cipher_descriptor[idx].min_key_length)
        {
            keylen = cipher_descriptor[idx].min_key_length;//
        }

        if ((err = ecb_start(idx, key, keylen, 0, &ctr)) != CRYPT_OK)
        {
             break;//return err;
        }

        p_operate = ecb_vect[i].name + strlen(ecb_vect[i].name) - strlen("Encrypt");
        if (strcmp( p_operate, "Encrypt") == 0 )
        { 
            memcpy(buf, pt, 64);
            QueryPerformanceCounter(&start_time); // cost time
            for (counter = 0; counter < counter_bound; ++counter) 
            {
                ecb_encrypt(buf, buf, /*16*/len, &ctr);
            } 
            QueryPerformanceCounter(&end_time);// cost time
            cost_time.QuadPart = end_time.QuadPart - start_time.QuadPart;
        }
        else if (strcmp( p_operate, "Decrypt") == 0 )
        {
            memcpy(buf, pt, 64);
            QueryPerformanceCounter(&start_time); // cost time
            for (counter = 0; counter < counter_bound; ++counter ) 
            {
                ecb_decrypt(buf, buf, /*16*/len, &ctr);
            }
            QueryPerformanceCounter(&end_time);// cost time
            cost_time.QuadPart = end_time.QuadPart - start_time.QuadPart;
        }
        else
        {
            printf("Test Vector : operate err!  %s \n",ecb_vect[i].name );
        }
        
        ecb_done(&ctr);

//        res = XMEMCMP(buf, ct, msglen);
        use_time = cost_time.QuadPart / (double)(frequence.QuadPart);
        speed = ( counter_bound / 1000000 ) * len * 8 / use_time ;
        printf("%s key = %d, cost %8.3f s, speed %8.3f mbps \n", p_operate, keylen, use_time, speed);
    }

    printf("Test ECB Speed Finish! Use Alg %s\n", p_cipher_name );
    printf("\n###############################################\n\n", p_cipher_name );
    return CRYPT_OK; 
}


void register_algs(void)

    register_cipher (&aes_desc);//
    register_cipher (&blowfish_desc);//
    register_cipher (&xtea_desc);
    register_cipher (&rc5_desc);
    register_cipher (&rc6_desc);
//    register_cipher (&saferp_desc);//
     register_cipher (&twofish_desc);//
//     register_cipher (&safer_k64_desc);
//     register_cipher (&safer_sk64_desc);
//     register_cipher (&safer_k128_desc);
//     register_cipher (&safer_sk128_desc);
    register_cipher (&rc2_desc);
    register_cipher (&des_desc);//
    register_cipher (&des3_desc);//
    register_cipher (&cast5_desc);//
    register_cipher (&noekeon_desc);
    register_cipher (&skipjack_desc);
    register_cipher (&khazad_desc);//
    register_cipher (&anubis_desc); //
    register_cipher (&kseed_desc);//
    register_cipher (&kasumi_desc); //
//    register_cipher (&multi2_desc); //
}

int Test_ECB_AES(void)
{
//    Test_ECB_AES_Alg( );
    
    int i = 0;
    register_algs( );


    for ( i = 0;i<TAB_SIZE;i++)
    {
        if (cipher_descriptor[i].name != NULL )
        {     
            Test_ECB_AES_Speed( cipher_descriptor[i].name );
        }
    }

    return 1;
}

ecb\ecb_XXX.c
/**
   Initialize a ECB context
   @param cipher      The index of the cipher desired
   @param key         The secret key 
   @param keylen      The length of the secret key (octets)
   @param num_rounds  Number of rounds in the cipher desired (0 for default)
   @param ecb         The ECB state to initialize
   @return CRYPT_OK if successful
*/
int ecb_start(int cipher, const unsigned char *key, int keylen, int num_rounds, symmetric_ECB *ecb)
{
   int err;
   LTC_ARGCHK(key != NULL);
   LTC_ARGCHK(ecb != NULL);

   if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
      return err;
   }
   ecb->cipher = cipher;
   ecb->blocklen = cipher_descriptor[cipher].block_length;
   return cipher_descriptor[cipher].setup(key, keylen, num_rounds, &ecb->key);
}
 


/**
  ECB encrypt
  @param pt     Plaintext
  @param ct     [out] Ciphertext
  @param len    The number of octets to process (must be multiple of the cipher block size)
  @param ecb    ECB state
  @return CRYPT_OK if successful
*/
int ecb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_ECB *ecb)
{
   int err;
   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(ecb != NULL);
   if ((err = cipher_is_valid(ecb->cipher)) != CRYPT_OK) {
       return err;
   }
   if (len % cipher_descriptor[ecb->cipher].block_length) {
      return CRYPT_INVALID_ARG;
   }

   /* check for accel */
   if (cipher_descriptor[ecb->cipher].accel_ecb_encrypt != NULL) {
      return cipher_descriptor[ecb->cipher].accel_ecb_encrypt(pt, ct, len / cipher_descriptor[ecb->cipher].block_length, &ecb->key);
   } else {
      while (len) {
         if ((err = cipher_descriptor[ecb->cipher].ecb_encrypt(pt, ct, &ecb->key)) != CRYPT_OK) {
            return err;
         }
         pt  += cipher_descriptor[ecb->cipher].block_length;
         ct  += cipher_descriptor[ecb->cipher].block_length;
         len -= cipher_descriptor[ecb->cipher].block_length;
      }
   }
   return CRYPT_OK;
}


/**
  ECB decrypt
  @param ct     Ciphertext
  @param pt     [out] Plaintext
  @param len    The number of octets to process (must be multiple of the cipher block size)
  @param ecb    ECB state
  @return CRYPT_OK if successful
*/
int ecb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_ECB *ecb)
{
   int err;
   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(ecb != NULL);
   if ((err = cipher_is_valid(ecb->cipher)) != CRYPT_OK) {
       return err;
   }
   if (len % cipher_descriptor[ecb->cipher].block_length) {
      return CRYPT_INVALID_ARG;
   }

   /* check for accel */
   if (cipher_descriptor[ecb->cipher].accel_ecb_decrypt != NULL) {
      return cipher_descriptor[ecb->cipher].accel_ecb_decrypt(ct, pt, len / cipher_descriptor[ecb->cipher].block_length, &ecb->key);
   } else {
      while (len) {
         if ((err = cipher_descriptor[ecb->cipher].ecb_decrypt(ct, pt, &ecb->key)) != CRYPT_OK) {
            return err;
         }
         pt  += cipher_descriptor[ecb->cipher].block_length;
         ct  += cipher_descriptor[ecb->cipher].block_length;
         len -= cipher_descriptor[ecb->cipher].block_length;
      }
   }
   return CRYPT_OK;
}


/** Terminate the chain
  @param ecb    The ECB chain to terminate
  @return CRYPT_OK on success
*/
int ecb_done(symmetric_ECB *ecb)
{
   int err;
   LTC_ARGCHK(ecb != NULL);

   if ((err = cipher_is_valid(ecb->cipher)) != CRYPT_OK) {
      return err;
   }
   cipher_descriptor[ecb->cipher].done(&ecb->key);
   return CRYPT_OK;
}

   

这篇关于密码库LibTomCrypt学习记录——(2.3)分组密码算法的工作模式——ECB代码示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/295216

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

不懂推荐算法也能设计推荐系统

本文以商业化应用推荐为例,告诉我们不懂推荐算法的产品,也能从产品侧出发, 设计出一款不错的推荐系统。 相信很多新手产品,看到算法二字,多是懵圈的。 什么排序算法、最短路径等都是相对传统的算法(注:传统是指科班出身的产品都会接触过)。但对于推荐算法,多数产品对着网上搜到的资源,都会无从下手。特别当某些推荐算法 和 “AI”扯上关系后,更是加大了理解的难度。 但,不了解推荐算法,就无法做推荐系

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

康拓展开(hash算法中会用到)

康拓展开是一个全排列到一个自然数的双射(也就是某个全排列与某个自然数一一对应) 公式: X=a[n]*(n-1)!+a[n-1]*(n-2)!+...+a[i]*(i-1)!+...+a[1]*0! 其中,a[i]为整数,并且0<=a[i]<i,1<=i<=n。(a[i]在不同应用中的含义不同); 典型应用: 计算当前排列在所有由小到大全排列中的顺序,也就是说求当前排列是第

csu 1446 Problem J Modified LCS (扩展欧几里得算法的简单应用)

这是一道扩展欧几里得算法的简单应用题,这题是在湖南多校训练赛中队友ac的一道题,在比赛之后请教了队友,然后自己把它a掉 这也是自己独自做扩展欧几里得算法的题目 题意:把题意转变下就变成了:求d1*x - d2*y = f2 - f1的解,很明显用exgcd来解 下面介绍一下exgcd的一些知识点:求ax + by = c的解 一、首先求ax + by = gcd(a,b)的解 这个

综合安防管理平台LntonAIServer视频监控汇聚抖动检测算法优势

LntonAIServer视频质量诊断功能中的抖动检测是一个专门针对视频稳定性进行分析的功能。抖动通常是指视频帧之间的不必要运动,这种运动可能是由于摄像机的移动、传输中的错误或编解码问题导致的。抖动检测对于确保视频内容的平滑性和观看体验至关重要。 优势 1. 提高图像质量 - 清晰度提升:减少抖动,提高图像的清晰度和细节表现力,使得监控画面更加真实可信。 - 细节增强:在低光条件下,抖

【数据结构】——原来排序算法搞懂这些就行,轻松拿捏

前言:快速排序的实现最重要的是找基准值,下面让我们来了解如何实现找基准值 基准值的注释:在快排的过程中,每一次我们要取一个元素作为枢纽值,以这个数字来将序列划分为两部分。 在此我们采用三数取中法,也就是取左端、中间、右端三个数,然后进行排序,将中间数作为枢纽值。 快速排序实现主框架: //快速排序 void QuickSort(int* arr, int left, int rig

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来