将密码放入 grails 错误中的 zip 文件

put password to a zip file in grails errors

因为我可以在 zip 文件上设置密码 grails

package zip
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

class SampleZipController {
def index() { }
def downloadSampleZip() {
    response.setContentType('APPLICATION/OCTET-STREAM')
    response.setHeader('Content-Disposition', 'Attachment;Filename="example.zip"')
    ZipOutputStream zip = new ZipOutputStream(response.outputStream);

    def file1Entry = new ZipEntry('first_file.txt');
    zip.putNextEntry(file1Entry);
    zip.write("This is the content of the first file".bytes);   
    def file2Entry = new ZipEntry('second_file.txt');
    zip.putNextEntry(file2Entry);
    zip.write("This is the content of the second file".bytes);
    zip.setPassword("password");

    zip.close();

}
} 

问题是我设置了 setPassword 属性 并且没有创建任何 zip 文件,因为我得到了错误的保留字。

好的,这就是交易。 Java SDK 不为 zip 文件提供密码保护。 ZipOutputStream.setPassword() 不存在,也没有任何其他设置密码的方法。

您可以改为使用第三方库。这是一个 Groovy 脚本,演示如何使用 Winzipaes:

密码保护 ZIP 文件
@Grab('de.idyl:winzipaes:1.0.1')

import de.idyl.winzipaes.AesZipFileEncrypter
import de.idyl.winzipaes.impl.AESEncrypterBC

def outputStream = new FileOutputStream('test.zip') /* Create an OutputStream */
def encrypter = new AesZipFileEncrypter(outputStream, new AESEncrypterBC())
def password = 'password'

encrypter.add('first_file.txt', new ByteArrayInputStream('This is the content of the first file'.bytes), password)
encrypter.add('second_file.txt', new ByteArrayInputStream('This is the content of the second file'.bytes), password)
encrypter.close()

如您所见,API 与您使用的相似。请记住,这是一个 Groovy 脚本 没有 Grails,因此请确保适当地添加 Winzipaes 依赖项(不要使用 @Grab)。

注意:加密算法为AES256,并非所有ZIP客户端都支持。例如,在 Mac OSX 上,我必须安装 7-zip 才能解密文件;内置的 ZIP 工具不起作用。

您可以阅读有关密码保护 ZIP 文件的更多信息here