Java中所有类型文件的加密解密AES [英] Encryption decryption AES for all type of file in java

查看:99
本文介绍了Java中所有类型文件的加密解密AES的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how to modify this AES encryption code so that it can encrypt and decrypt any type of file (pdf, docx....), because when I decrypt a pdf file or other I don't get the original file.

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");
    
}

推荐答案

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

As some important information regarding your source code is missing (method writeToFile, no information about the cipherAlgorithm, no information about the used key) your code is not executable.

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

Therefore I'm providing a sample program to encrypt and decrypt any kind of files using the AES mode ECB.

安全警告:请勿在生产中使用AES ECB模式,因为它是不安全的!最好使用AES GCM之类的模式.

Security warning: do NOT use AES ECB Mode in production because it is UNSECURE ! It's better to use a mode like AES GCM.

提供原始文件(plaintextfile),加密文件(ciphertextfile)和解密文件(decryptedfile)的文件名,以及 运行程序-解密后的文件等于原始文件.

Provide the filenames for the original file (plaintextfile), the encrypted file (ciphertextfile) and the decrypted file (decryptedfile) and run the program - the decrypted file is equal to the original file.

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

I'm using a static key (32 byte/256 bit key length) for this example - to run this program you need the unlimited crypto policies enabled on your Java system.

这就是结果:

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);
        }
    }
}

这篇关于Java中所有类型文件的加密解密AES的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆