js-databox
Version:
databox & metabox
73 lines (72 loc) • 2.94 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { RSAEncryptApi } from "./RSAEncrypt";
import { AESEncryptApi } from "./AESEncrypt";
class Encrypt {
aesKeyGen() {
return __awaiter(this, void 0, void 0, function* () {
let aesKey = "";
const array = new BigUint64Array(16);
window.crypto.getRandomValues(array);
array.forEach(v => {
aesKey += v.toString(16);
});
while (aesKey.length < 256)
aesKey += "0";
return aesKey;
});
}
genRSAKey() {
return __awaiter(this, void 0, void 0, function* () {
try {
const keyPair = yield RSAEncryptApi.generateKey();
const pemPrivateKey = yield RSAEncryptApi.exportCryptoKey(keyPair.privateKey);
const pemPublicKey = yield RSAEncryptApi.publicExportCryptoKey(keyPair.publicKey);
return {
privateKey: pemPrivateKey,
publicKey: pemPublicKey
};
}
catch (e) {
throw e;
}
});
}
encryptPrivateKey(privateKey, passwordHash, Iv) {
return __awaiter(this, void 0, void 0, function* () {
try {
const u8 = yield AESEncryptApi.AESEncData(privateKey, passwordHash, Iv);
return String.fromCharCode.apply(null,
//@ts-ignore
new Uint8Array(u8));
}
catch (e) {
throw e;
}
});
}
decryptPrivateKey(prePrivateKey, passwordHash, Iv) {
return __awaiter(this, void 0, void 0, function* () {
try {
const buf = new ArrayBuffer(prePrivateKey.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = prePrivateKey.length; i < strLen; i++) {
bufView[i] = prePrivateKey.charCodeAt(i);
}
const plainText = AESEncryptApi.AESDecData(bufView.buffer, passwordHash, Iv);
return new TextDecoder().decode(plainText);
}
catch (e) {
throw e;
}
});
}
}
export const EncryptApi = new Encrypt();