支持选择证书后缀为.key或.pem

This commit is contained in:
wzj 2025-06-14 09:34:08 +08:00
parent e38cf29bb4
commit 6361806dcb
2 changed files with 51 additions and 28 deletions

70
app.py
View File

@ -922,39 +922,55 @@ def export_certificate_view(cert_id):
}
)
elif format_type == 'pem_separate':
# 创建内存中的zip文件
memory_file = BytesIO()
try:
with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf:
# 添加证书文件
with open(cert['cert_path'], 'r') as f:
cert_content = f.read()
zf.writestr(f"{cert['common_name']}.pem", cert_content)
# 添加私钥文件
with open(cert['key_path'], 'r') as f:
key_content = f.read()
zf.writestr(f"{cert['common_name']}.key", key_content)
memory_file.seek(0)
return Response(
memory_file.getvalue(),
mimetype="application/zip",
headers={
"Content-Disposition": f"attachment; filename={cert['common_name']}_separate.zip"
}
)
except Exception as e:
flash(f'创建ZIP文件失败: {str(e)}', 'danger')
return redirect(url_for('export_certificate_view', cert_id=cert_id))
# 创建内存中的zip文件(.pem + .key)
return generate_separate_files_zip(
cert,
cert_ext=".pem",
zip_suffix="_pem_key"
)
elif format_type == 'crt_separate':
# 创建内存中的zip文件(.crt + .key)
return generate_separate_files_zip(
cert,
cert_ext=".crt",
zip_suffix="_crt_key"
)
else:
flash('不支持的导出格式', 'danger')
return render_template('export_certificate.html', cert=cert)
def generate_separate_files_zip(cert, cert_ext, zip_suffix):
"""生成包含分开文件的ZIP包通用函数"""
memory_file = BytesIO()
try:
with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf:
# 添加证书文件
with open(cert['cert_path'], 'r') as f:
cert_content = f.read()
zf.writestr(f"{cert['common_name']}{cert_ext}", cert_content)
# 添加私钥文件
with open(cert['key_path'], 'r') as f:
key_content = f.read()
zf.writestr(f"{cert['common_name']}.key", key_content)
memory_file.seek(0)
return Response(
memory_file.getvalue(),
mimetype="application/zip",
headers={
"Content-Disposition": f"attachment; filename={cert['common_name']}{zip_suffix}.zip"
}
)
except Exception as e:
flash(f'创建ZIP文件失败: {str(e)}', 'danger')
return redirect(url_for('export_certificate_view', cert_id=cert['id']))
@app.route('/download/<path:filename>')
@login_required
def download_file(filename):

View File

@ -30,7 +30,14 @@
<label class="form-check-label" for="formatPemSeparate">
PEM (.pem) - 分开文件
</label>
<div class="form-text">Base64编码的证书和私钥作为两个单独文件</div>
<div class="form-text">Base64编码的证书(.pem)和私钥(.key)作为两个单独文件</div>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="format" id="formatCrtSeparate" value="crt_separate">
<label class="form-check-label" for="formatCrtSeparate">
CRT (.crt) - 分开文件
</label>
<div class="form-text">Base64编码的证书(.crt)和私钥(.key)作为两个单独文件</div>
</div>
</div>