RSA逐块加密会为大于1kb的文件生成空白输出

Cra*_*ing 1 java encryption cryptography file output

我没有为AES或其他加密打开这个线程,因为这是我将用来加密AES和其他加密的密钥.我从StackOverflow和其他一些网站收集了几个代码并编辑它以适合我的程序但是当我尝试使用RSA问题进行逐块加密时,我只能加密大小为1千字节的小文本文件.文本文件的加密和解密工作正常.然而,加密图片和的任何文件较大超过1千字节会产生一个空白的加密文件.

我想请求帮助,如果有人可以帮我指出这段代码导致大于1千字节的文件导致空白输出文件/加密文件.这段代码适用于AES,但我不确定为什么它不适用于RSA加密.问题始于Encrypt_File它所读取循环的某个地方.

码:

public static final String ALGORITHM = "RSA";
private static final short KEY_LENGTH = 1024;
private static final short KEY_BYTES = 32;
private static final String CIPHER_EXTENSION = ".cgfile";

public void Encrypt_File(Path path_fileToEncrypt) {
    //get file name and the new file name
    String fileName = path_fileToEncrypt.getFileName().toString();
    String encryptedFileName = fileName+CIPHER_EXTENSION;
    String pathToEncryptedFile = path_fileToEncrypt.getParent()+File.separator+encryptedFileName;

    //attempt to open the public key
    try (ObjectInputStream publicKeyFile = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE))) {
        //load the key
        PublicKey publicKey = (PublicKey) publicKeyFile.readObject();

        // load file to encrypt and inputstream
        FileInputStream fileInputStream = new FileInputStream(new File(path_fileToEncrypt.toString()));

        // init the cipher
        final Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(pathToEncryptedFile),cipher);
        byte[] buffer = new byte[KEY_BYTES];
        int count;
        while((count = fileInputStream.read(buffer))>0){
            cos.write(buffer, 0, count);
        }

        //close
        fileInputStream.close();
        cos.close();
        //delete fileToEncrypt since we have the encrypted file now
        DeleteFile(new File(path_fileToEncrypt.toString()));
        System.out.println("Finished encrypting "+ fileName +" It's new file name is "+ encryptedFileName);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) {
    try {

        CGcipher rsaencrypt = new CGcipher();
        Path pathTosecret = Paths.get(System.getProperty("user.dir"), "pic.png");
        // Encrypt the string using the public key
        rsaencrypt.Encrypt_File(pathTosecret);
        //rsaencrypt.Decrypt_File(pathTosecret);

    } catch (Exception e) {
        System.out.println(e.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

Ebb*_*sen 5

RSA不适用于批量加密,因为与AES等对称算法相比,它的退出速度较慢(速度超过1000倍).可以使用RSA在一个块中加密的数据量取决于密钥大小和填充可能使用的任何数据.

当您需要RSA的两个密钥并且同时需要加密比一个RSA块中的密钥更多时,您通常会使用混合加密,其中您使用随机对称密钥加密数据部分,然后加密加密RSA的关键.这样您就可以获得对称密钥的速度以及RSA的两个密钥.但是如果你真的不需要使用不同的密钥进行加密和解密,那么你根本就不应该使用RSA.

由于RSA不适用于批量加密,因此当您尝试加密比一个块中的更多时,标准实现无法处理它 - 没有实现使用RSA 链接加密块的逻辑.这将是开箱即用的对称密码的处理方式.