RSA Encryption in Java

I try to write an encryption algorithm using RSA in Java, I get "javax.crypto.BadPaddingException: data must start from scratch"; I do not know what this exception is for. This is an example that 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);
        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;
}
+5
source share
2 answers

, , , - . / -, / , , , , .

+2
  • ,
  • , , getEncryptedValue, , getDecryptedValue
  • blockCipher
0

All Articles