// 加密证书 'use strict'; const Controller = require('egg').Controller; const UUID = require('uuid'); const assert = require('assert'); const filePath = require('../../config/filespath'); class EnccertController extends Controller { // 加密证书上传 async enccertupload() { const { ctx } = this; // 获取文件流 const stream = await ctx.getFileStream(); // 创建uuid const uuid = UUID.v1(); // 获取参数 const password = stream.fields.password; const name = stream.fields.name; assert(password, '请输入密码'); assert(name, '请输入名称'); // 创建文件名 const fileName = `${filePath.p12}${uuid}.p12`; // 获取数据文件 const configJson = require(filePath.configJson); try { // 存储P12文件 const res = await this.service.fileshandler.upload({ name: fileName, stream }); // 存储成功 if (res.errcode === 0) { // 拆出key const keys = await this.service.shell.keys({ password, fileName }); // 拆出成功 if (keys.errcode === 0) { // 存储p8文件 const p8 = await this.service.fileshandler.write({ filePath: `${filePath.keys}${uuid}.p8`, str: keys.data }); if (p8.errcode === 0) { // 转换p8文件 await this.service.shell.transform({ files: `${filePath.keys}${uuid}.p8`, target: `${filePath.keys}${uuid}.key` }); } } // 拆出cer文件 const certs = await this.service.shell.certs({ password, fileName }); if (certs.errcode === 0) { let dn, pwatype; // 存储cer文件 await this.service.fileshandler.write({ filePath: `${filePath.cert}${uuid}.cer`, str: certs.data }); // 获取cer信息 const dns = await this.service.shell.read({ filePath: `${filePath.cert}${uuid}.cer` }); // 获取dn if (dns.errcode === 0 && dns.data) { dns.data.trim().split('\n').forEach(function(v) { if (v.includes('Subject:')) { dn = v.replace('Subject:', ''); } if (v.includes('ASN1 OID:')) { pwatype = v.replace('ASN1 OID:', ''); } }); } // 制作数据 configJson.cert.push({ uuid, pwatype, dn, name, state: 1 }); const jsonstr = JSON.stringify(configJson); // 存储数据文件写入 await this.service.fileshandler.write({ filePath: filePath.configJson, str: jsonstr }); ctx.body = { errcode: 0, errmsg: '' }; } } } catch (error) { const body = { errcode: -1002, errmsg: '证书上传失败', error }; throw new Error(JSON.stringify(body)); } } } module.exports = EnccertController;