Java에서 파일 암호화 및 복호화가 작동하지 않음 [중복]
Dec 15 2020
largefile.mp4
가장 효율적으로 불리는 대용량 비디오 파일을 암호화 한 다음 다시 암호를 해독하고 싶지만 예상대로 작동하지 않습니다.
실제로 오류가 없으며 파일이 생성됩니다. 그러나 새로 생성 된 파일이 기본 파일보다 너무 작습니다.
여기는 largefile.mp4
100MB이지만 newEncryptedFile.txt
107KB이고 newDecryptedFile.mp4
210 바이트입니다.
무엇이 문제입니까?
package fileenc;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
public class FileEncrypterDecrypter {
SecretKey key;
Cipher cipher;
public FileEncrypterDecrypter() {
try {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
key = keygen.generateKey();
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
System.out.println(e);
}
}
public boolean fileEncrypt(String plainFile) {
try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(plainFile))){
cipher.init(Cipher.ENCRYPT_MODE, key);
FileOutputStream fs = new FileOutputStream("newEncryptedFile.txt");
CipherOutputStream out = new CipherOutputStream(fs, cipher);
byte[] byteSize = new byte[1024];
int numberOfBytedRead;
while ( (numberOfBytedRead = fis.read(byteSize)) != -1 ) {
out.write(numberOfBytedRead);
}
fis.close();
out.flush();
out.close();
System.out.println("Encryption done...");
return true;
} catch (IOException | InvalidKeyException e) {
}
return false;
}
public boolean fileDecrypt(String encryptedFile) {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("newDecryptedFile.mp4"))){
cipher.init(Cipher.DECRYPT_MODE, key);
FileInputStream fis = new FileInputStream(encryptedFile);
CipherInputStream in = new CipherInputStream(fis, cipher);
byte[] byteSize = new byte[1024];
int numberOfBytedRead;
while ( (numberOfBytedRead = in.read(byteSize)) != -1) {
bos.write(numberOfBytedRead);
}
System.out.println("Decryption done...");
bos.flush();
bos.close();
in.close();
return true;
} catch (IOException | InvalidKeyException e) {
}
return false;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
FileEncrypterDecrypter fed = new FileEncrypterDecrypter();
fed.fileEncrypt("largefile.mp4"); // about 100 mb
fed.fileDecrypt("newEncryptedFile.txt");
}
}
답변
1 MichaelFehr Dec 15 2020 at 17:06
새 프로젝트에서 더 이상 사용하지 않아야 하는 UNSECURE 모드 ECB 를 사용하고 있기 때문에 코드를 검사하지 않은 점 죄송합니다 .
다음은 CBC 모드에서 AES를 사용한 파일 암호화 및 암호 해독에 대한 샘플 코드입니다. 이 프로그램은 암호화 및 복호화를위한 임의의 키를 생성하고 (더 나은 저장을 위해 base64 인코딩의 키를 사용하여) 암호화 된 파일의 시작 부분에 기록되는 임의의 초기화 벡터 (IV)를 생성합니다.
해독의 경우 처음 16 바이트는 암호화되지 않은 데이터로 읽히고 다른 모든 데이터는 해독 스트림을 통과합니다.
암호화는 CipherOutput- / InputStream의 친절한 도움으로 8192 바이트 단위로 수행됩니다.
보안 경고 : 코드에는 예외 처리가 없으며 교육용으로 만 사용됩니다. 더 나은 보안을 위해 인증 된 암호화 (예 : HMAC 또는 GCM 모드 사용)로 변경할 수 있습니다.
산출:
AES CBC 256 file encryption with CipherOutputStream
encryption key in base64 encoding: vTsd0E8MX3arfLRFjxZ58FSjkKxKYe32+rT5zCnJPVY=
result encryption: true
result decryption: true
암호:
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class AesCbcEncryptionWithRandomKeyCipherOutputStreamSoExample {
public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException,
InvalidKeyException, InvalidAlgorithmParameterException {
System.out.println("AES CBC 256 file encryption with CipherOutputStream");
String uncryptedFilename = "plaintext.txt";
String encryptedFilename = "encrypted.enc";
String decryptedFilename = "decrypted.txt";
// generate random aes 256 key
byte[] encryptionKey = new byte[32];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(encryptionKey);
System.out.println("encryption key in base64 encoding: " + base64Encoding(encryptionKey));
boolean result;
// encryption
result = encryptCbcFileBufferedCipherOutputStream(uncryptedFilename, encryptedFilename, encryptionKey);
System.out.println("result encryption: " + result);
// decryption
result = decryptCbcFileBufferedCipherInputStream(encryptedFilename, decryptedFilename, encryptionKey);
System.out.println("result decryption: " + result);
}
public static boolean encryptCbcFileBufferedCipherOutputStream(String inputFilename, String outputFilename, byte[] key)
throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
// generate random iv
SecureRandom secureRandom = new SecureRandom();
byte[] iv = new byte[16];
secureRandom.nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
try (FileInputStream in = new FileInputStream(inputFilename);
FileOutputStream out = new FileOutputStream(outputFilename);
CipherOutputStream encryptedOutputStream = new CipherOutputStream(out, cipher);) {
out.write(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] buffer = new byte[8096];
int nread;
while ((nread = in.read(buffer)) > 0) {
encryptedOutputStream.write(buffer, 0, nread);
}
encryptedOutputStream.flush();
}
if (new File(outputFilename).exists()) {
return true;
} else {
return false;
}
}
public static boolean decryptCbcFileBufferedCipherInputStream(String inputFilename, String outputFilename, byte[] key) throws
IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
byte[] iv = new byte[16];
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
try (FileInputStream in = new FileInputStream(inputFilename);
CipherInputStream cipherInputStream = new CipherInputStream(in, cipher);
FileOutputStream out = new FileOutputStream(outputFilename))
{
byte[] buffer = new byte[8192];
in.read(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
int nread;
while ((nread = cipherInputStream.read(buffer)) > 0) {
out.write(buffer, 0, nread);
}
out.flush();
}
if (new File(outputFilename).exists()) {
return true;
} else {
return false;
}
}
private static String base64Encoding(byte[] input) {
return Base64.getEncoder().encodeToString(input);
}
}