在codenameone BouncyCastle中没有块大小对齐的数据(No Padding)

时间:2016-07-22 12:17:05

标签: java android encryption bouncycastle codenameone

我正在尝试使用codenameone BouncyCastle lib加密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的倍数)。

对此问题的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

加密适用于二进制数据,而您的pinblock是二进制,所以请保持这种方式。

调用SELECT t.course , MIN(t.user) AS min_user , MAX(t.user) AS max_user , COUNT(1) FROM mytable t GROUP BY t.course 时,您将十六进制编码的pinblock转换为performEncrypt(..)的字符串,并在new String(ByteUtil.hex2byte(padded))内将其转换为performEncrypt(...)的字节数组。这样做的问题是,并非所有字节序列都可以通过字符串来回正确映射,并且最终可能会得到不同的数据甚至不同的长度等。take a look here

将您的签名byte[] ptBytes = plainText.getBytes();更改为:

performEncrypt(..)

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