使用附加的初始化矢量Java

问题描述

我已经编写了一个Java程序,要求用户指定一个随机密钥(以base 64编码),指定要加密的纯文本文件以及输出文件名称(加密的文本文件)。 / p>

然后反向解密(密钥+输入的加密文件+输出的解密文件名称)。

这与OpenSSL提供的行为非常相似。

我的Java代码使用模式AES/CBC/PKCS5PADDING

我事先使用文件输出流将随机生成的初始化向量(16字节IV)附加到了密文中。然后,我相信密文输出流会在IV之后写入密文。

我可以确认通过加密和解密方法生成获取的IV都是相同的(都可以使用base64编码打印出来,并且将匹配)。

但是,问题出在试图解密加密的文本。解密后的文本能够显示加密文本的后半部分(与原始纯文本的后半部分匹配)。

示例:

纯文本:my secret motto: i am awesome!

密文:<lots of encrypted characters>

解密后的文本:<a few encrypted characters> i am awesome!

上半部分似乎被覆盖,或者收集了一些奇怪的剩余加密文本。这使我相信我使用流对IV进行加密/解密的方式不太正确。

相关的执行代码是布尔值fileStoreIV为true时。 else代码用于用户同时提供密钥和IV作为输入。

因此,fout.write(initVector);encryptedData.read(fileIV);代码的主要位。

加密方法

private static void encrypt(byte[] key,byte[] initVector,String inputFile,String outputFile) throws NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeyException,InvalidAlgorithmParameterException,IOException {
    //Initalisation for encryption
    Cipher cipher = Cipher.getInstance(CIPHER);
    if(fileStoreIV) {
        SecretKeySpec skeySpec = new SecretKeySpec(key,ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
    }
    else {
        IvParameterSpec iv = new IvParameterSpec(initVector);
        SecretKeySpec skeySpec = new SecretKeySpec(key,skeySpec,iv);
    }
    
    //File error checking
    File loadFile = new File(inputFile);
    Path saveFile = Paths.get(outputFile);
    
    Path loadFilePath = Paths.get(inputFile);
    if (!Files.exists(loadFilePath)){
        System.out.println("The inputFile you specified does not exist");
        return;
    }
    
    Path parentDir = saveFile.getParent();
    if (parentDir != null && !Files.exists(parentDir)) {
        System.out.println("The outputFile directory/s you specified does not exist");
        return;
    }
    
    System.out.println("Secret key is " + Base64.getEncoder().encodetoString(key));
    System.out.println("IV is " + Base64.getEncoder().encodetoString(initVector));

    //Special file reading and writing with 'Cipher Stream'
    try (InputStream fin = FileEncryptor.class.getResourceAsstream(loadFile.getName());
            OutputStream fout = Files.newOutputStream(saveFile);
            
            CipherOutputStream cipherOut = new CipherOutputStream(fout,cipher) {
    }) {
        final byte[] bytes = new byte[1024];
        for(int length=fin.read(bytes); length!=-1; length = fin.read(bytes)){
            
            
            if(fileStoreIV) {
                fout.write(initVector);
                fileStoreIV = false;
            }
            
            cipherOut.write(bytes,length);
            
        }
    } catch (IOException e) {
        System.out.println("Something went wrong with reading and writing these files!");
        System.out.println("Please check you have the latest version of this program");
        System.out.println("Contact your IT admin to make sure you have sufficient privileges");
    }
    System.out.println("SUCCESS! Encryption finished,saved at specified location");

解密方法

private static void decrypt(String inputKEY,String inputIV,IOException,InvalidAlgorithmParameterException {
    //Initalisation for decryption
    Cipher cipher = Cipher.getInstance(CIPHER);
    if(!fileStoreIV) {
        IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(inputIV));
        SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(inputKEY),ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE,iv);
    }
    
    Path saveFile = Paths.get(outputFile);
    
    Path loadFilePath = Paths.get(inputFile);
    if (!Files.exists(loadFilePath)){
        System.out.println("The inputFile you specified does not exist");
        return;
    }
    
    Path parentDir = saveFile.getParent();
    if (parentDir != null && !Files.exists(parentDir)) {
        System.out.println("The outputFile directory/s you specified does not exist");
        return;
    }
    
    InputStream encryptedData = Files.newInputStream(loadFilePath);
    
    if(fileStoreIV) {
        {
            byte[] fileIV = new byte[16];
            encryptedData.read(fileIV);
            System.out.println(Base64.getEncoder().encodetoString(fileIV));
                SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(inputKEY),ALGORITHM);
                cipher.init(Cipher.DECRYPT_MODE,new IvParameterSpec(fileIV));
                fileStoreIV = false;
        }
    }
    
        try (CipherInputStream decryptStream = new CipherInputStream(encryptedData,cipher);    
        OutputStream decryptedOut = Files.newOutputStream(saveFile)){
        final byte[] bytes = new byte[1024];
        for(int length=decryptStream.read(bytes); length!=-1; length = decryptStream.read(bytes)){
            decryptedOut.write(bytes,length);
        }
    } catch (IOException e) {
        System.out.println("Something went wrong with reading and writing these files!");
        System.out.println("Please check you have the latest version of this program");
        System.out.println("Contact your IT admin to make sure you have sufficient privileges");
    }
    
    System.out.println("SUCESS! Decryption finished,saved at specified location");

其他说明:当我在纯文本文件之前和内部添加足够的空格时。我设法将足够多的文本移到上方,以显示解密的文件<a few encrypted characters> my secret motto: i am awesome!

解决方法

解密未成功运行的主要部分是您的Encrypt方法中的这段代码:

if(fileStoreIV) {
     SecretKeySpec skeySpec = new SecretKeySpec(key,ALGORITHM);
     cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
} else {
     IvParameterSpec iv = new IvParameterSpec(initVector);
     SecretKeySpec skeySpec = new SecretKeySpec(key,skeySpec,iv);
}

fileStoreIV == true中,您没有为cipher.init函数指定IV。而且由于IV错误,解密后的明文的第一个块(AES为16个字节)被有效的随机垃圾所代替;根据其长度(根据@ dave_thompson_085的评论),它可能是纯文本的一半,全部或很小一部分。

我修改了您的代码,因为它由于其他一些错误而无法立即使用,但是我懒得去更正它们,而是在下面找到了完整的示例代码。

这是程序的输出,我的纯文本文件包含文本The quick brown fox jumps over the lazy dog

Secret key is S2guVMqVk8goYy3QsgBSMmjLLCyvoknprTGoFsxMZEo=
IV is VFIYWeCT6ixg/lwk9bBQ9g==
SUCCESS! Encryption finished,saved at specified location
SUCESS! Decryption finished,saved at specified location
Content of file decryptedtext.txt
The quick brown fox jumps over the lazy dog

代码:

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.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class FileEncryptorSo {
    static String ALGORITHM = "AES";
    static String CIPHER = "AES/CBC/PKCS5PADDING";
    static boolean fileStoreIV = true;

    public static void main(String[] args) throws IOException,InvalidKeyException,NoSuchAlgorithmException,NoSuchPaddingException,InvalidAlgorithmParameterException {
        System.out.println("");
        String plaintextFilename = "plaintext.txt";
        String ciphertextFilename = "ciphertext.enc";
        String decryptedFilename = "decryptedtext.txt";
        // random aes 256 key
        byte[] key = new byte[32];
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(key);
        // random iv
        byte[] iv = new byte[16];
        secureRandom.nextBytes(iv);
        encrypt(key,iv,plaintextFilename,ciphertextFilename);
        decrypt(Base64.getEncoder().encodeToString(key),Base64.getEncoder().encodeToString(iv),ciphertextFilename,decryptedFilename);
        printTextfile(decryptedFilename);
    }

    private static void encrypt(byte[] key,byte[] initVector,String inputFile,String outputFile)
            throws NoSuchAlgorithmException,InvalidAlgorithmParameterException {
        //Initalisation for encryption
        Cipher cipher = Cipher.getInstance(CIPHER);
        IvParameterSpec iv = new IvParameterSpec(initVector);
        SecretKeySpec skeySpec = new SecretKeySpec(key,ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,iv);
        /* ### leave out this part !
        if (fileStoreIV) {
            SecretKeySpec skeySpec = new SecretKeySpec(key,ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
        } else {
            IvParameterSpec iv = new IvParameterSpec(initVector);
            SecretKeySpec skeySpec = new SecretKeySpec(key,iv);
        }
         */
        //File error checking
        // ### not used File loadFile = new File(inputFile);
        Path saveFile = Paths.get(outputFile);
        Path loadFilePath = Paths.get(inputFile);
        if (!Files.exists(loadFilePath)) {
            System.out.println("The inputFile you specified does not exist");
            return;
        }
        Path parentDir = saveFile.getParent();
        if (parentDir != null && !Files.exists(parentDir)) {
            System.out.println("The outputFile directory/s you specified does not exist");
            return;
        }
        System.out.println("Secret key is " + Base64.getEncoder().encodeToString(key));
        System.out.println("IV is " + Base64.getEncoder().encodeToString(initVector));
        try (FileInputStream in = new FileInputStream(inputFile);
             FileOutputStream out = new FileOutputStream(outputFile);
             CipherOutputStream encryptedOutputStream = new CipherOutputStream(out,cipher);) {
            if (fileStoreIV) {
                out.write(initVector);
                // ### leave out this line fileStoreIV = false;
            }
            byte[] buffer = new byte[1024];
            int nread;
            while ((nread = in.read(buffer)) > 0) {
                encryptedOutputStream.write(buffer,nread);
            }
            encryptedOutputStream.flush();
        } catch (IOException e) {
            System.out.println("Something went wrong with reading and writing these files!");
            System.out.println("Please check you have the latest version of this program");
            System.out.println("Contact your IT admin to make sure you have sufficient privileges");
        }
        System.out.println("SUCCESS! Encryption finished,saved at specified location");
    }

    private static void decrypt(String inputKEY,String inputIV,InvalidAlgorithmParameterException {
        //Initalisation for decryption
        Cipher cipher = Cipher.getInstance(CIPHER);
        if (!fileStoreIV) {
            IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(inputIV));
            SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(inputKEY),ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE,iv);
        }
        Path saveFile = Paths.get(outputFile);
        Path loadFilePath = Paths.get(inputFile);
        if (!Files.exists(loadFilePath)) {
            System.out.println("The inputFile you specified does not exist");
            return;
        }
        Path parentDir = saveFile.getParent();
        if (parentDir != null && !Files.exists(parentDir)) {
            System.out.println("The outputFile directory/s you specified does not exist");
            return;
        }
        //byte[] fileIV = new byte[16];
        try (FileInputStream in = new FileInputStream(inputFile);
             CipherInputStream cipherInputStream = new CipherInputStream(in,cipher);
             FileOutputStream out = new FileOutputStream(outputFile))
        {
            byte[] buffer = new byte[1024];
            if (fileStoreIV) {
                byte[] fileIV = new byte[16];
                in.read(fileIV);
                SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(inputKEY),ALGORITHM);
                cipher.init(Cipher.DECRYPT_MODE,new IvParameterSpec(fileIV));
                // ### leave out his line fileStoreIV = false;
            }
            int nread;
            while ((nread = cipherInputStream.read(buffer)) > 0) {
                out.write(buffer,nread);
            }
            out.flush();
        } catch (IOException e) {
            System.out.println("Something went wrong with reading and writing these files!");
            System.out.println("Please check you have the latest version of this program");
            System.out.println("Contact your IT admin to make sure you have sufficient privileges");
        }
        System.out.println("SUCESS! Decryption finished,saved at specified location");
    }

    private static void printTextfile (String filename) throws IOException {
        File file = new File(filename);
        FileInputStream fis = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        fis.read(data);
        fis.close();
        String str = new String(data,"UTF-8");
        System.out.println("Content of file " + filename + "\n" + str);
    }
}