diff --git a/src/Pay/Encryptor.ts b/src/Pay/Encryptor.ts new file mode 100644 index 0000000..dca1236 --- /dev/null +++ b/src/Pay/Encryptor.ts @@ -0,0 +1,31 @@ +'use strict'; +import { PrivateKey } from "../Core/Support/PrivateKey"; +import { PublicKey } from "../Core/Support/PublicKey"; +import RSA from "../Core/Support/RSA"; + +class Encryptor extends RSA { + protected publicCert: PublicKey; + protected privateCert: PrivateKey; + + /** + * 设置加密机所需的公私密钥 + * @param publicCert PublicKey封装的公钥 + * @param privateCert PrivateKey封装的私钥 + */ + setCerts(publicCert: PublicKey, privateCert: PrivateKey) { + this.publicCert = publicCert; + this.privateCert = privateCert; + this.setPublicKey(publicCert.toString()); + this.setPrivateKey(privateCert.toString()); + } + + /** + * 获取公钥的序列号 + */ + getSerialNo(): string { + return this.publicCert.getSerialNo(); + } + +} + +export = Encryptor; diff --git a/src/Pay/Utils.ts b/src/Pay/Utils.ts index e421cc6..cfb176b 100644 --- a/src/Pay/Utils.ts +++ b/src/Pay/Utils.ts @@ -5,6 +5,7 @@ import RSA from '../Core/Support/RSA'; import { createHash, createHmac, getTimestamp, randomString } from '../Core/Support/Utils'; import { PayAppConfig, PayBridgeConfig, PaySdkConfig } from '../Types/global'; import MerchantInterface from './Contracts/MerchantInterface'; +import Encryptor from './Encryptor'; class Utils { @@ -30,13 +31,12 @@ class Utils * @returns */ async getEncryptor(platformCert: PublicKey = null) { - let rsa = new RSA; if (!platformCert || !(platformCert instanceof PublicKey)) { platformCert = await this.getPlatformCert(); } - rsa.setPublicKey(platformCert.toString()); - rsa.setPrivateKey(this.merchant.getPrivateKey().toString()); - return rsa; + let encryptor = new Encryptor; + encryptor.setCerts(platformCert, this.merchant.getPrivateKey()); + return encryptor; } /** diff --git a/test/Pay/Utils.test.js b/test/Pay/Utils.test.js index 53d004b..5a28720 100644 --- a/test/Pay/Utils.test.js +++ b/test/Pay/Utils.test.js @@ -30,10 +30,9 @@ class TestUnit extends BaseTestUnit { it('Should encrypt and decrypt correctly', async () => { let data = 'Abc123'; - let cert = await utils.getPlatformCert(); - let encryptor = await utils.getEncryptor(cert); + let encryptor = await utils.getEncryptor(); let ciphertext = encryptor.encrypt(data); - this.assert.strictEqual(cert.getSerialNo(), '0DC0DF83'); + this.assert.strictEqual(encryptor.getSerialNo(), '0DC0DF83'); let plaintext = encryptor.decrypt(ciphertext); this.assert.strictEqual(plaintext, data);