【问题标题】:Encryption decryption AES for all type of file in javajava中所有类型文件的加密解密AES
【发布时间】:2020-07-14 06:17:43
【问题描述】:

如何修改此 AES 加密代码,使其可以加密和解密任何类型的文件(pdf、docx ......),因为当我解密 pdf 文件或其他文件时,我没有得到原始文件。

public EncryptData(File originalFile, File encrypted, SecretKeySpec secretKey, String cipherAlgorithm) throws IOException, GeneralSecurityException{
    this.cipher = Cipher.getInstance(cipherAlgorithm);      
    encryptFile(getFileInBytes(originalFile), encrypted, secretKey);
}

public void encryptFile(byte[] input, File output, SecretKeySpec key) throws IOException, GeneralSecurityException {
    this.cipher.init(Cipher.ENCRYPT_MODE, key);
    writeToFile(output, this.cipher.doFinal(input));
}
public SecretKeySpec getSecretKey(String filename, String algorithm) throws IOException{
    byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
    return new SecretKeySpec(keyBytes, algorithm);
}

public static void main(String[] args) throws IOException, GeneralSecurityException, Exception{
    StartEncryption startEnc = new StartEncryption();
    File originalFile = new File("file.docx");
    File encryptedFile = new File("EncryptedFiles/encryptedFile");
    new EncryptData(originalFile, encryptedFile, startEnc.getSecretKey("OneKey/secretKey", "AES"), "AES");
}
public DecryptData(File encryptedFileReceived, File decryptedFile, SecretKeySpec secretKey, String algorithm) throws IOException, GeneralSecurityException {
    this.cipher = Cipher.getInstance(algorithm);
    decryptFile(getFileInBytes(encryptedFileReceived), decryptedFile, secretKey);
}

public void decryptFile(byte[] input, File output, SecretKeySpec key) throws IOException, GeneralSecurityException {
    this.cipher.init(Cipher.DECRYPT_MODE, key);
    writeToFile(output, this.cipher.doFinal(input));
}
public SecretKeySpec getSecretKey(String filename, String algorithm) throws IOException{
    byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
    return new SecretKeySpec(keyBytes, algorithm);
}

public static void main(String[] args) throws IOException, GeneralSecurityException, Exception{
    StartDecryption startEnc = new StartDecryption();
    
    File encryptedFileReceived = new File("EncryptedFiles/encryptedFile");
    File decryptedFile = new File("DecryptedFiles/decryptedFile");
    new DecryptData(encryptedFileReceived, decryptedFile, startEnc.getSecretKey("DecryptedFiles/SecretKey", "AES"), "AES");
    
}

【问题讨论】:

  • 像 AES 这样的通用加密算法并不关心它们加密的文档类型;他们只是对字节流进行操作。如果解密后没有得到原始文档,则可能是加密/解密代码中存在错误。

标签: java encryption aes


【解决方案1】:

由于缺少有关您的源代码的一些重要信息(方法 writeToFile,没有关于 cipherAlgorithm 的信息,没有关于使用的密钥的信息)您的代码不可执行

因此,我提供了一个示例程序来使用 AES 模式 ECB 加密和解密任何类型的文件。

安全警告:不要在生产中使用 AES ECB 模式,因为它不安全!最好使用像 AES GCM 这样的模式。

提供原始文件(plaintextfile)、加密文件(ciphertextfile)和解密文件(decryptedfile)的文件名和 运行程序 - 解密后的文件与原始文件相同。

我在此示例中使用静态密钥(32 字节/256 位密钥长度) - 要运行此程序,您需要在 Java 系统上启用无限制的加密策略。

结果如下:

https://stackoverflow.com/questions/62883618/encryption-decryption-aes-for-all-type-of-file-in-java
AES ECB Stream Encryption
* * * WARNING Do NOT use AES ECB mode in production as it is UNSECURE ! * * *
file used for encryption: plaintext.pdf
created encrypted file  : plaintext.enc
created decrypted file  : plaintext_decrypted.pdf
AES ECB Stream Encryption ended

代码:

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AES_ECB_Stream {
    public static void main(String[] args) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {
        System.out.println("https://stackoverflow.com/questions/62883618/encryption-decryption-aes-for-all-type-of-file-in-java");
        System.out.println("AES ECB Stream Encryption");
        System.out.println("* * * WARNING Do NOT use AES ECB mode in production as it is UNSECURE ! * * *");
        String plaintextFilename = "plaintext.pdf";
        String ciphertextFilename = "plaintext.enc";
        String decryptedtextFilename = "plaintext_decrypted.pdf";
        byte[] key = "12345678901234561234567890123456".getBytes("UTF-8"); // 32 byte = 256 bit key length
        encryptWitEcb(plaintextFilename, ciphertextFilename, key);
        decryptWithEcb(ciphertextFilename, decryptedtextFilename, key);
        System.out.println("file used for encryption: " + plaintextFilename);
        System.out.println("created encrypted file  : " + ciphertextFilename);
        System.out.println("created decrypted file  : " + decryptedtextFilename);
        System.out.println("AES ECB Stream Encryption ended");
    }

    public static void encryptWitEcb(String filenamePlain, String filenameEnc, byte[] key) throws IOException,
            NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        try (FileInputStream fis = new FileInputStream(filenamePlain);
             BufferedInputStream in = new BufferedInputStream(fis);
             FileOutputStream out = new FileOutputStream(filenameEnc);
             BufferedOutputStream bos = new BufferedOutputStream(out)) {
            byte[] ibuf = new byte[1024];
            int len;
            while ((len = in.read(ibuf)) != -1) {
                byte[] obuf = cipher.update(ibuf, 0, len);
                if (obuf != null)
                    bos.write(obuf);
            }
            byte[] obuf = cipher.doFinal();
            if (obuf != null)
                bos.write(obuf);
        }
    }

    public static void decryptWithEcb(String filenameEnc, String filenameDec, byte[] key) throws IOException,
            NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException {
        try (FileInputStream in = new FileInputStream(filenameEnc);
             FileOutputStream out = new FileOutputStream(filenameDec)) {
            byte[] ibuf = new byte[1024];
            int len;
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            while ((len = in.read(ibuf)) != -1) {
                byte[] obuf = cipher.update(ibuf, 0, len);
                if (obuf != null)
                    out.write(obuf);
            }
            byte[] obuf = cipher.doFinal();
            if (obuf != null)
                out.write(obuf);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2013-04-19
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多