【发布时间】:2021-10-16 09:22:54
【问题描述】:
我正在使用密码加密和解密 android 中的字节数组以发送到服务器。我没有使用字符串,但我仍然收到非法块大小异常。
try {
byte[] cipherNameText = {};
KeyGenerator keygen = null;
keygen = KeyGenerator.getInstance("AES");
keygen.init(256);
SecretKey key= keygen.generateKey();
String name = nameEdit.getText().toString();
Cipher cipher = null;
cipher = Cipher.getInstance("AES_256/CBC/NoPadding");
SecureRandom iv = new SecureRandom();
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
cipherNameText = cipher.doFinal(name.getBytes(StandardCharsets.UTF_8));
byte[] iv1 = cipher.getIV();
HashMap<String, byte[]> map = new HashMap<>();
map.put("name",key.toString().getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
2021-08-12 20:55:17.606 15222-15222/com.example.package W/System.err: javax.crypto.IllegalBlockSizeException: error:1e00006a:Cipher functions:OPENSSL_internal:DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
2021-08-12 21:51:47.322 15606-15606/com.example.package W/System.err:在 com.example.servertutorial.MainActivity$4.onClick(MainActivity.java:212)
^this 指向“cipherNameText = cipher.doFinal(name.getBytes(StandardCharsets.UTF_8));”
【问题讨论】:
-
通过使用
NoPadding,您已承诺要加密的数据的长度是块大小(16 字节)的倍数。使用不同的填充模式,或自己填充数据。请参阅this answer 了解更多信息。
标签: java android encryption