数据未在代码名称 BouncyCastle 中对齐块大小(无填充)

Data not block size aligned in codenameone BouncyCastle (No Padding)

我正在尝试使用代号为 BouncyCastle 的库来加密 ISO-0 pinblock。 我使用的实现方法如下:

private static byte[] performEncrypt(byte[] key, String plainText, boolean padding) {
    byte[] ptBytes = plainText.getBytes();

    BufferedBlockCipher cipher;
    if (padding) {
        cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
    } else {
        cipher = new BufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
    }
    cipher.init(true, new KeyParameter(key));
    byte[] rv = new byte[cipher.getOutputSize(ptBytes.length)];
    int oLen = cipher.processBytes(ptBytes, 0, ptBytes.length, rv, 0);
    try {
        cipher.doFinal(rv, oLen);
    } catch (CryptoException ce) {
        LoggingUtil.error(TAG, ce, "Unexpected Exception");
    }
    return rv;
}

private static String createIso0PinBlock(String pin, String number) {
    ...
}

private static String getPaddedData(String data, byte padCharacter) {
    String paddedData = ByteUtil.pad(data, (char) padCharacter, 8).toString();
    return paddedData;
}

public static String createPinBlockAndEncrypt(String pin, String number) {
    LoggingUtil.debug("SecurityUtil", "CREAT PIN BLOCK AND ENCRYPT.. PIN: " + pin + " NUMBER: " + number);
    String pb = createIso0PinBlock(pin, number.substring(0, number.length() - 1));
    LoggingUtil.debug("SecurityUtil", "PINBLOCK: " + pb);
    String padded = getPaddedData(pb, (byte) 0x00);
    LoggingUtil.debug("SecurityUtil", "PADDED: " + padded);
    byte[] encrypted = performEncrypt(Hex.decode(KEY.getBytes()), new String(ByteUtil.hex2byte(padded)), false);
    return ByteUtil.byte2hex(encrypted);
}

ByteUtil中:

public static StringBuilder pad(String data, char padCharacter, int multiplier) {
    StringBuilder text = new StringBuilder();
    text.append(data);
    while (text.length() % multiplier != 0) {
        text.append(padCharacter);
    }
    return text;
}

举例日志输出:

[SecurityUtil] CREAT PIN BLOCK AND ENCRYPT.. PIN: 2255 NUMBER: 6284734104205417486
[SecurityUtil] PINBLOCK: 042214FBDFABE8B7
[SecurityUtil] PADDED: 042214FBDFABE8B7

当我通过 public static void main 方法 运行 时,它按预期工作,但是,当我通过 Codenameone 为 Android 构建它时,我在 logcat:

org.bouncycastle.crypto.DataLengthException: data not block size aligned
org.bouncycastle.crypto.BufferedBlockCipher.doFinal(BufferedBlockCipher.java:275)

尽管填充的 pinblock 长度为 16(8 的倍数)。

如能提供有关此问题的任何帮助,我们将不胜感激。

加密适用于 binary 数据,而您的 pinblock 是 binary,所以请保持这种状态。

调用 performEncrypt(..) 时,使用 new String(ByteUtil.hex2byte(padded)) 将十六进制编码的 pinblock 转换为字符串,在 performEncrypt(...) 中使用 byte[] ptBytes = plainText.getBytes(); 将其转换为字节数组。这样做的问题是,并非所有字节序列都可以通过字符串来回正确映射,并且您最终可能会得到不同的数据甚至不同的长度等。 take a look here

将您的签名 performEncrypt(..) 更改为:

private static byte[] performEncrypt(byte[] key, byte[] plainText, boolean padding) {

并避免完全通过字符串进行转换。