Ver Mensaje Individual
  #2 (permalink)  
Antiguo 30/11/2015, 08:02
Mechabits
 
Fecha de Ingreso: agosto-2013
Mensajes: 103
Antigüedad: 10 años, 8 meses
Puntos: 1
Respuesta: Encriptacion con clave publica

Lo quería para mandar un fichero encriptado mediante RSA por un cliente web service y la solucion, por si a alguien le sirve, es esta:
Código Java:
Ver original
  1. private Cipher rsa;
  2. PublicKey publicKey=AxisSSLSocketFactory.getPublicKey();
  3. rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  4. this.rsa.init(Cipher.ENCRYPT_MODE, publicKey);
  5. byte[] encrypted = blockCipher(cargarFicheroComoArrayDeBytes(arrayDeFicheros[i]),Cipher.ENCRYPT_MODE);
  6. byte[] base64EncodedData = Base64.encodeBase64(encrypted);
  7. String datosEncriptadosEnB64 = new String (base64EncodedData);

Código Java:
Ver original
  1. private static byte[] cargarFicheroComoArrayDeBytes(SmbFile file) throws Exception {
  2.         int length = (int) file.length();
  3.         BufferedInputStream reader = new BufferedInputStream(new SmbFileInputStream(file));
  4.         byte[] bytes = new byte[length];
  5.         reader.read(bytes, 0, length);
  6.         reader.close();
  7.         return bytes;
  8.      }  
  9.    
  10.     private byte[] blockCipher(byte[] bytes, int mode) throws IllegalBlockSizeException, BadPaddingException{
  11.         // Se inicializan 2 buffers
  12.         // scrambled llevará a cabo los resultados intermedios
  13.         byte[] scrambled = new byte[0];
  14.  
  15.         // toReturn llevará a cabo el resultado total
  16.         byte[] toReturn = new byte[0];
  17.         // si encriptamos, usamos bloques de 100 bytes de longitud. Desencriptar requiere bloques de 128 bytes (por ser RSA)
  18.         int length = (mode == Cipher.ENCRYPT_MODE)? 100 : 128;
  19.  
  20.         // otro buffer. Este llevará a cabo los bytes que tienen que ser modificados en este paso.
  21.         byte[] buffer = new byte[length];
  22.  
  23.         for (int i=0; i< bytes.length; i++){
  24.  
  25.             // si llenamos nuestro array buffer tenemos nuestro bloque listo para des/encriptar.
  26.             if ((i > 0) && (i % length == 0)){
  27.                 //ejecutamos la operación
  28.                 scrambled = rsa.doFinal(buffer);
  29.                 // añadimos el resultado a nuestro resultado total
  30.                 toReturn = append(toReturn,scrambled);
  31.                 // aqui calculamos la longitud de nuestro próximo buffer requerido.
  32.                 int newlength = length;
  33.  
  34.                 // si newlength fuese más largo que el resto de bytes en el array de bytes, lo acortamos.
  35.                 if (i + length > bytes.length) {
  36.                      newlength = bytes.length - i;
  37.                 }
  38.                 // limpia el buffer
  39.                 buffer = new byte[newlength];
  40.             }
  41.             // copia el byte a nuestro buffer
  42.             buffer[i%length] = bytes[i];
  43.         }
  44.        
  45.         // este paso es necesitado si tuvieramos un buffer de salida. Solo debería ocurrir cuando encriptaramos.
  46.         // Por ejemplo, nosotros encriptamos 110 bytes, 100 bytes por run significa que "olvidamos" los últimos 10 bytes. Estan en el array del buffer.
  47.         scrambled = rsa.doFinal(buffer);
  48.  
  49.         // último paso antes de que podamos devolver datos modificados.
  50.         toReturn = append(toReturn,scrambled);
  51.  
  52.         return toReturn;
  53.     }
  54.    
  55.     private byte[] append(byte[] prefix, byte[] suffix){
  56.         byte[] toReturn = new byte[prefix.length + suffix.length];
  57.         for (int i=0; i< prefix.length; i++){
  58.             toReturn[i] = prefix[i];
  59.         }
  60.         for (int i=0; i< suffix.length; i++){
  61.             toReturn[i+prefix.length] = suffix[i];
  62.         }
  63.         return toReturn;
  64.     }