2

我想将AES加密与ISO9797 M2 Padding. 但是在java下不能按标准填充模式Cipher Algorithm Padding
..如何实现?

谢谢

4

2 回答 2

4

如果它在标准 Java 中不可用,那么您可以自己实现它,并将适当的字节添加到明文的末尾。然后使用加密,NoPadding这样您就不会添加额外的填充。再次使用解密NoPadding,然后自己删除填充。

填充方案实现起来非常简单:

add an 0x80 byte
while not at block boundary
  add an 0x00 byte
endwhile

我快速浏览了 Bouncy Castle 库,它似乎也没有 ISO 9797。

于 2012-06-21T11:16:46.457 回答
1

请参阅从 Bouncy Castle 复制的以下代码。它主要在 Bouncy Castle提供程序中用于 DES MAC 算法,但您可以在 Bouncy Castle 的轻量级加密库中简单地使用它,或者将其用作您自己实现的基础:

package org.bouncycastle.crypto.paddings;

import java.security.SecureRandom;

import org.bouncycastle.crypto.InvalidCipherTextException;

/**
 * A padder that adds the padding according to the scheme referenced in
 * ISO 7814-4 - scheme 2 from ISO 9797-1. The first byte is 0x80, rest is 0x00
 */
public class ISO7816d4Padding
    implements BlockCipherPadding
{
    /**
     * Initialise the padder.
     *
     * @param random - a SecureRandom if available.
     */
    public void init(SecureRandom random)
        throws IllegalArgumentException
    {
        // nothing to do.
    }

    /**
     * Return the name of the algorithm the padder implements.
     *
     * @return the name of the algorithm the padder implements.
     */
    public String getPaddingName()
    {
        return "ISO7816-4";
    }

    /**
     * add the pad bytes to the passed in block, returning the
     * number of bytes added.
     */
    public int addPadding(
        byte[]  in,
        int     inOff)
    {
        int added = (in.length - inOff);

        in [inOff]= (byte) 0x80;
        inOff ++;

        while (inOff < in.length)
        {
            in[inOff] = (byte) 0;
            inOff++;
        }

        return added;
    }

    /**
     * return the number of pad bytes present in the block.
     */
    public int padCount(byte[] in)
        throws InvalidCipherTextException
    {
        int count = in.length - 1;

        while (count > 0 && in[count] == 0)
        {
            count--;
        }

        if (in[count] != (byte)0x80)
        {
            throw new InvalidCipherTextException("pad block corrupted");
        }

        return in.length - count;
    }
}
于 2012-06-21T13:06:27.353 回答