El codigo es el del stack Overflow, pero en el proyecto finalmente a quedado del siguiente modo:
public static void fileEncripWrapped
(File in,
File out,
PublicKey pub,
byte [] key
) {
try {
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.WRAP_MODE, pub);
byte[] encKey = cipher.wrap(keySpec);
osAppend.write(encKey);
osAppend.close();
cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
CipherOutputStream os
= new CipherOutputStream
(new FileOutputStream(out,
true), cipher
);
copy(is, os);
is.close();
os.close();
System.
err.
println("Ha succeït un error xifrant: " + ex
); }
}
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.UNWRAP_MODE, priv);
byte[] bufferKey = getFirstBytes(is, 256);
Key ky
= cipher.
unwrap(bufferKey,
"AES", Cipher.
SECRET_KEY);
cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, ky);
CipherInputStream cIs = new CipherInputStream(is, cipher);
copy (cIs , os);
is.close();
cIs.close();
os.close();
System.
err.
println("Ha succeït un error xifrant: " + ex
); }
}
Y por otro lado :
/**
* Copy the bytes of input string to bytes in output string in blocks of 1024 bytes
* @param is - InputStream
* @param os - OutputStream
* @throws IOException
*/
int i;
byte[] b = new byte[1024];
while((i=is.read(b))!=-1) {
os.write(b, 0, i);
}
}
/**
* Get the first n bytes of a binary file
* @param is - InoutStream
* @param size - Size do you want to take.
* @return
*/
private static byte [] getFirstBytes
(InputStream is,
int size
) { byte [] bytes = new byte [size];
try {
if (is.read(bytes) != bytes.length) {
is.close();
}
Logger.getLogger(Asimetric.class.getName()).log(Level.SEVERE, null, ex);
}
return bytes;
}
Ojala sirva!
La idea no se si es buena. Incorporar en el mismo archivo la llave para descifrar... La verdad es que me gustaría profundizar en el tema, con el tiempo!
Alomejor posteo en algún tiempo alguna mejora del codigo que tengo pensar de hacer para optimizar y reducir algoritmos.
Salut!