первый раз отправляю это так что не слишком сильно на меня (хотя я читал этот форум совсем какое-то время)Не удалось Расшифровать после сжатия строки в текстовый файл (AES)
Проблема, Я встречаюсь с использованием AES в Java, вот так.
Во-первых, мне нужно зашифровать строку и записать ее в текстовый файл, а затем сжать ее, без проблем с этим. Я использую шифрование AES, и я определяю свой собственный ключ, например, «123»
Во-вторых, мне нужно распаковать файл (или извлечь его?) И расшифровать его, используя тот же ключ, который я использовал на первом шаге.
Что произойдет в здесь: Первый шаг это хорошо, но второй один потерпел неудачу на дешифрование файла, даже если строка результата является тем же самым, общий характер, слово и т.д.
Вот код для записи файла
private static void inputKeFile(String input) throws IOException
{
FileWriter fstream = new FileWriter("C:/Users/Sactio/Desktop/tyo/txtToZip.txt",false);
BufferedWriter out = new BufferedWriter(fstream);
out.write(input);
//Close the output stream
out.close();
}
пронестись файл
private static void doZip() {
try {
String filename ="C:/Users/Sactio/Desktop/tyo/txtToZip.txt";
String zipfilename="C:/Users/Sactio/Desktop/OutputZipWrite";
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
long length = file.length();
byte[] buf = new byte[(int)length];
fis.read(buf,0,buf.length);
CRC32 crc = new CRC32();
ZipOutputStream s = new ZipOutputStream(new FileOutputStream(zipfilename));
s.setLevel(9);
ZipEntry entry = new ZipEntry(filename);
entry.setSize((long)buf.length);
crc.reset();
crc.update(buf);
entry.setCrc(crc.getValue());
s.putNextEntry(entry);
s.write(buf, 0, buf.length);
s.finish();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
и это шифрование
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class JcaTest {
private Cipher ecipher;
private Cipher dcipher;
JcaTest(SecretKey key) {
try {
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (Exception e) {
System.out.println("Failed in initialization");
}
}
public String encrypt(String str) {
try {
byte[] utf8 = str.getBytes("UTF-8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
} catch (Exception e) {
System.out.println("Failed in Encryption");
}
return null;
}
public String decrypt(String str) {
try {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF-8");
} catch (Exception e) {
System.out.println("Failed in Decryption");
}
return null;
}
и, наконец, экстрактор для почтового
private static void bacaZip(String zipfilename) throws IOException
{
ZipInputStream zinstream = new ZipInputStream(
new FileInputStream(zipfilename));
File file = new File(zipfilename);
FileInputStream fis = new FileInputStream(file);
long length = file.length();
byte[] buf = new byte[(int)length];
ZipEntry zentry = zinstream.getNextEntry();
System.out.println("Name of current Zip Entry : " + zentry + "\n");
while (zentry != null) {
String entryName = zentry.getName();
System.out.println("Name of Zip Entry : " + entryName);
FileOutputStream outstream = new FileOutputStream("C:/Users/Sactio/Desktop/OutputZipWrite.txt");
int n;
while ((n = zinstream.read(buf, 0, buf.length)) > -1) {
outstream.write(buf, 0, n);
}
System.out.println("Successfully Extracted File Name : "
+ entryName);
outstream.close();
zinstream.closeEntry();
zentry = zinstream.getNextEntry();
}
}
private static void extractZip(String jsonString) throws FileNotFoundException
{
try {
bacaZip(jsonString);
} catch (IOException e1) {
// TODO Auto-generated catch block
System.err.println("Exception: "+e1);
}
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:/Users/Sactio/Desktop/OutputZipWrite.txt"));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println("HASIL: "+contents.toString());
}
Если я пропускаю сжатие и файлы шагов, AES работает хорошо, но если я посылаю строку в файл и сжать его, шифрование AES терпит неудачу по какой-то причине , Кто-нибудь имеет представление об этой проблеме?
Непосредственно связано с вашей проблемой, но не сжимает выход AES. Это не сработает. Сжатие текста перед его зашифровкой. – Thilo
Вы читаете и записываете файл в двоичном режиме? Трансляция CR LF может вас тронуть. – rsp
Как указал Тило, данные шифрования не могут быть хорошо сжаты из-за отсутствия повторяющихся паттеров, поэтому шифрование-сжатие бесполезно. –