import { Base } from './Base'; import { getCertificationAttribute } from '../config/ClientConfig' import { sendHttpsRequest } from '../node/sendHttpRequest'; import { ICertResponse } from '../interface/LocalStorage'; import { generateKeypairPem, pemToPrivateKey, pemToPublicKey, certificationRequest, utf8tob64, pemtohex, } from "@vf.js/pki" export interface CertInfo extends ICertResponse { privateKeyPem?: string; pubblicKeyPem?: string; } export class CallUserCertification extends Base { /** 用于区分证书的唯一ID,一般使用地址 */ public address: string | null = null; protected async getDefaultRequest() { let pemCSR: string = ''; let pairKeyObject: { priPem: string | null pubPem: string | null } = {} as any; if (!this.address) { throw new Error("CallUserCertification->请设置address"); } if (!this.userConfig.orgId) { throw new Error("CallUserCertification->请设置userConfig.orgId"); } if (this.autoCreteKeyPair) { const keypairPem = generateKeypairPem({ "alg": 'EC', "curve": "secp256r1" }) if (keypairPem) { pairKeyObject.priPem = keypairPem.privateKeyPem; pairKeyObject.pubPem = keypairPem.publicKeyPem; } } else { pairKeyObject.priPem = this.privateKeyPem; pairKeyObject.pubPem = this.publicKeyPem; } if (pairKeyObject.priPem && pairKeyObject.pubPem) { const privateKey = await pemToPrivateKey(pairKeyObject.priPem); const publicKey = await pemToPublicKey(pairKeyObject.pubPem); // 执行生成 CSR const csr = await certificationRequest(privateKey, publicKey, getCertificationAttribute({ address: this.address!, orgId: this.userConfig.orgId! })) pemCSR = csr.csrPem } return { userId: this.address, source: this.userConfig.source, orgId: this.userConfig.orgId, userType: this.userConfig.userType, certUsage: this.userConfig.certUsage, pubHex: pemtohex(pairKeyObject.pubPem!), csr: utf8tob64(pemCSR) } } private async sendCsr() { const request = await this.getRequest() const result = await sendHttpsRequest(request, { url: '/chain/business/v1/genCertByCsr' }) return result } /** * 查询证书 * @returns */ async sendCertQuery() { const request = { // userType: this.userConfig.userType, // certUsage: this.userConfig.certUsage, // certSn: this.certSn } const result = await sendHttpsRequest(request, { url: '/chain/business/v1/queryCerts' }) return result } /** * 申请证书 * @returns */ async send() { // 本地存在 // let certObject = await LocalStorage.get('pemCertificate'); // if (certObject) { // return { code: 200, data: certObject.value, message: '证书已存在' }; // } // 都不存在,申请新的 const csrResult = await this.sendCsr(); if (csrResult && csrResult.code === 200) { return { code: 200, data: csrResult.data, message: '证书申请成功' };; } return { code: 500, data: undefined, message: '证书申请失败' }; } }