// FtsSignPlugin Js 12.10.2018 16:06:16 // // FtsActions.CadesApi.js // // Cades API 2.0.13292 (function () { // Already loaded if (window.cadesplugin) return; var pluginObject; var plugin_resolved = 0; var plugin_reject; var plugin_resolve; var isOpera = 0; var isFireFox = 0; var isEdge = 0; var failed_extensions = 0; var canPromise = !!window.Promise; var cadesplugin; if (canPromise) { cadesplugin = new Promise(function (resolve, reject) { plugin_resolve = resolve; plugin_reject = reject; }); } else { cadesplugin = {}; } function check_browser() { var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if (/trident/i.test(M[1])) { tem = /\brv[ :]+(\d+)/g.exec(ua) || []; return { name: 'IE', version: (tem[1] || '') }; } if (M[1] === 'Chrome') { tem = ua.match(/\b(OPR|Edge)\/(\d+)/); if (tem != null) return { name: tem[1].replace('OPR', 'Opera'), version: tem[2] }; } M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]); return { name: M[0], version: M[1] }; } var browserSpecs = check_browser(); function cpcsp_console_log(level, msg) { //IE9 не может писать в консоль если не открыта вкладка developer tools if (typeof (console) == 'undefined') return; if (level <= cadesplugin.current_log_level) { if (level == cadesplugin.LOG_LEVEL_DEBUG) console.log("DEBUG: %s", msg); if (level == cadesplugin.LOG_LEVEL_INFO) console.info("INFO: %s", msg); if (level == cadesplugin.LOG_LEVEL_ERROR) console.error("ERROR: %s", msg); return; } } function set_log_level(level) { if (!((level == cadesplugin.LOG_LEVEL_DEBUG) || (level == cadesplugin.LOG_LEVEL_INFO) || (level == cadesplugin.LOG_LEVEL_ERROR))) { cpcsp_console_log(cadesplugin.LOG_LEVEL_ERROR, "cadesplugin_api.js: Incorrect log_level: " + level); return; } cadesplugin.current_log_level = level; if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG) cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, "cadesplugin_api.js: log_level = DEBUG"); if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO) cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, "cadesplugin_api.js: log_level = INFO"); if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR) cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, "cadesplugin_api.js: log_level = ERROR"); if (isNativeMessageSupported()) { if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG) window.postMessage("set_log_level=debug", "*"); if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO) window.postMessage("set_log_level=info", "*"); if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR) window.postMessage("set_log_level=error", "*"); } } function set_constantValues() { cadesplugin.CAPICOM_LOCAL_MACHINE_STORE = 1; cadesplugin.CAPICOM_CURRENT_USER_STORE = 2; cadesplugin.CADESCOM_LOCAL_MACHINE_STORE = 1; cadesplugin.CADESCOM_CURRENT_USER_STORE = 2; cadesplugin.CADESCOM_CONTAINER_STORE = 100; cadesplugin.CAPICOM_MY_STORE = "My"; cadesplugin.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2; cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1; cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED = 0; cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPING = 1; cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE = 2; cadesplugin.XmlDsigGost3410UrlObsolete = "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411"; cadesplugin.XmlDsigGost3411UrlObsolete = "http://www.w3.org/2001/04/xmldsig-more#gostr3411"; cadesplugin.XmlDsigGost3410Url = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411"; cadesplugin.XmlDsigGost3411Url = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411"; cadesplugin.CADESCOM_CADES_DEFAULT = 0; cadesplugin.CADESCOM_CADES_BES = 1; cadesplugin.CADESCOM_CADES_T = 0x5; cadesplugin.CADESCOM_CADES_X_LONG_TYPE_1 = 0x5d; cadesplugin.CADESCOM_ENCODE_BASE64 = 0; cadesplugin.CADESCOM_ENCODE_BINARY = 1; cadesplugin.CADESCOM_ENCODE_ANY = -1; cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT = 0; cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN = 1; cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY = 2; cadesplugin.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME = 0; cadesplugin.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME = 1; cadesplugin.CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0; cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1; cadesplugin.CAPICOM_CERTIFICATE_FIND_ISSUER_NAME = 2; cadesplugin.CAPICOM_CERTIFICATE_FIND_ROOT_NAME = 3; cadesplugin.CAPICOM_CERTIFICATE_FIND_TEMPLATE_NAME = 4; cadesplugin.CAPICOM_CERTIFICATE_FIND_EXTENSION = 5; cadesplugin.CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY = 6; cadesplugin.CAPICOM_CERTIFICATE_FIND_APPLICATION_POLICY = 7; cadesplugin.CAPICOM_CERTIFICATE_FIND_CERTIFICATE_POLICY = 8; cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_VALID = 9; cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID = 10; cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED = 11; cadesplugin.CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12; cadesplugin.CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 128; cadesplugin.CAPICOM_PROPID_ENHKEY_USAGE = 9; cadesplugin.CAPICOM_OID_OTHER = 0; cadesplugin.CAPICOM_OID_KEY_USAGE_EXTENSION = 10; cadesplugin.CAPICOM_EKU_CLIENT_AUTH = 2; cadesplugin.CAPICOM_EKU_SMARTCARD_LOGON = 5; cadesplugin.CAPICOM_EKU_OTHER = 0; cadesplugin.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0; cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME = 1; cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION = 2; cadesplugin.CADESCOM_ATTRIBUTE_OTHER = -1; cadesplugin.CADESCOM_STRING_TO_UCS2LE = 0; cadesplugin.CADESCOM_BASE64_TO_BINARY = 1; cadesplugin.CADESCOM_DISPLAY_DATA_NONE = 0; cadesplugin.CADESCOM_DISPLAY_DATA_CONTENT = 1; cadesplugin.CADESCOM_DISPLAY_DATA_ATTRIBUTE = 2; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC2 = 0; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC4 = 1; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_DES = 2; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_3DES = 3; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_AES = 4; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89 = 25; cadesplugin.CADESCOM_HASH_ALGORITHM_SHA1 = 0; cadesplugin.CADESCOM_HASH_ALGORITHM_MD2 = 1; cadesplugin.CADESCOM_HASH_ALGORITHM_MD4 = 2; cadesplugin.CADESCOM_HASH_ALGORITHM_MD5 = 3; cadesplugin.CADESCOM_HASH_ALGORITHM_SHA_256 = 4; cadesplugin.CADESCOM_HASH_ALGORITHM_SHA_384 = 5; cadesplugin.CADESCOM_HASH_ALGORITHM_SHA_512 = 6; cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411 = 100; cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256 = 101; cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512 = 102; cadesplugin.LOG_LEVEL_DEBUG = 4; cadesplugin.LOG_LEVEL_INFO = 2; cadesplugin.LOG_LEVEL_ERROR = 1; cadesplugin.CADESCOM_AllowNone = 0; cadesplugin.CADESCOM_AllowNoOutstandingRequest = 0x1; cadesplugin.CADESCOM_AllowUntrustedCertificate = 0x2; cadesplugin.CADESCOM_AllowUntrustedRoot = 0x4; cadesplugin.CADESCOM_SkipInstallToStore = 0x10000000; } function async_spawn(generatorFunc) { function continuer(verb, arg) { var result; try { result = generator[verb](arg); } catch (err) { return Promise.reject(err); } if (result.done) { return result.value; } else { return Promise.resolve(result.value).then(onFulfilled, onRejected); } } var generator = generatorFunc(Array.prototype.slice.call(arguments, 1)); var onFulfilled = continuer.bind(continuer, "next"); var onRejected = continuer.bind(continuer, "throw"); return onFulfilled(); } function isIE() { // var retVal = (("Microsoft Internet Explorer" == navigator.appName) || // IE < 11 // navigator.userAgent.match(/Trident\/./i)); // IE 11 return (browserSpecs.name == 'IE' || browserSpecs.name == 'MSIE'); } function isIOS() { var retVal = (navigator.userAgent.match(/ipod/i) || navigator.userAgent.match(/ipad/i) || navigator.userAgent.match(/iphone/i)); return retVal; } function isNativeMessageSupported() { // В IE работаем через NPAPI if (isIE()) return false; // В Edge работаем через NativeMessage if (browserSpecs.name == 'Edge') { isEdge = true; return true; } // В Chrome, Firefox и Opera работаем через асинхронную версию в зависимости от версии if (browserSpecs.name == 'Opera') { isOpera = true; if (browserSpecs.version >= 33) { return true; } else { return false; } } if (browserSpecs.name == 'Firefox') { isFireFox = true; if (browserSpecs.version >= 52) { return true; } else { return false; } } if (browserSpecs.name == 'Chrome') { if (browserSpecs.version >= 42) { return true; } else { return false; } } } // Функция активации объектов КриптоПро ЭЦП Browser plug-in function CreateObject(name) { if (isIOS()) { // На iOS для создания объектов используется функция // call_ru_cryptopro_npcades_10_native_bridge, определенная в IOS_npcades_supp.js return call_ru_cryptopro_npcades_10_native_bridge("CreateObject", [name]); } if (isIE()) { // В Internet Explorer создаются COM-объекты if (name.match(/X509Enrollment/i)) { try { // Объекты CertEnroll создаются через CX509EnrollmentWebClassFactory var objCertEnrollClassFactory = document.getElementById("certEnrollClassFactory"); return objCertEnrollClassFactory.CreateObject(name); } catch (e) { throw ("Для создания обьектов X509Enrollment следует настроить веб-узел на использование проверки подлинности по протоколу HTTPS"); } } // Объекты CAPICOM и CAdESCOM создаются через CAdESCOM.WebClassFactory try { var objWebClassFactory = document.getElementById("webClassFactory"); return objWebClassFactory.CreateObject(name); } catch (e) { // Для версий плагина ниже 2.0.12538 return new ActiveXObject(name); } } // создаются объекты NPAPI return pluginObject.CreateObject(name); } function decimalToHexString(number) { if (number < 0) { number = 0xFFFFFFFF + number + 1; } return number.toString(16).toUpperCase(); } function GetMessageFromException(e) { var err = e.message; if (!err) { err = e; } else if (e.number) { err += " (0x" + decimalToHexString(e.number) + ")"; } return err; } function getLastError(exception) { if (isNativeMessageSupported() || isIE() || isIOS()) { return GetMessageFromException(exception); } try { return pluginObject.getLastError(); } catch (e) { return GetMessageFromException(exception); } } // Функция для удаления созданных объектов function ReleasePluginObjects() { return cpcsp_chrome_nmcades.ReleasePluginObjects(); } // Функция активации асинхронных объектов КриптоПро ЭЦП Browser plug-in function CreateObjectAsync(name) { return pluginObject.CreateObjectAsync(name); } //Функции для IOS var ru_cryptopro_npcades_10_native_bridge = { callbacksCount: 1, callbacks: {}, // Automatically called by native layer when a result is available resultForCallback: function resultForCallback(callbackId, resultArray) { var callback = ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId]; if (!callback) return; callback.apply(null, resultArray); }, // Use this in javascript to request native objective-c code // functionName : string (I think the name is explicit :p) // args : array of arguments // callback : function with n-arguments that is going to be called when the native code returned call: function call(functionName, args, callback) { var hasCallback = callback && typeof callback == "function"; var callbackId = hasCallback ? ru_cryptopro_npcades_10_native_bridge.callbacksCount++ : 0; if (hasCallback) ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId] = callback; var iframe = document.createElement("IFRAME"); var arrObjs = new Array("_CPNP_handle"); try { iframe.setAttribute("src", "cpnp-js-call:" + functionName + ":" + callbackId + ":" + encodeURIComponent(JSON.stringify(args, arrObjs))); } catch (e) { alert(e); } document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } }; function call_ru_cryptopro_npcades_10_native_bridge(functionName, array) { var tmpobj; var ex; ru_cryptopro_npcades_10_native_bridge.call(functionName, array, function (e, response) { ex = e; var str = 'tmpobj=' + response; eval(str); if (typeof (tmpobj) == "string") { tmpobj = tmpobj.replace(/\\\n/gm, "\n"); tmpobj = tmpobj.replace(/\\\r/gm, "\r"); } }); if (ex) throw ex; return tmpobj; } function show_firefox_missing_extension_dialog() { if (!window.cadesplugin_skip_extension_install) { var ovr = document.createElement('div'); ovr.id = "cadesplugin_ovr"; ovr.style = "visibility: hidden; position: fixed; left: 0px; top: 0px; width:100%; height:100%; background-color: rgba(0,0,0,0.7)"; ovr.innerHTML = "
" + "" + "

Для работы КриптоПро ЭЦП Browser plugin на данном сайте необходимо расширение для браузера. Убедитесь, что оно у Вас включено или установите его." + "

Скачать расширение

" + "
"; document.getElementsByTagName("Body")[0].appendChild(ovr); document.getElementById("cadesplugin_close_install").addEventListener('click', function () { plugin_loaded_error("Плагин недоступен"); document.getElementById("cadesplugin_ovr").style.visibility = 'hidden'; }); ovr.addEventListener('click', function () { plugin_loaded_error("Плагин недоступен"); document.getElementById("cadesplugin_ovr").style.visibility = 'hidden'; }); ovr.style.visibility = "visible"; } } //Выводим окно поверх других с предложением установить расширение для Opera. //Если установленна переменная cadesplugin_skip_extension_install - не предлагаем установить расширение function install_opera_extension() { if (!window.cadesplugin_skip_extension_install) { document.addEventListener('DOMContentLoaded', function () { var ovr = document.createElement('div'); ovr.id = "cadesplugin_ovr"; ovr.style = "visibility: hidden; position: fixed; left: 0px; top: 0px; width:100%; height:100%; background-color: rgba(0,0,0,0.7)"; ovr.innerHTML = "
" + "" + "

Для работы КриптоПро ЭЦП Browser plugin на данном сайте необходимо установить расширение из каталога дополнений Opera." + "

" + "
"; document.getElementsByTagName("Body")[0].appendChild(ovr); var btn_install = document.getElementById("cadesplugin_install"); btn_install.addEventListener('click', function (event) { opr.addons.installExtension("epebfcehmdedogndhlcacafjaacknbcm", function () { document.getElementById("cadesplugin_ovr").style.visibility = 'hidden'; location.reload(); }, function () { }) }); document.getElementById("cadesplugin_close_install").addEventListener('click', function () { plugin_loaded_error("Плагин недоступен"); document.getElementById("cadesplugin_ovr").style.visibility = 'hidden'; }); ovr.addEventListener('click', function () { plugin_loaded_error("Плагин недоступен"); document.getElementById("cadesplugin_ovr").style.visibility = 'hidden'; }); ovr.style.visibility = "visible"; document.getElementById("cadesplugin_ovr_item").addEventListener('click', function (e) { e.stopPropagation(); }); }); } else { plugin_loaded_error("Плагин недоступен"); } } function firefox_or_edge_nmcades_onload() { cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error); } function nmcades_api_onload() { window.postMessage("cadesplugin_echo_request", "*"); window.addEventListener("message", function (event) { if (typeof (event.data) != "string" || !event.data.match("cadesplugin_loaded")) return; if (isFireFox || isEdge) { // Для Firefox вместе с сообщением cadesplugin_loaded прилетает url для загрузки nmcades_plugin_api.js var url = event.data.substring(event.data.indexOf("url:") + 4); var fileref = document.createElement('script'); fileref.setAttribute("type", "text/javascript"); fileref.setAttribute("src", url); fileref.onerror = plugin_loaded_error; fileref.onload = firefox_or_edge_nmcades_onload; document.getElementsByTagName("head")[0].appendChild(fileref); // Для Firefox и Edge у нас только по одному расширению. failed_extensions++; } else { cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error); } }, false); } //Загружаем расширения для Chrome, Opera, YaBrowser, FireFox, Edge function load_extension() { if (isFireFox || isEdge) { // вызываем callback руками т.к. нам нужно узнать ID расширения. Он уникальный для браузера. nmcades_api_onload(); return; } else { // в асинхронном варианте для chrome и opera подключаем оба расширения var fileref = document.createElement('script'); fileref.setAttribute("type", "text/javascript"); fileref.setAttribute("src", "chrome-extension://iifchhfnnmpdbibifmljnfjhpififfog/nmcades_plugin_api.js"); fileref.onerror = plugin_loaded_error; fileref.onload = nmcades_api_onload; document.getElementsByTagName("head")[0].appendChild(fileref); fileref = document.createElement('script'); fileref.setAttribute("type", "text/javascript"); fileref.setAttribute("src", "chrome-extension://epebfcehmdedogndhlcacafjaacknbcm/nmcades_plugin_api.js"); fileref.onerror = plugin_loaded_error; fileref.onload = nmcades_api_onload; document.getElementsByTagName("head")[0].appendChild(fileref); } } //Загружаем плагин для NPAPI function load_npapi_plugin() { var elem = document.createElement('object'); elem.setAttribute("id", "cadesplugin_object"); elem.setAttribute("type", "application/x-cades"); elem.setAttribute("style", "visibility: hidden"); document.getElementsByTagName("body")[0].appendChild(elem); pluginObject = document.getElementById("cadesplugin_object"); if (isIE()) { var elem1 = document.createElement('object'); elem1.setAttribute("id", "certEnrollClassFactory"); elem1.setAttribute("classid", "clsid:884e2049-217d-11da-b2a4-000e7bbb2b09"); elem1.setAttribute("style", "visibility: hidden"); document.getElementsByTagName("body")[0].appendChild(elem1); var elem2 = document.createElement('object'); elem2.setAttribute("id", "webClassFactory"); elem2.setAttribute("classid", "clsid:B04C8637-10BD-484E-B0DA-B8A039F60024"); elem2.setAttribute("style", "visibility: hidden"); document.getElementsByTagName("body")[0].appendChild(elem2); } } //Отправляем событие что все ок. function plugin_loaded() { plugin_resolved = 1; if (canPromise) { plugin_resolve(); } else { window.postMessage("cadesplugin_loaded", "*"); } } //Отправляем событие что сломались. function plugin_loaded_error(msg) { if (isNativeMessageSupported()) { //в асинхронном варианте подключаем оба расширения, если сломались оба пробуем установить для Opera failed_extensions++; if (failed_extensions < 2) return; if (isOpera && (typeof (msg) == 'undefined' || typeof (msg) == 'object')) { install_opera_extension(); return; } } if (typeof (msg) == 'undefined' || typeof (msg) == 'object') msg = "Плагин недоступен"; plugin_resolved = 1; if (canPromise) { plugin_reject(msg); } else { window.postMessage("cadesplugin_load_error", "*"); } } //проверяем что у нас хоть какое то событие ушло, и если не уходило кидаем еще раз ошибку function check_load_timeout() { if (plugin_resolved == 1) return; if (isFireFox) { show_firefox_missing_extension_dialog(); } plugin_resolved = 1; if (canPromise) { plugin_reject("Истекло время ожидания загрузки плагина"); } else { window.postMessage("cadesplugin_load_error", "*"); } } //Вспомогательная функция для NPAPI function createPromise(arg) { return new Promise(arg); } function check_npapi_plugin() { try { var oAbout = CreateObject("CAdESCOM.About"); plugin_loaded(); } catch (err) { document.getElementById("cadesplugin_object").style.display = 'none'; // Объект создать не удалось, проверим, установлен ли // вообще плагин. Такая возможность есть не во всех браузерах var mimetype = navigator.mimeTypes["application/x-cades"]; if (mimetype) { var plugin = mimetype.enabledPlugin; if (plugin) { plugin_loaded_error("Плагин загружен, но не создаются обьекты"); } else { plugin_loaded_error("Ошибка при загрузке плагина"); } } else { plugin_loaded_error("Плагин недоступен"); } } } //Проверяем работает ли плагин function check_plugin_working() { var div = document.createElement("div"); div.innerHTML = ""; var isIeLessThan9 = (div.getElementsByTagName("iecheck").length == 1); if (isIeLessThan9) { plugin_loaded_error("Internet Explorer версии 8 и ниже не поддерживается"); return; } if (isNativeMessageSupported()) { load_extension(); } else if (!canPromise) { window.addEventListener("message", function (event) { if (event.data != "cadesplugin_echo_request") return; load_npapi_plugin(); check_npapi_plugin(); }, false); } else { if (document.readyState === "complete") { load_npapi_plugin(); check_npapi_plugin(); } else { window.addEventListener("load", function (event) { load_npapi_plugin(); check_npapi_plugin(); }, false); } } } function set_pluginObject(obj) { pluginObject = obj; } //Export cadesplugin.JSModuleVersion = "2.1.0"; cadesplugin.async_spawn = async_spawn; cadesplugin.set = set_pluginObject; cadesplugin.set_log_level = set_log_level; cadesplugin.getLastError = getLastError; if (isNativeMessageSupported()) { cadesplugin.CreateObjectAsync = CreateObjectAsync; cadesplugin.ReleasePluginObjects = ReleasePluginObjects; } if (!isNativeMessageSupported()) { cadesplugin.CreateObject = CreateObject; } if (window.cadesplugin_load_timeout) { setTimeout(check_load_timeout, window.cadesplugin_load_timeout); } else { setTimeout(check_load_timeout, 20000); } set_constantValues(); cadesplugin.current_log_level = cadesplugin.LOG_LEVEL_ERROR; window.cadesplugin = cadesplugin; check_plugin_working(); }()); // // FtsActions.CadesApi.js // // // FtsActions.FtsSignPluginUtils.js // // Sign Plugin Utils (function () { // Helpers window.decimalToHexString = function (number) { if (!number) return; if (number < 0) { number = 0xFFFFFFFF + number + 1; } return '(0x' + number.toString(16).toUpperCase() + ')'; } window.getErrorMessage = function (ex) { return ex ? (ex.message || ex.description || decimalToHexString(ex.number) || ex) : 'Неизвестная ошибка'; } window.extractDictionary = function (from) { var result = {}; var infoMatches = from.match(/([A-ZА-Я0-9\.]+)\=(([^",]+)|("([\s\S]*?)"))(, |$)/gi); for (var i = 0; i < infoMatches.length; i++) { var infoMatch = infoMatches[i].match(/([A-ZА-Я0-9\.]+)\=(([^",]+)|("([\s\S]*?)"))(, |$)/i); var attr = (infoMatch[1] || '').trim().toUpperCase(); var value = (infoMatch[2] || '').replace('""', '"').replace('/n', ' ').replace('/r', ' ').replace(' ', ' ').trim(); if (!result[attr]) { result[attr] = value; } else { result[attr] = result[attr] + ', ' + value; } } return result; } window.extract = function (from, what) { if (!from) return; if (!what) return; var fromDictionary = extractDictionary(from); return fromDictionary[what.trim().toUpperCase()]; } // Base64 Unicode var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", a256 = '', r64 = [256], r256 = [256], i = 0; var UTF8 = { /** * Encode multi-byte Unicode string into utf-8 multiple single-byte characters * (BMP / basic multilingual plane only) * * Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars * * @param {String} strUni Unicode string to be encoded as UTF-8 * @returns {String} encoded string */ encode: function (strUni) { // use regular expressions & String.replace callback function for better efficiency // than procedural approaches var strUtf = strUni.replace(/[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz function (c) { var cc = c.charCodeAt(0); return String.fromCharCode(0xc0 | cc >> 6, 0x80 | cc & 0x3f); }) .replace(/[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz function (c) { var cc = c.charCodeAt(0); return String.fromCharCode(0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f); }); return strUtf; }, /** * Decode utf-8 encoded string back into multi-byte Unicode characters * * @param {String} strUtf UTF-8 string to be decoded back to Unicode * @returns {String} decoded string */ decode: function (strUtf) { // note: decode 3-byte chars first as decoded 2-byte strings could appear to be 3-byte char! var strUni = strUtf.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars function (c) { // (note parentheses for precence) var cc = ((c.charCodeAt(0) & 0x0f) << 12) | ((c.charCodeAt(1) & 0x3f) << 6) | (c.charCodeAt(2) & 0x3f); return String.fromCharCode(cc); }) .replace(/[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars function (c) { // (note parentheses for precence) var cc = (c.charCodeAt(0) & 0x1f) << 6 | c.charCodeAt(1) & 0x3f; return String.fromCharCode(cc); }); return strUni; } }; while (i < 256) { var c = String.fromCharCode(i); a256 += c; r256[i] = i; r64[i] = b64.indexOf(c); ++i; } window.code = function (s, discard, alpha, beta, w1, w2) { s = String(s); var buffer = 0, i = 0, length = s.length, result = '', bitsInBuffer = 0; while (i < length) { var c = s.charCodeAt(i); c = c < 256 ? alpha[c] : -1; buffer = (buffer << w1) + c; bitsInBuffer += w1; while (bitsInBuffer >= w2) { bitsInBuffer -= w2; var tmp = buffer >> bitsInBuffer; result += beta.charAt(tmp); buffer ^= tmp << bitsInBuffer; } ++i; } if (!discard && bitsInBuffer > 0) result += beta.charAt(buffer << (w2 - bitsInBuffer)); return result; } //(function (r) { if (typeof exports === "object" && typeof module !== "undefined") { module.exports = r() } else if (typeof define === "function" && define.amd) { define([], r) } else { var e; if (typeof window !== "undefined") { e = window } else if (typeof global !== "undefined") { e = global } else if (typeof self !== "undefined") { e = self } else { e = this } e.base64js = r() } })(function () { var r, e, t; return function r(e, t, n) { function o(i, a) { if (!t[i]) { if (!e[i]) { var u = typeof require == "function" && require; if (!a && u) return u(i, !0); if (f) return f(i, !0); var d = new Error("Cannot find module '" + i + "'"); throw d.code = "MODULE_NOT_FOUND", d } var c = t[i] = { exports: {} }; e[i][0].call(c.exports, function (r) { var t = e[i][1][r]; return o(t ? t : r) }, c, c.exports, r, e, t, n) } return t[i].exports } var f = typeof require == "function" && require; for (var i = 0; i < n.length; i++) o(n[i]); return o }({ "/": [function (r, e, t) { "use strict"; t.byteLength = c; t.toByteArray = v; t.fromByteArray = s; var n = []; var o = []; var f = typeof Uint8Array !== "undefined" ? Uint8Array : Array; var i = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; for (var a = 0, u = i.length; a < u; ++a) { n[a] = i[a]; o[i.charCodeAt(a)] = a } o["-".charCodeAt(0)] = 62; o["_".charCodeAt(0)] = 63; function d(r) { var e = r.length; if (e % 4 > 0) { throw new Error("Invalid string. Length must be a multiple of 4") } return r[e - 2] === "=" ? 2 : r[e - 1] === "=" ? 1 : 0 } function c(r) { return r.length * 3 / 4 - d(r) } function v(r) { var e, t, n, i, a, u; var c = r.length; a = d(r); u = new f(c * 3 / 4 - a); n = a > 0 ? c - 4 : c; var v = 0; for (e = 0, t = 0; e < n; e += 4, t += 3) { i = o[r.charCodeAt(e)] << 18 | o[r.charCodeAt(e + 1)] << 12 | o[r.charCodeAt(e + 2)] << 6 | o[r.charCodeAt(e + 3)]; u[v++] = i >> 16 & 255; u[v++] = i >> 8 & 255; u[v++] = i & 255 } if (a === 2) { i = o[r.charCodeAt(e)] << 2 | o[r.charCodeAt(e + 1)] >> 4; u[v++] = i & 255 } else if (a === 1) { i = o[r.charCodeAt(e)] << 10 | o[r.charCodeAt(e + 1)] << 4 | o[r.charCodeAt(e + 2)] >> 2; u[v++] = i >> 8 & 255; u[v++] = i & 255 } return u } function l(r) { return n[r >> 18 & 63] + n[r >> 12 & 63] + n[r >> 6 & 63] + n[r & 63] } function h(r, e, t) { var n; var o = []; for (var f = e; f < t; f += 3) { n = (r[f] << 16) + (r[f + 1] << 8) + r[f + 2]; o.push(l(n)) } return o.join("") } function s(r) { var e; var t = r.length; var o = t % 3; var f = ""; var i = []; var a = 16383; for (var u = 0, d = t - o; u < d; u += a) { i.push(h(r, u, u + a > d ? d : u + a)) } if (o === 1) { e = r[t - 1]; f += n[e >> 2]; f += n[e << 4 & 63]; f += "==" } else if (o === 2) { e = (r[t - 2] << 8) + r[t - 1]; f += n[e >> 10]; f += n[e >> 4 & 63]; f += n[e << 2 & 63]; f += "=" } i.push(f); return i.join("") } }, {}] }, {}, [])("/") }); //window.btoa = function (plain, utf8encode) { // plain = utf8encode ? UTF8.encode(plain) : plain; // return base64js.toByteArray(plain); //} //window.atob = function (coded, utf8decode) { // coded = base64js.fromByteArray(coded); // return utf8decode ? UTF8.decode(coded) : coded; //} window.btoa = function (plain, utf8encode) { plain = utf8encode ? UTF8.encode(plain) : plain; plain = code(plain, false, r256, b64, 8, 6); return plain + '===='.slice((plain.length % 4) || 4); }; window.atob = function (coded, utf8decode) { coded = String(coded).split('='); var i = coded.length; do { --i; coded[i] = code(coded[i], true, r64, a256, 6, 8); } while (i > 0); coded = coded.join(''); return utf8decode ? UTF8.decode(coded) : coded; }; // Hex window.hexToBase64 = function (str) { return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")) ); } window.base64ToHex = function (str) { for (var i = 0, bin = atob(str.replace(/[ \r\n]+$/, "")), hex = []; i < bin.length; ++i) { var tmp = bin.charCodeAt(i).toString(16); if (tmp.length === 1) tmp = "0" + tmp; hex[hex.length] = tmp; } return hex.join(" "); } // Transform window.transform = function (data) { try { var doc; if (window.DOMParser) { var parser = new DOMParser(); doc = parser.parseFromString(data, "text/xml"); } else { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = false; doc.loadXML(data); } var transformedData = transformEl(doc.documentElement); return transformedData; } catch (e) { throw new Error('Ошибка при трансформации XML ' + (e.message || e)); } } window.transformWithSortEl = function (el, parentNamespaces) { var result = []; var attributes = []; for (var i = 0; i < el.attributes.length; i++) { var attr = el.attributes[i]; if (attr.prefix != 'xmlns' && attr.nodeName != 'xmlns') { attributes.push({ attr: attr, nodeName: attr.nodeName }); } } attributes = attributes.sort(function (a, b) { if (a.namespaceURI > b.namespaceURI) return 1; if (a.namespaceURI < b.namespaceURI) return -1; if (a.namespaceURI == b.namespaceURI) { if (a.nodeName > b.nodeName) return 1; if (a.nodeName < b.nodeName) return -1; } return 0; }); var namespaces = []; namespaces.push(el.namespaceURI); for (var i = 0; i < attributes.length; i++) { var attr = attributes[i]; if (attr.namespaceURI && namespaces.indexOf(attr.namespaceURI) == -1) { namespaces.push(attr.namespaceURI); } } namespaces = namespaces.sort(); if (!el.namespaceURI) { result.push('<' + el.nodeName); } else { result.push(''); var isText = true; for (var i = 0; i < el.childNodes.length; i++) { var ch = el.childNodes[i]; if (ch.nodeType == 1) { isText = false; } } for (var i = 0; i < el.childNodes.length; i++) { var ch = el.childNodes[i]; if (ch.nodeType == 1) { // Element result.push(transformWithSortEl(ch, namespaces)); } else if (ch.nodeType == 3 && isText) { // Text var xml = ch.nodeValue; xml = xml.replace(/\&/g, '&'); xml = xml.replace(/\/g, '>'); result.push(xml); } } if (!el.namespaceURI) { result.push(''); } else { result.push(''); } return result.join(''); } window.transformEl = function (el) { return transformWithSortEl(el); //var result = []; //result.push(' b.nodeName) return 1; // if (a.nodeName < b.nodeName) return -1; // return 0; //}); //for (var i = 0; i < sortedAttributes.length; i++) { // var attr = sortedAttributes[i].attr; // if (attr.prefix != 'xmlns' && attr.nodeName != 'xmlns') { // if (!attr.namespaceURI) { // result.push(' ' + attr.nodeName + '="' + attr.nodeValue + '"'); // } else if (attr.namespaceURI == n1El.namespaceURI) { // result.push(' n1:' + attr.nodeName + '="' + attr.nodeValue + '"'); // } else { // result.push(' xmlns:' + n++ + '="' + attr.namespaceURI + '"'); // result.push(' n' + n++ + ':' + attr.nodeName + '="' + attr.nodeValue + '"'); // } // } //} //result.push('>'); //var isText = true; //for (var i = 0; i < el.childNodes.length; i++) { // var ch = el.childNodes[i]; // if (ch.nodeType == 1) { // isText = false; // } //} //for (var i = 0; i < el.childNodes.length; i++) { // var ch = el.childNodes[i]; // if (ch.nodeType == 1) { // // Element // result.push(transformEl(ch)); // } else if (ch.nodeType == 3 && isText) { // // Text // var xml = ch.nodeValue; // xml = xml.replace(/\&/g, '&'); // xml = xml.replace(/\/g, '>'); // result.push(xml); // } //} //result.push(''); //return result.join(''); } })(); // // FtsActions.FtsSignPluginUtils.js // // // FtsActions.FtsSignPluginAsync.js // // Sign Plugin Async (function () { // Constants var CAPICOM_ENCODE_BASE64 = 0; var CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT = 0; var CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN = 1; var CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY = 2; var CADESCOM_BASE64_TO_BINARY = 1; var CADESCOM_HASH_ALGORITHM_CP_GOST_3411 = 100; var CADESCOM_CADES_BES = 1; var CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE = 2; // Setup if (window.saveDefaultCertificate == undefined) window.saveDefaultCertificate = false; // Запоминать сертификат после удачного использования if (window.showAlerts == undefined) window.showAlerts = true; if (window.alertNoSignPluginText == undefined) window.alertNoSignPluginText = 'У Вас не установлен плагин "КриптоПро ЭЦП Browser plug-in" актуальной версии.'; if (window.alertSignPluginDownloadQuestion == undefined) window.alertSignPluginDownloadQuestion = window.alertNoSignPluginText + ' Вы хотите скачать плагин для его установки?'; if (window.alertNoCspText == undefined) window.alertNoCspText = 'У Вас не установлен криптопровайдер "КриптоПро CSP" актуальной версии.'; if (window.alertCspDownloadQuestion == undefined) window.alertCspDownloadQuestion = window.alertNoCspText + ' Вы хотите скачать криптопровайдер для его установки?'; if (window.useFtsSignPlugin == undefined) window.useFtsSignPlugin = false; if (window.cspUrl == undefined) window.cspUrl = 'http://www.cryptopro.ru/products/csp/overview'; if (window.pluginUrl == undefined) window.pluginUrl = 'https://www.cryptopro.ru/products/cades/plugin/get_2_0'; // Variables window.cadesSignPlugin = null; window.cadesSignPluginVersion = null; window.cadesSignPluginCspVersion = null; window.cadesSignPluginCertificates = null; window.cadesSignPluginError = null; //window.ftsSignPlugin = null; // Default window.defaultCertificate = null; // Сертификат по умолчанию window.defaultCertificateName = window.defaultCertificateName || null; // Сертификат по умолчанию, имя window.defaultCertificateThumbprint = window.defaultCertificateThumbprint || null; // Сертификат по умолчанию, хэш // Last window.lastCertificate = null; // Последний использованный сертификат window.lastCertificateName = null; // Последний использованный сертификат, имя window.lastCertificateThumbprint = null; // Последний использованный сертификат, хэш // Log var log = function (text) { if (window.console && window.console.log) { window.console.log(text); } } var grabTop = function () { // First window.cadesSignPlugin = top.cadesSignPlugin; window.cadesSignPluginVersion = top.cadesSignPluginVersion; window.cadesSignPluginCspVersion = top.cadesSignPluginCspVersion; window.cadesSignPluginCertificates = top.cadesSignPluginCertificates; window.cadesSignPluginError = top.cadesSignPluginError; window.ftsSignPlugin = top.ftsSignPlugin; // Default window.defaultCertificate = top.defaultCertificate; window.defaultCertificateName = top.defaultCertificateName; window.defaultCertificateThumbprint = top.defaultCertificateThumbprint; // Last window.lastCertificate = top.lastCertificate; window.lastCertificateName = top.lastCertificateName; window.lastCertificateThumbprint = top.lastCertificateThumbprint; } var translateError = function (e) { var msg = e.message || e || 'Неизвестная ошибка'; if (/\(0x800B010A\)/.test(msg)) { msg = msg.replace('(0x800B010A)', '{0x800B010A}') return 'Не удается построить цепочку сертификатов до доверенного корневого центра сертификации, убедитесь что установлены все корневые и промежуточные сертификаты' + ' > ' + msg; } else if (/\(0x8009200B\)/.test(msg)) { msg = msg.replace('(0x8009200B)', '{0x8009200B}') return 'Не удается найти закрытый ключ для подписи, убедитесь что сертификат установлен правильно' + ' > ' + msg; } else if (/\(0x000004C7\)/.test(msg)) { msg = msg.replace('(0x000004C7)', '{0x000004C7}') return 'Не удается получить доступ к сертификатам либо пользователь отказался предоставить доступ' + ' > ' + msg; } else if (/\(0x8010006E\)/.test(msg)) { msg = msg.replace('(0x8010006E)', '{0x8010006E}') return 'Действие отменено пользователем' + ' > ' + msg; } else if (/Error calling method on NPObject!/.test(msg)) { msg = msg.replace('Error calling method on NPObject!', 'Не удается вызвать метод у NPObject') // Firefox return 'Не удается подписать, убедитесь что выбранный сертификат подходит для подписи' + ' > ' + msg; } else if (/сервером программирования/.test(msg) || /automation server/.test(msg)) { msg = msg.replace('сервером программирования', 'сервером программирования') msg = msg.replace('automation server', 'automation server') // IE return 'Не удается подписать, для браузера Internet Explorer адрес сайта должен быть помещен в надежные узлы (Свойства > Безопасность > Надежные узлы), установить уровень безопасности для надежных узлов средний или низкий (Свойства > Безопасность > Надежные узлы), очистить кэш браузера, переустановить плагин, перезаупстить браузер' + ' > ' + msg; } else if (/ 3221226021/.test(msg)) { msg = msg.replace('3221226021', '{3221226021}') return 'FtsSignPlugin более не поддерживается, удалите плагин FtsSignPlugin, установите актуальную версию "КриптоПро ЭЦП Browser plug-in". Ссылка для скачивания плагина: ' + pluginUrl + ' > ' + msg; } else if (/ 2148073480/.test(msg)) { msg = msg.replace('2148073480', '{2148073480}') return 'Алгоритм выбранного сертификата не поддерживается "КриптоПро CSP"' + ' > ' + msg; } else if (/ 2148073504/.test(msg)) { msg = msg.replace('2148073504', '{2148073504}') return 'Контейнер закрытого ключа не выбран' + ' > ' + msg; } else if (/ 2148532334/.test(msg)) { msg = msg.replace('2148532334', '{2148532334}') return 'Контейнер закрытого ключа не выбран' + ' > ' + msg; } else if (/ 2148081675/.test(msg)) { msg = msg.replace('2148081675', '{2148081675}') return 'FtsSignPlugin более не поддерживается, удалите плагин FtsSignPlugin, установите актуальную версию "КриптоПро ЭЦП Browser plug-in". Ссылка для скачивания плагина: ' + pluginUrl + ' > ' + msg; } else { return msg; } } var checkPlugin = function (resolve, _reject) { var reject = function (e) { if (!/0x000004C7/.test(e) && window.showAlerts) { if (window.showAlerts) { if (confirm(window.alertSignPluginDownloadQuestion)) { window.location = window.pluginUrl; } } } _reject(e); } if (window.cadesSignPluginCertificates) { resolve(); } else if (window.cadesSignPluginError) { reject(window.cadesSignPluginError); } else { // Recognize var recognizeSuccess = function () { log('Плагин для подписи определен успешно'); resolve(); } var recognizeError = function (e) { window.cadesplugin = undefined; window.cadesSignPluginCertificates = undefined; window.cadesSignPluginError = translateError(e); log('Ошибка определения плагина для подписи: ' + window.cadesSignPluginError); reject(window.cadesSignPluginError); } var recognize = function () { try { if (window.cadesplugin.CreateObjectAsync) { log('Найден асинхронный плагин для подписи'); window.cadesSignPlugin = window.cadesplugin; cadesCheckPluginAsync(recognizeSuccess, recognizeError); } else if (window.cadesplugin.CreateObject) { log('Найден синхронный плагин для подписи'); window.cadesSignPlugin = window.cadesplugin; cadesCheckPluginSync(recognizeSuccess, recognizeError); } else { throw 'Плагин для подписи не найден'; } } catch (e) { recognizeError(e); } } // First load cades sign plugin if (window.cadesplugin && window.cadesplugin.then && !window.cadesSignPlugin) { log('Ожидание загрузки асинхронного плагина для подписи'); window.cadesplugin.then(function () { log('Плагин для подписи загружен'); recognize(); }, function (e) { recognizeError(e); }); } else if (window.cadesplugin && !window.cadesSignPlugin) { log('Ожидание загрузки синхронного плагина для подписи'); recognize(); } //// First load fts sign plugin //if (useFtsSignPlugin) { // var loadFtsSignPluginTimeout = 100; // var loadFtsSignPlugin = function () { // if (!window.ftsSignPlugin && ((!window.cadesplugin && !window.cadesSignPlugin) || (window.cadesSignPlugin && window.cadesSignPluginError))) { // // Fts Sign Plugin // var signPluginSpan = document.createElement("div"); // signPluginSpan.setAttribute('style', 'height: 0px;') // signPluginSpan.innerHTML = ''; // document.body.appendChild(signPluginSpan); // window.ftsSignPlugin = signPluginSpan.firstChild; // log('Plugin FtsSignPlugin Loaded') // } else { // log('Plugin FtsSignPlugin Waiting...') // setTimeout(loadFtsSignPlugin, loadFtsSignPluginTimeout *= 2); // } // } // loadFtsSignPlugin(); //} } } var cadesCheckPluginAsync = function (resolve, reject) { try { window.cadesSignPlugin.CreateObjectAsync("CAdESCOM.About")["catch"](function (e) { reject('Ошибка создания CAdESCOM.Abouts: ' + (e.message || e)); }).then(function (cadesAbout) { cadesAbout.Version["catch"](function (e) { reject('Ошибка вызова cadesAbout.Version: ' + (e.message || e)); }).then(function (pluginVersion) { window.cadesSignPluginVersion = pluginVersion; // CSPVersion try { var cpProviderName = "Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider"; var cpProviderType = 75; cadesAbout.CSPVersion(cpProviderName, parseInt(cpProviderType, 10))["catch"](function (e) { reject('Ошибка вызова cadesAbout.CSPVersion: ' + (e.message || e)); }).then(function (cspVersionObj) { cspVersionObj.toString()["catch"](function (e) { reject('Ошибка вызова cspVersionObj.Version: ' + (e.message || e)); }).then(function (cspVersion) { window.cadesSignPluginCspVersion = cspVersion; }); }); } catch (e) { //throw new Error(window.alertNoSignPluginText + '. Ошика: Невозможно получить версию криптопровайдера, undefined cadesAbout.CSPVersion'); } // Store window.cadesSignPlugin.CreateObjectAsync("CAdESCOM.Store")["catch"](function (e) { reject('Ошибка создания CAdESCOM.Store: ' + (e.message || e)); }).then(function (cadesStore) { cadesStore.Open()["catch"](function (e) { reject('Ошибка вызова cadesStore.Open: ' + (e.message || e)); }).then(function () { cadesStore.Certificates["catch"](function (e) { reject('Ошибка вызова cadesStore.Certificates: ' + (e.message || e)); }).then(function (certificates) { certificates.Count["catch"](function (e) { reject('Ошибка вызова certificates.Count: ' + (e.message || e)); }).then(function (certificatesCount) { window.cadesSignPluginCertificates = []; for (var i = 1; i <= certificatesCount; i++) { certificates.Item(i)["catch"](function (e) { reject('Ошибка вызова certificates.Item: ' + (e.message || e)); }).then(function (certificateObj) { var current = { certificateObj: certificateObj }; try { certificateObj.ValidFromDate["catch"](function (e) { current.Error = 'Ошибка вызова certificateObj.ValidFromDate: ' + (e.message || e); }).then(function (certificateValidFromDate) { current.ValidFromDate = certificateValidFromDate; }); certificateObj.ValidToDate["catch"](function (e) { current.Error = 'Ошибка вызова certificateObj.ValidToDate: ' + (e.message || e); }).then(function (certificateValidToDate) { current.ValidToDate = certificateValidToDate; }); certificateObj.HasPrivateKey()["catch"](function (e) { current.Error = 'Ошибка вызова certificateObj.HasPrivateKey: ' + (e.message || e); }).then(function (certificateHasPrivateKey) { current.HasPrivateKey = certificateHasPrivateKey; }); //setTimeout(function () { // certificateObj.IsValid()["catch"](function (e) { // current.IsValid = false; // }).then(function (certificateIsValid) { // if (certificateIsValid && certificateIsValid.Result) { // certificateIsValid.Result["catch"](function (e) { current.Error = 'Ошибка вызова certificateIsValid.Result: ' + (e.message || e); }).then(function (certificateIsValidResult) { // current.IsValid = certificateIsValidResult == 1; // }); // } else { // current.IsValid = false; // } // }); //}, 100); certificateObj.SubjectName["catch"](function (e) { current.Error = 'Ошибка вызова certificateObj.SubjectName: ' + (e.message || e); }).then(function (certificateSubjectName) { current.SubjectName = certificateSubjectName; current.SubjectCN = extract(current.SubjectName, 'CN'); current.SubjectO = extract(current.SubjectName, 'O'); current.SubjectSN = extract(current.SubjectName, 'SN'); current.SubjectG = extract(current.SubjectName, 'G'); current.SubjectT = extract(current.SubjectName, 'T'); }); certificateObj.IssuerName["catch"](function (e) { current.Error = 'Ошибка вызова certificateObj.IssuerName: ' + (e.message || e); }).then(function (certificateIssuerName) { current.IssuerName = certificateIssuerName; current.IssuerCN = extract(current.IssuerName, 'CN'); current.IssuerO = extract(current.IssuerName, 'O'); }); certificateObj.Thumbprint["catch"](function (e) { current.Error = 'Ошибка вызова certificateObj.Thumbprint: ' + (e.message || e); }).then(function (certificateThumbprint) { current.Thumbprint = certificateThumbprint; }); certificateObj.Export(CAPICOM_ENCODE_BASE64)["catch"](function (e) { current.Error = 'Ошибка вызова certificateObj.Export: ' + (e.message || e); }).then(function (certificateBase64) { current.Base64 = certificateBase64; }); certificateObj.PublicKey()["catch"](function (e) { current.Error = 'Ошибка вызова certificateObj.PublicKey: ' + (e.message || e); }).then(function (certificatePublicKey) { current.PublicKey = certificatePublicKey; certificatePublicKey.Algorithm["catch"](function (e) { current.Error = 'Ошибка вызова certificatePublicKey.Algorithm: ' + (e.message || e); }).then(function (certificatePublicKeyAlgorithm) { current.PublicKeyAlgorithm = certificatePublicKeyAlgorithm; certificatePublicKeyAlgorithm.Value["catch"](function (e) { current.Error = 'Ошибка вызова certificatePublicKeyAlgorithm.Value: ' + (e.message || e); }).then(function (certificatePublicKeyAlgorithmValue) { current.PublicKeyAlgorithmValue = certificatePublicKeyAlgorithmValue; }); certificatePublicKeyAlgorithm.FriendlyName["catch"](function (e) { current.Error = 'Ошибка вызова certificatePublicKeyAlgorithm.FriendlyName: ' + (e.message || e); }).then(function (certificatePublicKeyAlgorithmFriendlyName) { current.PublicKeyAlgorithmFriendlyName = certificatePublicKeyAlgorithmFriendlyName; }); }); }); } catch (e) { current.Error = e.message || e; } window.cadesSignPluginCertificates.push(current); }); } var checkFullLoadTimeout1 = setTimeout(function () { clearTimeout(checkFullLoadTimeout2); if (window.cadesSignPluginCertificates.length == certificatesCount) { resolve(); } else { reject('Превышен таймаут загрузки сертификатов'); } }, 30000); var checkFullLoad = function () { var isFullLoad = window.cadesSignPluginCertificates.length == certificatesCount; if (isFullLoad) { for (var i = 0; i < window.cadesSignPluginCertificates.length; i++) { var certificate = window.cadesSignPluginCertificates[i]; if (certificate.ValidFromDate === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.ValidToDate === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.HasPrivateKey === undefined && certificate.Error === undefined) isFullLoad = false; //if (certificate.IsValid === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.SubjectName === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.IssuerName === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.Thumbprint === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.Base64 === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.PublicKey === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.PublicKeyAlgorithm === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.PublicKeyAlgorithmValue === undefined && certificate.Error === undefined) isFullLoad = false; if (certificate.PublicKeyAlgorithmFriendlyName === undefined && certificate.Error === undefined) isFullLoad = false; } } if (isFullLoad) { clearTimeout(checkFullLoadTimeout1); resolve(); } else { checkFullLoadTimeout2 = setTimeout(checkFullLoad, 100); } } var checkFullLoadTimeout2 = setTimeout(checkFullLoad, 100); }); }); }); }); }); }); } catch (e) { reject(e); } } var cadesCheckPluginSync = function (resolve, reject) { try { var cadesAbout = window.cadesSignPlugin.CreateObject("CAdESCOM.About"); window.cadesSignPluginVersion = cadesAbout.Version; // CSPVersion try { var cpProviderName = "Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider"; var cpProviderType = 75; var cspVersionObj = cadesAbout.CSPVersion(cpProviderName, parseInt(cpProviderType, 10)); window.cadesSignPluginCspVersion = cspVersionObj.toString(); } catch (e) { //throw new Error(window.alertNoSignPluginText + '. Ошика: Невозможно получить версию криптопровайдера, undefined cadesAbout.CSPVersion'); } // Store var cadesStore = window.cadesSignPlugin.CreateObject("CAdESCOM.Store"); cadesStore.Open(); var certificates = cadesStore.Certificates; var certificatesCount = certificates.Count; window.cadesSignPluginCertificates = []; for (var i = 1; i <= certificatesCount; i++) { var certificateObj = certificates.Item(i); var current = { certificateObj: certificateObj }; try { current.ValidFromDate = certificateObj.ValidFromDate; current.ValidToDate = certificateObj.ValidToDate; current.HasPrivateKey = certificateObj.HasPrivateKey(); //setTimeout(function () { // try { // current.IsValid = certificateObj.IsValid() && certificateObj.IsValid().Result; // } catch (e) { // current.IsValid = false; // } //}, 100); current.SubjectName = certificateObj.SubjectName; current.SubjectCN = extract(current.SubjectName, 'CN'); current.SubjectO = extract(current.SubjectName, 'O'); current.SubjectSN = extract(current.SubjectName, 'SN'); current.SubjectG = extract(current.SubjectName, 'G'); current.SubjectT = extract(current.SubjectName, 'T'); current.IssuerName = certificateObj.IssuerName; current.IssuerCN = extract(current.IssuerName, 'CN'); current.IssuerO = extract(current.IssuerName, 'O'); current.Thumbprint = certificateObj.Thumbprint; current.Base64 = certificateObj.Export(CAPICOM_ENCODE_BASE64); current.PublicKeyAlgorithmFriendlyName = certificateObj.PublicKey().Algorithm.FriendlyName; } catch (e) { current.Error = e.message || e; } window.cadesSignPluginCertificates.push(current); } resolve(); } catch (e) { reject(e); } } var isCertificateUsable = function (certificate) { return certificate.HasPrivateKey && new Date(certificate.ValidFromDate) < new Date() && new Date(certificate.ValidToDate) > new Date(); } var getCertificateInfo = function (certificate) { var text = []; var issuerName = (certificate.IssuerO || certificate.IssuerCN || '').trim(); var organizationName = (certificate.SubjectO || certificate.SubjectCN || '').trim(); var userName = ((certificate.SubjectSN || '') + ' ' + (certificate.SubjectG || '')).trim(); if (!userName && certificate.SubjectO) userName = certificate.SubjectCN; var userPost = (certificate.SubjectT || '').trim(); text.push(userName + (organizationName ? (userName ? ' - ' : '') + userPost + ' ' + organizationName : '')); text.push('Выдан: ' + issuerName); text.push('Действует с ' + (new Date(certificate.ValidFromDate)).toLocaleDateString() + ' по ' + (new Date(certificate.ValidToDate)).toLocaleDateString()); //text.push('Алгоритм ключа: ' + certificate.PublicKeyAlgorithmFriendlyName); if (!certificate.HasPrivateKey) { text.push('Закрытый ключ отсутствует'); } if (new Date(certificate.ValidFromDate) > new Date()) { text.push('Срок действия сертификата ещё не начался'); } if (new Date(certificate.ValidToDate) < new Date()) { text.push('Срок действия сертификата истек'); } if (certificate.Error) { text.push('Ошибка получения свойств сертификата: ' + certificate.Error); } return text.join('\n'); } window.getLastCertificate = function () { try { if (top && top.getLastCertificate && top != window) { return top.getLastCertificate(); } } catch (e) { // Top pop suck puck } if (window.lastCertificate) { return window.lastCertificate; } else if (window.lastCertificateName || window.lastCertificateThumbprint) { return { SubjectCN: window.lastCertificateName, Thumbprint: window.lastCertificateThumbprint }; } } window.getDefaultCertificate = function () { try { if (top && top.getDefaultCertificate && top != window) { return top.getDefaultCertificate(); } } catch (e) { // Top pop suck puck } if (window.defaultCertificate) { return window.defaultCertificate; } else if (window.defaultCertificateName || window.defaultCertificateThumbprint) { return { SubjectCN: window.defaultCertificateName, Thumbprint: window.defaultCertificateThumbprint }; } } window.getCertificate = window.getCertificate || function (_resolve, reject) { try { if (top && top.getCertificate && top != window) { return top.getCertificate(_resolve, reject); } } catch (e) { // Top pop suck puck } var resolve = function (certificate) { window.lastCertificate = certificate; window.lastCertificateName = certificate.SubjectCN; window.lastCertificateThumbprint = certificate.Thumbprint; _resolve(certificate); } checkPlugin(function () { var defaultCertificates = []; for (var i = 0; i < window.cadesSignPluginCertificates.length; i++) { var current = window.cadesSignPluginCertificates[i]; if (window.defaultCertificateThumbprint) { if (window.defaultCertificateThumbprint == current.Thumbprint) { defaultCertificates.push(current); } } else if (window.defaultCertificateName) { if (window.defaultCertificateName && window.defaultCertificateName == current.SubjectCN) { defaultCertificates.push(current); } } } if (defaultCertificates.length == 1) { window.defaultCertificate = defaultCertificates[0]; } if (window.defaultCertificate) { resolve(window.defaultCertificate); } else if (!window.cadesSignPluginCertificates) { reject('Нет доступа к сертификатам'); } else if (window.cadesSignPluginCertificates.length == 0) { reject('Сертификаты отсутствуют'); } else if (window.cadesSignPluginCertificates.length == 1) { resolve(window.cadesSignPluginCertificates[0]); } else { choiseCertificate(resolve, reject); } }, reject); } window.choiseCertificate = window.choiseCertificate || function (resolve, reject) { try { if (top && top.choiseCertificate && top != window) { return top.choiseCertificate(resolve, reject); } } catch (e) { // Top pop suck puck } checkPlugin(function () { if (window.Ext) { window.choiseCertificateExt(resolve, reject); } else if (typeof $.fn.modal == 'function') { window.choiseCertificateBootstrap(resolve, reject); } else { window.choiseCertificateJs(resolve, reject); } }, reject); } window.getGostCertificates = function () { //if (!window.cadesSignPluginCertificatesGost) { window.cadesSignPluginCertificatesGost = []; for (var i = 0; i < window.cadesSignPluginCertificates.length; i++) { var certificate = window.cadesSignPluginCertificates[i]; if (/ГОСТ/.test(certificate.PublicKeyAlgorithmFriendlyName) || certificate.PublicKeyAlgorithmValue == "1.2.643.2.2.19") { window.cadesSignPluginCertificatesGost.push(certificate); } } if (window.cadesSignPluginCertificatesGost.length == 0) return window.cadesSignPluginCertificates; //} return window.cadesSignPluginCertificatesGost; } window.choiseCertificateExt = window.choiseCertificateExt || function (resolve, reject) { var rg = { xtype: 'radiogroup', columns: 1, vertical: true, items: [] }; var rejectOnClose = true; var gostCertificates = window.getGostCertificates(); for (var i = 0; i < gostCertificates.length; i++) { var certificate = gostCertificates[i]; rg.items.push({ xtype: 'radio', style: 'color: ' + (isCertificateUsable(certificate) ? 'green' : 'red'), boxLabel: (i + 1) + '. ' + getCertificateInfo(certificate).replace(/\n/g, '
        '), inputValue: certificate.Thumbprint, certificate: certificate, listeners: { change: { fn: function (field) { rejectOnClose = false; win.hide(); resolve(field.certificate); } } } }); } var win = new Ext.Window({ title: 'Выберите сертификат', width: Ext.getBody().getViewSize().width / 3 * 2, height: Ext.getBody().getViewSize().height / 3 * 2, autoScroll: false, layout: 'fit', maximizable: true, closable: true, modal: true, bodyStyle: 'background-color: white; padding: 10px;', items: [new Ext.Container({ autoScroll: true, items: [{ xtype: 'container', html: 'Выберите сертификат для подписи', style: 'margin-bottom: 10px;' }, rg] })], listeners: { beforeclose: { fn: function () { if (rejectOnClose) setTimeout(function () { reject('Сертификат не выбран'); }, 100); } } } }); window.actionWindow = win; if (window.hideMask) window.hideMask(); win.show(); } window.choiseCertificateBootstrap = window.choiseCertificateBootstrap || function (resolve, reject) { var btsrpModal = $('