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++代码

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

     test_main()
{

    int m_BlockSize = 8;
    unsigned char in[]="A";
    unsigned char *out=NULL;
    out=test_pkcs5padding(in, 8);
    unsigned char in2[] ="AA";
    out=test_pkcs5padding(in2,8);
    unsigned char in3[] = "AAA";
    out = test_pkcs5padding(in3,8);
    unsigned char in8[] = "AAAAAAAA";
    out = test_pkcs5padding(in8, 8);
    
}


 

public byte[] pkcs5_padding(byte[] source) {
        int sourceLength = source.length;
        int paddingLength = sourceLength  + (8- (sourceLength % 8));
        byte[] paddingResult = new byte[paddingLength];
        System.arrayCopy(source, 0, paddingResult, 0, sourceLength);
        for (int i = sourceLength; i < paddingLength; i++) {
            paddingResult[i] = (byte)(paddingLength - (sourceLength % 8);
        }
        return paddingResult;
    }

你可能感兴趣的:(c++,开发语言)