AES应该使用哪种填充? [英] What kind of padding should AES use?

查看:82
本文介绍了AES应该使用哪种填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了AES加密(家庭作业),但是我偶然发现了填充消息的问题.

I have implemented the AES encryption (homework), but I stumble upon the problem of padding the messages.

如果我的消息是这样的字节数组:

If my messages are arrays of bytes as such:

public byte[] encrypt(byte[] message) {
    int size = (int) Math.ceil(message.length / 16.0);
    byte[] result = new byte[size * 16];
    for (int i = 0; i < size; i++) {
        if ((i+1) * 16 > message.length){
            //padding here????
        } else {
            byte[] block = Arrays.copyOfRange(message, i * 16, (i + 1) * 16);
            byte[] encryptedBlock = encryptBlock(block);                
            System.arraycopy(encryptedBlock, 0, result, i*16, 16);
        }
    }
    return result;
}

如何填充此类消息?

我不能使用零填充",因为每个字节可能为零,并且可能会影响带有尾随零的此类消息.

I cannot use Zero Padding because the each byte could be zero, and it might affect such a message with trailing zeros.

即使在此处(描述AES加密的论文)

I cannot find any reference to how is this done not even here (the paper describing the AES encryption)

推荐答案

您可以使用多种方法,从简单到高级.布鲁斯·施耐尔(Bruce Schneier)提出了两种相当简单的方法:

There are a number of methods you can use, from simple to advanced. Bruce Schneier suggests two rather simple methods:

一种方法是用n个字节填充最后一个块,所有字节都带有值n,这就是Alex Wien建议的.这有问题(包括限制您限制小于256字节长的块大小).这种填充模式称为PKCS#7填充(用于16个字节的块)或PKCS#5填充(用于8个字节的块).

One is to pad the last block with n bytes all with value n, which is what Alex Wien suggested. This has issues (including restricting you to block sizes that are less than 256 bytes long). This padding mode is known as PKCS#7 padding (for 16 byte blocks) or PKCS#5 padding (for 8 byte blocks).

另一种方法是附加一个值为0x80的字节(二进制值为1000 0000的字节),后跟所需的零字节,以填充最后一个块.此方法称为ISO填充,它是ISO/IEC 9797-1填充方法2的缩写.填充本身是位级填充,将单个值为1的位相加,然后将0值的位相加,直到到达该块为止大小.

The other is to append a byte with value 0x80 (a byte with value 1000 0000 in binary) followed by as many zero bytes as needed to fill the last block. This method is known as ISO padding, which is short for ISO/IEC 9797-1 padding method 2. The padding itself is bit-level padding, a single bit valued 1 is added, and then add 0 valued bits until you reach the block size.

至于如何知道是否填充了一条消息,答案是一条消息将总是被填充 :即使该消息的最后一块完全适合一个块(即,该消息的大小)消息是块大小的倍数),则您必须添加一个虚拟的最后一个块.

As for how to know whether a message is padded, the answer is a message will always be padded: even if the last chunk of the message fits perfectly inside a block (i.e. the size of the message is a multiple of the block size), you will have to add a dummy last block.

如果您有兴趣研究一些更高级的方法,请在Wikipedia上查找一种称为密文窃取的技术: http://en.wikipedia.org/wiki/Ciphertext_stealing

If you are interested in researching some of the more advanced methods, look up a technique called ciphertext stealing on wikipedia: http://en.wikipedia.org/wiki/Ciphertext_stealing

这篇关于AES应该使用哪种填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆