Я пишу небольшое тестовое приложение. Дело в том... Сервлет загружает любой зашифрованный файл AES в мое настольное приложение. Затем мое настольное приложение расшифровывает его и сохраняет на локальном жестком диске. Он отлично работает с двоичным видео, изображениями и т. Д., Но по какой-то причине я теряю символы из файлов txt. Насколько я понимаю, в любом текстовом файле отсутствуют 128 последних битов (это 15 или 16 последних символов).
Я не знаю, почему это происходит, поэтому мне нужен ваш совет.
Вот код сервлета:
final int BUFFER_SIZE = 4096;
FileInputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
byte buffer[] = new byte[BUFFER_SIZE];
for (int nread = 0; (nread = in.read(buffer)) != -1;) {
out.write(buffer, 0, nread);
}
out.flush();
out.close();
in.close();
И фрагмент кода настольного приложения:
response = httpclient.execute(httppost);//it is HttpClient 4...
resEntity = response.getEntity();
InputStream in = resEntity.getContent();
in = new CipherInputStream(in, decipher);//maybe the aes block missing here...
FileOutputStream out= new FileOutputStream(path);
byte[] buffer = new byte[4096];
int numRead = 0;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
out.flush();
out.close();
И вот как я получаю расшифровку:
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
key = kgen.generateKey();
byte[] ivar = new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
};
AlgorithmParameterSpec params = new IvParameterSpec(ivar );
dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, key, params );
... А вот фрагмент загрузки десктопного приложения
HttpPost httppost = null;
HttpResponse response=null;
HttpEntity resEntity=null;
try {
File file = filePath;
fileLength=file.length();
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.
PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
String url="http://localhost:8080/testUrl";
httppost = new HttpPost(url);
String name=file.getName();
InputStreamBody inputStreamBody=new InputStreamBody(new FileInputStream(file),name);
MultiPartEntity multiPartEntity = new MultiPartEntity();
multiPartEntity .addPart("file-name", new StringBody(name, Charset.forName("UTF-8")));
multiPartEntity .addPart("file-stream", inputStreamBody);
и метод записи InputStreamBody (вы можете увидеть документ здесь http://hc.apache.org/httpcomponents-client-ga/httpmime/clover/org/apache/http/entity/mime/content/InputStreamBody.html). ..
byte[] ivar = new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
};
...
AlgorithmParameterSpec params = new IvParameterSpec(ivar);
encipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encipher .init(Cipher.ENCRYPT_MODE, key, params);
...
public void writeTo(final OutputStream out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
try {
out = new CipherOutputStream(out, encipher );
int numRead = 0;
while ( (count = in.read(buf)) !=-1) {
out.write(buf, 0, count);
}
out.flush();
in.close();
}
catch (java.io.IOException e) {
}
}
Помогите, пожалуйста, с проблемой расшифровки. Возможно, в бинарных файлах тоже не хватает 128 бит, но это не так уж примечательно, за исключением содержимого текстовых файлов :( Я слышал, что это может произойти из-за закрытия потоков неправильной последовательности или около того, но я не уверен.
Я слышал, что это может быть проблема с длиной содержимого InputStreamBody, метод:
public long getContentLength() {
return -1;
}
Но как правильно установить измененную длину вывода, если "in.length!=out.length" из-за шифрования (см. метод writeTo)?
Пожалуйста, помогите мне исправить это
Любой полезный комментарий приветствуется :)
catch (java.io.IOException e) {}
- это просто съест ваше исключение, и вы не узнаете, что это такое. Используйте как минимум что-то вродеcatch (java.io.IOException e) { e.printStackTrace(); }
(и посмотрите, есть ли что-то на выходе ошибки). - person Paŭlo Ebermann   schedule 02.04.2011