我想在Java中使用RSA编写加密算法,我得到一个 “javax.crypto.BadPaddingException:数据必须以零开头”;我不知道这是什么例外。 这是我用的例子here在Java中的RSA加密
这是我的代码;请帮忙。
public byte[] getEncryptedValue(byte[] bytes, PublicKey key) {
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
return blockCipher(bytes, Cipher.ENCRYPT_MODE);
} catch (Exception ex) {
Logger.getLogger(SecurityUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public byte[] getDecryptedValue(byte[] bytes, PrivateKey key) {
try {
cipher.init(Cipher.DECRYPT_MODE, key);
return blockCipher(bytes, Cipher.DECRYPT_MODE);
} catch (Exception ex) {
Logger.getLogger(SecurityUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
private byte[] append(byte[] prefix, byte[] suffix) {
byte[] toReturn = new byte[prefix.length + suffix.length];
System.arraycopy(prefix, 0, toReturn, 0, prefix.length);
System.arraycopy(suffix, 0, toReturn, prefix.length, suffix.length);
return toReturn;
}
private byte[] blockCipher(byte[] bytes, int mode) throws IllegalBlockSizeException, BadPaddingException {
byte[] scrambled = new byte[0];
byte[] toReturn = new byte[0];blocks (because of RSA)
int length = (mode == Cipher.ENCRYPT_MODE) ? 100 : 128;
int n = 0;
byte[] buffer = new byte[length];
for (int i = 0; i < bytes.length; i++) {
if ((i > 0) && (i % length == 0)) {
n = 0;
scrambled = cipher.doFinal(buffer);
toReturn = append(toReturn, scrambled);
}
buffer[i % length] = bytes[i];
n++;
}
***scrambled = cipher.doFinal(buffer, 0, n);*** <-- the exception is caught here
toReturn = append(toReturn, scrambled);
return toReturn;
}
当你得到的例外 - 而加密或解密? – sinha 2011-05-19 05:50:44
您是否在发布您的问题之前在javax.crypto.BadPaddingException上进行搜索?这看起来像[this](http://stackoverflow.com/questions/4895773)和[this]的可能重复(http://stackoverflow.com/questions/4580982)。回答:您不是将十六进制字符串正确地转换回字节数组以解密 – 2011-05-20 21:28:07
称我为笨,但变量'cipher'是如何初始化的?它的内容是什么? 似乎没有声明或是全球? – bl4ckb0l7 2011-05-23 13:49:58