我試圖使用codenameone BouncyCastle lib加密ISO-0 pinblock。 我使用達到此目的的方法如下:在codenameone BouncyCastle(無填充)中對齊數據塊大小
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的倍數)。
有關這個問題的任何幫助,將不勝感激。
很棒的回答。我們會避免在Codename One中使用字符串作爲二進制數據,因爲我們將字符串映射到本地字符串,例如在iOS上,它們在某些極端邊緣情況下可能會有輕微的行爲差異。例如。我們在整合zip支持https://www.codenameone.com/blog/zip-and-toast.html時遇到了問題 –