最近有需求要做excel加密,实现方式是设置密码。
看代码:
public static void setPassword4OOXML(InputStream inputStream, OutputStream outputStream, String password) {
try (POIFSFileSystem fs = new POIFSFileSystem()) {
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(password);
try (OPCPackage opc = OPCPackage.open(inputStream);
OutputStream os = enc.getDataStream(fs)) {
opc.save(os);
}
fs.writeFilesystem(outputStream);
} catch (Exception e) {
log.error("setPwd4OOXML ex : {}" ,e);
}
}
public static void setPassword4OfficeFile(String path, String password) {
try (POIFSFileSystem fs = new POIFSFileSystem()) {
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(password);
try (OPCPackage opc = OPCPackage.open(new File(path), PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs)) {
opc.save(os);
}
try (FileOutputStream fos = new FileOutputStream(path)) {
fs.writeFilesystem(fos);
}
} catch (Exception e) {
log.error("setPwd office file ex : {}" ,e);
}
}
要啥自行车,代码请自行优化 TODO
参考:https://poi.apache.org/encryption.html
网友评论