Skip to content

Instantly share code, notes, and snippets.

@levancho
Created August 11, 2023 00:51
Show Gist options
  • Save levancho/73a3d2dba9f248ade097ad007c0e9c7d to your computer and use it in GitHub Desktop.
Save levancho/73a3d2dba9f248ade097ad007c0e9c7d to your computer and use it in GitHub Desktop.
password protect excel
public static byte[] passwordProtectExcel(byte[] inputExcel) throws IOException, GeneralSecurityException {
// Convert the input byte array to a Workbook
XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(inputExcel));
// Prepare to encrypt the workbook
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("password"); // Set the password here
// Write the Workbook to an encrypted OutputStream
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
workbook.write(os);
os.close();
try (ByteArrayOutputStream encOs = new ByteArrayOutputStream()) {
enc.encryptDocument(os, encOs);
encOs.close();
fs.writeFilesystem(encOs);
return encOs.toByteArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment