Здравствуйте товарищи-кодеры. Застрял на задаче по кодировке, хочу сделать ее именно с использование Java Cryptography API.
Проблема в следующем - программа успешно шифрует и записывает текст из одного файла в другой, но не способна расшифровать текст обратно.
Case "-d" не работает, как ожидается.
Не могу найти в чем проблема, буду благодарен за помощь.
/*
Шифровка
*/
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
public class Solution {
public static void main(String[] args) throws Exception {
byte[] encryptionKeyBytes = "thisisa128bitkey".getBytes();
SecretKey secretKey = new SecretKeySpec(encryptionKeyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
switch (args[0]) {
case "-e":
encode(args[1], args[2], secretKey, cipher);
break;
case "-d":
decode(args[1], args[2], secretKey, cipher);
break;
default:
System.err.println("Wrong parameter!");
}
}
public static void encode(String fileInName, String fileOutName, Key key, Cipher cipher) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, key, cipher.getParameters());
FileInputStream fileInputStream = new FileInputStream(fileInName);
FileOutputStream fileOutputStream = new FileOutputStream(fileOutName);
byte[] buffer = new byte[fileInputStream.available()];
while (fileInputStream.available() > 0) {
fileInputStream.read(buffer);
byte[] cipherText = cipher.doFinal(buffer);
fileOutputStream.write(cipherText);
}
fileInputStream.close();
fileOutputStream.close();
}
public static void decode(String fileInName, String fileOutName, Key key, Cipher cipher) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, key, cipher.getParameters());
FileInputStream fileInputStream = new FileInputStream(fileInName);
FileOutputStream fileOutputStream = new FileOutputStream(fileOutName);
byte[] buffer = new byte[fileInputStream.available()];
while (fileInputStream.available() > 0) {
fileInputStream.read(buffer);
byte[] cipherText = cipher.doFinal(buffer);
fileOutputStream.write(cipherText);
}
fileInputStream.close();
fileOutputStream.close();
}
}