enccert.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // 加密证书
  2. 'use strict';
  3. const Controller = require('egg').Controller;
  4. const UUID = require('uuid');
  5. const assert = require('assert');
  6. const filePath = require('../../config/filespath');
  7. class EnccertController extends Controller {
  8. // 加密证书上传
  9. async enccertupload() {
  10. const { ctx } = this;
  11. // 获取文件流
  12. const stream = await ctx.getFileStream();
  13. // 创建uuid
  14. const uuid = UUID.v1();
  15. // 获取参数
  16. const password = stream.fields.password;
  17. const name = stream.fields.name;
  18. assert(password, '请输入密码');
  19. assert(name, '请输入名称');
  20. // 创建文件名
  21. const fileName = `${filePath.p12}${uuid}.p12`;
  22. // 获取数据文件
  23. const configJson = require(filePath.configJson);
  24. try {
  25. // 存储P12文件
  26. const res = await this.service.fileshandler.upload({ name: fileName, stream });
  27. // 存储成功
  28. if (res.errcode === 0) {
  29. // 拆出key
  30. const keys = await this.service.shell.keys({ password, fileName });
  31. // 拆出成功
  32. if (keys.errcode === 0) {
  33. // 存储p8文件
  34. const p8 = await this.service.fileshandler.write({ filePath: `${filePath.keys}${uuid}.p8`, str: keys.data });
  35. if (p8.errcode === 0) {
  36. // 转换p8文件
  37. await this.service.shell.transform({ files: `${filePath.keys}${uuid}.p8`, target: `${filePath.keys}${uuid}.key` });
  38. }
  39. }
  40. // 拆出cer文件
  41. const certs = await this.service.shell.certs({ password, fileName });
  42. if (certs.errcode === 0) {
  43. let dn,
  44. pwatype;
  45. // 存储cer文件
  46. await this.service.fileshandler.write({ filePath: `${filePath.cert}${uuid}.cer`, str: certs.data });
  47. // 获取cer信息
  48. const dns = await this.service.shell.read({ filePath: `${filePath.cert}${uuid}.cer` });
  49. // 获取dn
  50. if (dns.errcode === 0 && dns.data) {
  51. dns.data.trim().split('\n').forEach(function(v) {
  52. if (v.includes('Subject:')) {
  53. dn = v.replace('Subject:', '');
  54. }
  55. if (v.includes('ASN1 OID:')) {
  56. pwatype = v.replace('ASN1 OID:', '');
  57. }
  58. });
  59. }
  60. // 制作数据
  61. configJson.cert.push({ uuid, pwatype, dn, name, state: 1 });
  62. const jsonstr = JSON.stringify(configJson);
  63. // 存储数据文件写入
  64. await this.service.fileshandler.write({ filePath: filePath.configJson, str: jsonstr });
  65. ctx.body = { errcode: 0, errmsg: '' };
  66. }
  67. }
  68. } catch (error) {
  69. const body = { errcode: -1002, errmsg: '证书上传失败', error };
  70. throw new Error(JSON.stringify(body));
  71. }
  72. }
  73. }
  74. module.exports = EnccertController;