2011-05-19 48 views
5

Estoy tratando de escribir un algoritmo de cifrado usando RSA en Java, obtengo un "javax.crypto.BadPaddingException: los datos deben comenzar con cero"; No sé para qué sirve esta excepción. Este es el ejemplo que usé hereCifrado RSA en Java

y Aquí está mi código; por favor ayuda.

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; 
} 
+0

Cuando se le recibiendo la excepción - mientras cifrado o descifrado? – sinha

+1

¿Ha buscado en javax.crypto.BadPaddingException antes de publicar su pregunta? Esto parece un posible duplicado de [esto] (http://stackoverflow.com/questions/4895773) y [este] (http://stackoverflow.com/questions/4580982). ¿Qué respuesta: no está convirtiendo la cadena hexadecimal de nuevo a una matriz de bytes correctamente para el descifrado? –

+0

Llámame estúpido, pero ¿cómo se inicializa la variable 'cifrar' y cuál es su contenido? Parece que no hay declaración o es global? – bl4ckb0l7

Respuesta

2

El problema podría ser que los datos enviados a través de la red con sockets pueden estar dañados debido a algunos problemas de codificación. Tuve el mismo problema al desarrollar un sencillo programa de chat cliente/servidor que encripta/descifra usando clave asimétrica los mensajes entre el servidor y el cliente y viceversa, en lugar de enviar el mensaje como una cadena, lo envié como una matriz de bytes que es el mensaje encriptado

0
  • cheque si las claves son coincidentes
  • de verificación si los datos devueltos por getEncryptedValue son los mismos que se pasa a getDecryptedValue
  • cheque corectness de bucle en el método blockCipher