将十六进制字符串转换为字节数组以进行 RSA 解密
我有 RSA 加密后的十六进制字符串。当我将其转换为 byte[] 时,RSA 解密给出 javax.crypto.BadPaddingException: Blocktype Mismatch: 0
我正在使用此方法进行转换(在堆栈溢出本身上获取它)
public static byte[] hexStringToByteArray(String data) {
int k = 0;
byte[] results = new byte[data.length() / 2];
for (int i = 0; i < data.length();) {
results[k] = (byte) (Character.digit(data.charAt(i++), 16) << 4);
results[k] += (byte) (Character.digit(data.charAt(i++), 16));
k++;
}
return results;
}
请提供任何建议。
I have a hex string after RSA encryption. When I convert it to a byte[], the RSA decryption gives javax.crypto.BadPaddingException: Blocktype mismatch: 0
I am using this method for conversion (got it on Stack overflow itself)
public static byte[] hexStringToByteArray(String data) {
int k = 0;
byte[] results = new byte[data.length() / 2];
for (int i = 0; i < data.length();) {
results[k] = (byte) (Character.digit(data.charAt(i++), 16) << 4);
results[k] += (byte) (Character.digit(data.charAt(i++), 16));
k++;
}
return results;
}
Any suggestions please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
加密方式要求输入为固定长度;为了避免这种异常,您必须将填充添加到所需的长度。该大小将取决于密钥大小。
编辑:
data
的迭代中还存在一个潜在的错误:如果其长度不能被 2 整除,那么第二个i++
将导致IndexOutOfBoundsException
>。您最好在for
循环中将i
增加 2,并使用[i]
和[i+1]
访问数据时:The encryption method requires the input to be a fixed-length; you're going to have to add padding to the required length in order to avoid this exception. This size will depend on the key size.
EDIT: There is also a potential bug in your iteration of
data
: If its length is not divisible by two then the secondi++
will cause anIndexOutOfBoundsException
. You are better off incrementingi
by 2 in thefor
loop and using[i]
and[i+1]
when accessing the data: