Skip to content
Snippets Groups Projects
CryptoServiceNode.js 7.43 KiB
Newer Older
  • Learn to ignore specific revisions
  • Igor Markin's avatar
    Igor Markin committed
    "use strict";
    
    Igor Markin's avatar
    Igor Markin committed
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
        if (k2 === undefined) k2 = k;
        Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
    }) : (function(o, m, k, k2) {
        if (k2 === undefined) k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    };
    
    Igor Markin's avatar
    Igor Markin committed
    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());
        });
    };
    
    Igor Markin's avatar
    Igor Markin committed
    var __importDefault = (this && this.__importDefault) || function (mod) {
        return (mod && mod.__esModule) ? mod : { "default": mod };
    };
    
    Igor Markin's avatar
    Igor Markin committed
    Object.defineProperty(exports, "__esModule", { value: true });
    
    Igor Markin's avatar
    Igor Markin committed
    // All functions are async in order to be compatible with the ICryptoService API
    
    Igor Markin's avatar
    Igor Markin committed
    const js_md5_1 = __importDefault(require("js-md5"));
    const crypto = __importStar(require("crypto"));
    
    const common_1 = require("../../utils/common");
    
    Igor Markin's avatar
    Igor Markin committed
    const AES_GCM_ALGO = "aes-256-gcm";
    
    Igor Markin's avatar
    Igor Markin committed
    const getBytes = (value, encoding) => {
        let bytes;
        if (typeof value === "string") {
            const valueString = value;
            bytes = Buffer.from(valueString, encoding);
        }
        else {
            bytes = Buffer.from(value);
        }
        return bytes;
    };
    
        encryptAESGCM(data, key, iv) {
    
            return __awaiter(this, void 0, void 0, function* () {
    
                if (!key && !iv) {
                    key = crypto.randomBytes(32);
                    iv = crypto.randomBytes(12);
                }
    
                const cipher = crypto.createCipheriv(AES_GCM_ALGO, key, iv);
                let encrypted;
                if (typeof data === "string") {
                    encrypted = cipher.update(data, "utf8");
                }
                else {
                    encrypted = cipher.update((0, common_1.ensureUint8Array)(data));
                }
                cipher.final();
                const authTag = cipher.getAuthTag();
                const encryptedWithTag = Buffer.concat([
                    Buffer.from(encrypted),
                    Buffer.from(authTag),
                ]);
                return {
    
                    key: key,
                    iv: iv,
    
                    data: encryptedWithTag,
                };
            });
        }
        decryptAESGCM(data, key, iv, returnBuffer) {
            return __awaiter(this, void 0, void 0, function* () {
                const decipher = crypto.createDecipheriv(AES_GCM_ALGO, Buffer.from(key), Buffer.from(iv));
                const authTag = data.slice(data.byteLength - 16, data.byteLength);
                const encrypted = data.slice(0, data.byteLength - 16);
                if (returnBuffer) {
                    const decrypted = decipher.update((0, common_1.ensureUint8Array)(encrypted));
                    decipher.setAuthTag(Buffer.from(authTag));
                    return Buffer.concat([decrypted, decipher.final()]);
                }
                let str = decipher.update((0, common_1.ensureUint8Array)(encrypted), null, "utf8");
                decipher.setAuthTag(Buffer.from(authTag));
                str += decipher.final("utf8");
                return str;
            });
        }
        generateRSAKeys() {
            return __awaiter(this, void 0, void 0, function* () {
                const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
                    modulusLength: 4096,
                    publicKeyEncoding: {
                        type: "spki",
                        format: "pem",
                    },
                    privateKeyEncoding: {
                        type: "pkcs8",
                        format: "pem",
                    },
                });
                return {
                    publicKeyPEM: publicKey,
                    privateKeyPEM: privateKey,
                };
            });
        }
        encryptRSA(publicKeyPEM, data) {
            return __awaiter(this, void 0, void 0, function* () {
                const encryptedData = crypto.publicEncrypt({
                    key: publicKeyPEM,
                    padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
                    oaepHash: "sha256",
                }, 
                // We convert the data string to a buffer using `Buffer.from`
                Buffer.from(data));
                return encryptedData.buffer;
            });
        }
        decryptRSA(privateKeyPEM, data) {
            return __awaiter(this, void 0, void 0, function* () {
                const encryptedData = crypto.privateDecrypt({
                    key: privateKeyPEM,
                    padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
                    oaepHash: "sha256",
                }, 
                // We convert the data string to a buffer using `Buffer.from`
                Buffer.from(data));
                return encryptedData.buffer;
            });
        }
        signRSA(privateKeyPEM, data) {
            return __awaiter(this, void 0, void 0, function* () {
                const sign = crypto.createSign("SHA256");
                sign.update(Buffer.from(data));
                sign.end();
                return sign.sign(privateKeyPEM).buffer;
            });
        }
        SHA1(value, encoding = "utf8") {
            return __awaiter(this, void 0, void 0, function* () {
                const bytes = getBytes(value, encoding);
                return crypto.createHash("sha1").update(bytes).digest();
            });
        }
        SHA256(value, encoding = "utf8") {
            return __awaiter(this, void 0, void 0, function* () {
                const bytes = getBytes(value, encoding);
                return crypto.createHash("sha256").update(bytes).digest();
            });
        }
        SHA384(value, encoding = "utf8") {
            return __awaiter(this, void 0, void 0, function* () {
                const bytes = getBytes(value, encoding);
                return crypto.createHash("sha384").update(bytes).digest();
            });
        }
        SHA512(value, encoding = "utf8") {
            return __awaiter(this, void 0, void 0, function* () {
                const bytes = getBytes(value, encoding);
                return crypto.createHash("sha512").update(bytes).digest();
            });
        }
        MD5(value, encoding = "utf8") {
            return __awaiter(this, void 0, void 0, function* () {
                const bytes = getBytes(value, encoding);
                return js_md5_1.default.arrayBuffer(bytes);
            });
        }
        verifyRSASignature(publicKeyPEM, data, signature) {
            return __awaiter(this, void 0, void 0, function* () {
                const verify = crypto.createVerify("SHA256");
                verify.update(Buffer.from(data));
                verify.end();
                const publicKey = crypto.createPublicKey(Buffer.from(publicKeyPEM, "utf-8"));
                return verify.verify(publicKey, Buffer.from(signature));
            });
        }
    }
    exports.default = CryptoServiceNode;