I am trying to encrypt pinblock ISO-0 using codenameone BouncyCastle lib. To do this, I use the following methods:
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); }
In 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; }
To give an example of log outputs:
[SecurityUtil] CREAT PIN BLOCK AND ENCRYPT.. PIN: 2255 NUMBER: 6284734104205417486 [SecurityUtil] PINBLOCK: 042214FBDFABE8B7 [SecurityUtil] PADDED: 042214FBDFABE8B7
When I run it using the public static void main method, it works as expected, however, when I create it for Android via Codenameone, I get the following error in logcat:
org.bouncycastle.crypto.DataLengthException: data not block size aligned org.bouncycastle.crypto.BufferedBlockCipher.doFinal(BufferedBlockCipher.java:275)
Despite the fact that the laid hopper has a length of 16 (a multiple of 8).
Any help on this would be appreciated.