• C++-openssl-aes-cbc-pkcs5


    PKCS#5填充是PKCS#7填充的一个子集,在PKCS#7填充时BlockSize为8的时候,PKCS#5与PKCS#7填充是一样的,在BlockSize不同时PKCS#5与PKCS#7填充是不同的
    PKCS#5填充是将数据填充到8的倍数,
    填充后数据长度的计算公式:
    定于元数据长度为x,
    填充后的长度是 x + (8 - (x % 8)),
    填充的数据是 8 - (x % 8)

    示例:
    1byte
      数据数 0x41
        填充前:0x41
        填充后:0x410x070x070x070x070x070x070x07

    2byte
      数据数 0x41
        填充前:0x410x41
        填充后:0x410x410x060x060x060x060x060x06

    3byte
      数据数 0x41
      填充前:0x410x410x41
      填充后:0x410x410x410x050x050x050x050x05

    4byte
      数据数 0x41
      填充前:0x410x410x410x41
       填充后:0x410x410x410x410x040x040x040x04

    5byte
      数据数 0x41
      填充前:0x410x410x410x410x41
       填充后:0x410x410x410x410x410x030x030x03

    6byte
       数据数 0x41
       填充前:0x410x410x410x410x410x41
       填充后:0x410x410x410x410x410x410x020x02

    7byte
       数据数 0x41
       填充前:0x410x410x410x410x410x410x41
       填充后:0x410x410x410x410x410x410x410x01

    8byte
     数据数 0x41
     填充前:0x410x410x410x410x410x410x410x41
      填充后:0x410x410x410x410x410x410x410x410x080x080x080x080x080x080x080x08


    以下是c++代码

    1. unsigned char* test_pkcs5padding(unsigned char* in, int m_BlockSize)
    2. {
    3. int inlen = strlen((char*)in); //1.获取输入长度
    4. int outlen = inlen + (8 - (inlen % 8)); //2.计算输出长度
    5. unsigned char* out = new unsigned char[outlen]; //3.创建输出buf
    6. memcpy(out, in, inlen); //4.out
    7. for (int i = inlen; i < outlen; i++) //5.填充out 中剩余的位数
    8. {
    9. int paddingval = (outlen - (inlen % 8));
    10. out[i] = paddingval;
    11. }
    12. return out;
    13. }

    1. test_main()
    2. {
    3. int m_BlockSize = 8;
    4. unsigned char in[]="A";
    5. unsigned char *out=NULL;
    6. out=test_pkcs5padding(in, 8);
    7. unsigned char in2[] ="AA";
    8. out=test_pkcs5padding(in2,8);
    9. unsigned char in3[] = "AAA";
    10. out = test_pkcs5padding(in3,8);
    11. unsigned char in8[] = "AAAAAAAA";
    12. out = test_pkcs5padding(in8, 8);
    13. }


     

    1. public byte[] pkcs5_padding(byte[] source) {
    2.         int sourceLength = source.length;
    3.         int paddingLength = sourceLength  + (8- (sourceLength % 8));
    4.         byte[] paddingResult = new byte[paddingLength];
    5.         System.arrayCopy(source, 0, paddingResult, 0, sourceLength);
    6.         for (int i = sourceLength; i < paddingLength; i++) {
    7.             paddingResult[i] = (byte)(paddingLength - (sourceLength % 8);
    8.         }
    9.         return paddingResult;
    10.     }

  • 相关阅读:
    JS前端使用Blob和File读取文件的操作代码
    自定义注解打印日志与耗时
    React-RouterV6版本的使用
    WPF 入门笔记 - 01 - 入门基础以及常用布局
    【Android UI】贝塞尔曲线 ② ( 二阶贝塞尔曲线公式 | 三阶贝塞尔曲线及公式 | 高阶贝塞尔曲线 )
    Linux|僵死进程
    【Vue】Vuex详解,一文读懂并使用Vuex
    python面向对象
    go-zero 是如何实现计数器限流的?
    洛谷P1601
  • 原文地址:https://blog.csdn.net/aggie4628/article/details/133903979