RSA encryption in Java
I am trying to write an encryption algorithm using RSA in Java, I am getting a "javax.crypto.BadPaddingException: Data must start with zero"; I do not know what is this exception for. This is the example I used here
and Here is my code; please help.
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);
开发者_StackOverflowreturn 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;
}
The problem could be the data sent over the network using sockets may be corrupted due to some encoding problems. I had the same problem while developing a simple client/server chat program that encrypts/decrypts using asymmetric key the messages between the server and client and vise versa, instead of sending the message as a string, I sent it as a byte array which is the encrypted message.
- check if keys are matching
- check if data returned by getEncryptedValue are the same that you pass to getDecryptedValue
- check corectness of loop in blockCipher method
精彩评论