Compare commits

..

No commits in common. "master" and "v2.0.5" have entirely different histories.

185 changed files with 44835 additions and 33226 deletions

View File

@ -1,46 +0,0 @@
name: CryptoPRO tests
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
buildAndTest:
runs-on: ubuntu-20.04
strategy:
matrix:
node-version: [ 16 ]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
check-latest: true
- name: Clean install, build, test
run: |
npm ci
npm run build --if-present --openssl-legacy-provider
npm test
lint:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3
- name: Use Node.js 16
uses: actions/setup-node@v3
with:
node-version: 16
check-latest: true
- name: Clean install, lint
run: |
npm ci
npm run lint

3
.travis.yml Normal file
View File

@ -0,0 +1,3 @@
language: node_js
node_js:
- lts/*

98
CHANGELOG.md Normal file
View File

@ -0,0 +1,98 @@
2.0.5 / 2020-07-04
==================
* Улучшение: Дополнены словари для расшифровки данных о сертификате
2.0.4 / 2020-04-05
==================
* Улучшение: Исправлены ссылки в README.md
* Улучшение: Добавлен файл с лицензией
* Улучшение: Обновлены версии пакета в примерах
2.0.3 / 2020-03-29
==================
* Улучшение: Дополнен README.md
2.0.2 / 2020-03-29
==================
* Фикс: Исправлены ссылки в README.md с учетом разницы форматов Markdown между Github и NPM
2.0.1 / 2020-03-28
==================
* Фикс: Ссылки на якоря в README.md с учетом особенностей Markdown на Github
2.0.0 / 2020-03-28
==================
* Улучшение: Проект переписан с использованием Typescript
* Улучшение: В Readme обновлены примеры, документация и добавлен [список изменений](README.md#Миграция-с-версии-1-на-2) для миграции с 1 на 2 версию
1.1.2 / 2019-12-07
==================
* Фикс: Дополнена [обработка ошибок](https://github.com/vgoma/crypto-pro/issues/8)
1.1.1 / 2019-12-05
==================
* Улучшение: Добавлены изменения из оригинального js модуля Крипто ПРО "2.1.2" [ссылка на оригинальный файл](https://www.cryptopro.ru/sites/default/files/products/cades/cadesplugin_api.js)
1.1.0 / 2017-12-20
==================
* Улучшение: объединена кодовая база по работе с синхронной и асинхронной версии API Крипто ПРО
1.0.11 / 2017-06-08
==================
* Улучшение: Убрана зависимость от Object.keys и Object.assign
1.0.10 / 2017-04-26
==================
* Фикс: уточнения в README
1.0.9 / 2017-04-26
==================
* Фикс: оформление README
1.0.8 / 2017-04-26
==================
* Улучшение: Добавлена поддержка Firefox >= 52
* Улучшение: Более подробный README
1.0.7 / 2017-01-30
==================
* Улучшение: Указание отпечатка сертификата при ошибке доступа к нему
1.0.6 / 2017-01-30
==================
* Фикс: Проброс ошибки метода получения сертификатов по цепочке промисов
1.0.5 / 2017-01-24
==================
* Улучшение: Фиксация версий всех зависимостей
1.0.4 / 2017-01-20
==================
* Улучшение: Добавлены изменения из оригинального js модуля Крипто ПРО "2.0.3" [ссылка на оригинальный файл](https://www.cryptopro.ru/sites/default/files/products/cades/cadesplugin_api.js)
1.0.3 / 2017-01-20
==================
* Улучшение: Убрана попытка загрузки сразу двух расширений (для Opera и для Chrome)
1.0.2 / 2017-01-16
==================
* Улучшение: Добавлена возможность подключать модуль напрямую из папки src/ для приложений, собираемых webpack'ом

View File

@ -1,7 +1,6 @@
MIT License MIT License
Copyright (c) 2020 Vitalii Goma Copyright (c) 2020 Vitalii Goma
Copyright (c) 2021 Artem Vasilev
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

337
README.md
View File

@ -1,24 +1,17 @@
[![License][license-image]][license-url]
[![NPM version][npm-version-image]][npm-url] [![NPM version][npm-version-image]][npm-url]
[![NPM downloads][npm-downloads-image]][downloads-url] [![NPM downloads][npm-downloads-image]][downloads-url]
[![Build Status][actions-image]][actions-url] [![Build Status][travis-image]][travis-url]
[![Coverage Status][coveralls-image]][coveralls-url]
[![Donate][donate-image]][donate-url]
<a name="cryptopro"></a> <a name="cryptopro"></a>
# cryptoPro # cryptoPro
Асинхронный JavaScript API для работы с КриптоПРО ЭЦП Browser Plug-In Единое, асинхронное API для взаимодействия с КриптоПРО ЭЦП Browser Plug-In
> **Это форк проекта [vgoma/crypto-pro](https://github.com/vgoma/crypto-pro)**
>
> **API форка отличается от оригинала**: внимательно читайте README
| [![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/62.2.25/src/chrome/chrome_64x64.png)](https://www.chromium.org/getting-involved/download-chromium#TOC-Downloading-old-builds-of-Chrome-Chromium) | [![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/62.2.25/src/firefox/firefox_64x64.png)](https://ftp.mozilla.org/pub/firefox/releases/) | [![IE](https://raw.githubusercontent.com/alrra/browser-logos/62.2.25/src/archive/internet-explorer_9-11/internet-explorer_9-11_64x64.png)](https://www.microsoft.com/ru-ru/download/details.aspx?id=43374) | [![Opera](https://raw.githubusercontent.com/alrra/browser-logos/62.2.25/src/opera/opera_64x64.png)](http://get.opera.com/ftp/pub/opera/desktop/) | | [![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/62.2.25/src/chrome/chrome_64x64.png)](https://www.chromium.org/getting-involved/download-chromium#TOC-Downloading-old-builds-of-Chrome-Chromium) | [![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/62.2.25/src/firefox/firefox_64x64.png)](https://ftp.mozilla.org/pub/firefox/releases/) | [![IE](https://raw.githubusercontent.com/alrra/browser-logos/62.2.25/src/archive/internet-explorer_9-11/internet-explorer_9-11_64x64.png)](https://www.microsoft.com/ru-ru/download/details.aspx?id=43374) | [![Opera](https://raw.githubusercontent.com/alrra/browser-logos/62.2.25/src/opera/opera_64x64.png)](http://get.opera.com/ftp/pub/opera/desktop/) |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| __v45+__ с расширением [CryptoPro Extension for CAdES Browser Plug-in](https://chrome.google.com/webstore/detail/cryptopro-extension-for-c/iifchhfnnmpdbibifmljnfjhpififfog?utm_source=chrome-app-launcher-info-dialog) | __v43+__. Начиная с версии 52, с [расширением](https://www.cryptopro.ru/sites/default/files/products/cades/extensions/cryptopro_extension_for_cades_browser_plug_in-1.1.1-an+fx-windows.xpi) | __v9+__ с установленным [КриптоПро ЭЦП Browser plug-in](https://www.cryptopro.ru/products/cades/plugin) | __v40+__ с расширением [CryptoPro Extension for CAdES Browser Plug-in](https://addons.opera.com/en/extensions/details/cryptopro-extension-for-cades-browser-plug-in/) | | __v45+__ с расширением [CryptoPro Extension for CAdES Browser Plug-in](https://chrome.google.com/webstore/detail/cryptopro-extension-for-c/iifchhfnnmpdbibifmljnfjhpififfog?utm_source=chrome-app-launcher-info-dialog) | __v43+__. Начиная с версии 52, с [расширением](https://www.cryptopro.ru/sites/default/files/products/cades/extensions/cryptopro_extension_for_cades_browser_plug_in-1.1.1-an+fx-windows.xpi) | __v9+__ с установленным [КриптоПро ЭЦП Browser plug-in](https://www.cryptopro.ru/products/cades/plugin) | __v40+__ с расширением [CryptoPro Extension for CAdES Browser Plug-in](https://addons.opera.com/en/extensions/details/cryptopro-extension-for-cades-browser-plug-in/) |
## Ошибка `Параметр задан неверно. (0x80070057)`
Если при попытке подписать сообщение с использованием PKCS#7 подписи падает такая ошибка, то читайте [этот issue](https://github.com/webmasterskaya/crypto-pro-js/issues/20)
- [cryptoPro](#cryptopro) - [cryptoPro](#cryptopro)
- [Зачем мне этот пакет?](#why) - [Зачем мне этот пакет?](#why)
- [Установка](#install) - [Установка](#install)
@ -28,10 +21,19 @@
- [Поддерживаемые СКЗИ](#supported-cist) - [Поддерживаемые СКЗИ](#supported-cist)
- [Примеры](#examples) - [Примеры](#examples)
- [Тэг script (UMD)](#example-script-tag) - [Тэг script (UMD)](#example-script-tag)
- [Angular (ES Modules + Typescript)](#example-angular)
- [React (ES Modules + JavaScript)](#example-react)
- [Миграция с версии 1 на 2](#upgrade-from-1-to-2)
- [Тем, кто хочет помочь](#developers) - [Тем, кто хочет помочь](#developers)
- [Запуск режима разработки](#dev-mode) - [Запуск режима разработки](#dev-mode)
- [Запуск тестов](#tests-execution) - [Запуск тестов](#tests-execution)
- [Проверка работы примеров с React и Angular](#examples-testing)
- [Проверка пакета перед публикацией в NPM](#final-check) - [Проверка пакета перед публикацией в NPM](#final-check)
- [Полезная информация](#helpful)
- [Установка КриптоПРО CSP в Linux / OSX](#csp-install-linux-osx)
- [Установка КриптоПРО ЭЦП browser plug-in в Linux](#plugin-install-linux)
- [Настройка плагина для Firefox (до версии 52)](#plugin-install-old-firefox)
- [Установка сертификатов в Linux](#certificates-install-linux)
- [Лицензия](#lisense) - [Лицензия](#lisense)
<a name="why"></a> <a name="why"></a>
@ -39,27 +41,36 @@
КриптоПРО ЭЦП Browser Plug-In доступен в разных браузерах в двух версиях. КриптоПРО ЭЦП Browser Plug-In доступен в разных браузерах в двух версиях.
Асинхронной (в современных браузерах) и синхронной (в браузерах постарше). Асинхронной (в современных браузерах) и синхронной (в браузерах постарше).
С помощью этого пакета можно не писать реализацию под каждую версию плагина дважды. С помощью этого пакета можно не писать реализацию под каждую версию плагина дважды.
И вместо [этого](http://cpdn.cryptopro.ru/content/cades/plugin-samples-sign.html)
и [этого](http://cpdn.cryptopro.ru/content/cades/plugin-samples-sign-cades-bes-async.html)
написать это (UMD):
![crypto-pro-umd.gif](crypto-pro-umd.gif)
или это (ES Modules):
![crypto-pro-esm.gif](crypto-pro-esm.gif)
<a name="install"></a> <a name="install"></a>
## Установка ## Установка
Для NPM: Для NPM:
```bash ```bash
npm install crypto-pro-js npm install crypto-pro
``` ```
Для Yarn: Для Yarn:
```bash ```bash
yarn add crypto-pro-js yarn add crypto-pro
``` ```
Для Bower: Для Bower:
```bash ```bash
bower install webmasterskaya/crypto-pro-js bower install crypto-pro
``` ```
Подключение пакета как UMD модуля через тэг script: Подключение пакета как UMD модуля через тэг script:
```html ```html
<script src="crypto-pro-js/dist/crypto-pro.min.js"></script> <script src="crypto-pro/dist/crypto-pro.min.js"></script>
<script> <script>
window.cryptoPro.getUserCertificates() window.cryptoPro.getUserCertificates()
.then(function (certificates) { .then(function (certificates) {
@ -73,7 +84,7 @@ window.cryptoPro.getUserCertificates()
Подключение пакета как ES модуля с Typescript или JavaScript: Подключение пакета как ES модуля с Typescript или JavaScript:
```typescript ```typescript
import { getUserCertificates, Certificate } from 'crypto-pro-js'; import { getUserCertificates, Certificate } from 'crypto-pro';
(async () => { (async () => {
let certificates: Certificate[]; let certificates: Certificate[];
@ -96,21 +107,11 @@ import { getUserCertificates, Certificate } from 'crypto-pro-js';
<a name="api-cryptopro"></a> <a name="api-cryptopro"></a>
### Методы объекта cryptoPro ### Методы объекта cryptoPro
- [getUserCertificates](src/api/getUserCertificates.ts) - возвращает список [сертификатов](#api-certificate), доступных пользователю в системе - [getUserCertificates](src/api/getUserCertificates.ts) - возвращает список [сертификатов](#api-certificate), доступных пользователю в системе
- [getAllUserCertificates](src/api/getAllUserCertificates.ts) - возвращает список [сертификатов](#api-certificate), доступных пользователю в системе, в том числе просроченные и без закрытого ключа
- [getContainerCertificates](src/api/getContainerCertificates.ts) - возвращает список [сертификатов](#api-certificate), из закрытых ключей и/или сертификаты не установленные всистеме*
- [getAllContainerCertificates](src/api/getAllContainerCertificates.ts) - возвращает список [сертификатов](#api-certificate), из закрытых ключей и/или сертификаты не установленные всистеме*, в том числе просроченные и без закрытого ключа
- [getCertificate](src/api/getCertificate.ts) - возвращает [сертификат](#api-certificate) по отпечатку - [getCertificate](src/api/getCertificate.ts) - возвращает [сертификат](#api-certificate) по отпечатку
- [createAttachedSignature](src/api/createAttachedSignature.ts) - создает совмещенную (присоединенную) подпись сообщения - [createSignature](src/api/createSignature.ts) - создает подпись данных
- [createDetachedSignature](src/api/createDetachedSignature.ts) - создает отсоединенную (открепленную) подпись сообщения
- [addAttachedSignature](src/api/addAttachedSignature.ts) - добавляет совмещенную (присоединенную) подпись к раннее подписанному документу (реализует метод coSign)
- [addDetachedSignature](src/api/addDetachedSignature.ts) - добавляет отсоединенную (открепленную) подпись к раннее подписанному документу (реализует метод coSign)
- [createXMLSignature](src/api/createXMLSignature.ts) - создает XML подпись для документа в формате XML
- [createHash](src/api/createHash.ts) - создает хеш сообщения по ГОСТ Р 34.11-2012 256 бит
- [getSystemInfo](src/api/getSystemInfo.ts) - возвращает информацию о CSP и плагине - [getSystemInfo](src/api/getSystemInfo.ts) - возвращает информацию о CSP и плагине
- [isValidSystemSetup](src/api/isValidSystemSetup.ts) - возвращает флаг корректности настроек ЭП на машине - [isValidSystemSetup](src/api/isValidSystemSetup.ts) - возвращает флаг корректности настроек ЭП на машине
> *Методы `getContainerCertificates` и `getAllContainerCertificates` позволяют получить сертификаты из закрытых ключей, записанных на обыкновенную флэшку
<a name="api-certificate"></a> <a name="api-certificate"></a>
### Методы объекта сертификата ### Методы объекта сертификата
[Сертификат](src/api/certificate/certificate.ts) предоставляет следущее API: [Сертификат](src/api/certificate/certificate.ts) предоставляет следущее API:
@ -126,7 +127,15 @@ import { getUserCertificates, Certificate } from 'crypto-pro-js';
<a name="supported-cist"></a> <a name="supported-cist"></a>
## Поддерживаемые СКЗИ ## Поддерживаемые СКЗИ
[КриптоПРО CSP](https://www.cryptopro.ru/products/csp/downloads) (v4.0+) [КриптоПРО CSP](https://www.cryptopro.ru/products/csp/downloads) (v4.0+) *рекомендуется использование только сертифицированных версий*. Инструкция по установке:
- [Linux / OSX](#csp-install-linux-osx)
- (в Windows следуйте указаниям программы-установщика)
[КриптоПРО ЭЦП browser plug-in](https://www.cryptopro.ru/products/cades/plugin) (v2.0.12438+).
[Инструкция](#plugin-install-linux) по установке плагина в Linux. В Windows и OSX следуйте указаниям программы-установщика.
[Инструкция](#certificates-install-linux) по установке сертификатов в систему для Linux / OSX.
<a name="examples"></a> <a name="examples"></a>
## Примеры ## Примеры
@ -140,6 +149,87 @@ npm i
npm start npm start
``` ```
<a name="example-angular"></a>
### Angular (ES Modules + Typescript)
```bash
cd examples/angular
npm i
```
Запуск в режиме разработки:
```bash
npm start
```
Запуск в продакшн режиме:
```bash
npm run build
npm run serve
```
<a name="example-react"></a>
### React (ES Modules + JavaScript)
```bash
cd examples/react
npm i
```
Запуск в режиме разработки:
```bash
npm start
```
Запуск в продакшн режиме:
```bash
npm run build
npm run serve
```
<a name="upgrade-from-1-to-2"></a>
## Миграция с версии 1 на 2
Внесены следующие изменения:
- Пакет собран в форматах:
- UMD, в папке `dist/`, для подключения через тэг script. Объект `window.cryptoPro` доступен глобально.
- ES Modules, в папке `lib/`, для использования с разными системами сборки.
Методы API импортируются напрямую из npm пакета.
- В UMD версии переименован глобальный объект с `window.CryptoPro` на `window.cryptoPro`
- Переименованы общие методы:
- `getCertsList` -> `getUserCertificates`
- `getCert` -> `getCertificate`
- `signData` -> `createSignature`
- `isValidEDSSettings`, `isValidCSPVersion`, `isValidCadesVersion` -> `isValidSystemSetup`
- Убран метод `signDataXML`
- Переименованы методы сертификата:
- `getProp` -> `getCadesProp`
- Результат методов сертификата `getOwnerInfo` и `getIssuerInfo`
изменился с `{ descr, title, translated }` на `{ description, title, isTranslated }`
- Принципиальная реализация методов, обращающихся к Крипто ПРО не изменилась.
Получение сертификатов, создание подписи, проверка корректности настроек работают по-прежнему.
- Убрана поддержка IE8 (Крипто ПРО его больше не поддерживает)
- Убрана поддержка КриптоПРО CSP версий ниже 4.0
- Убрана поддержка КриптоПРО ЭЦП browser plug-in версий ниже 2.0
- Доработана обработка ошибок, выбрасываемых из Крипто ПРО
- При написании кода будут работать автодополнения и подсказки
- Исправлена [проблема](https://github.com/vgoma/crypto-pro/issues/11) работы библиотеки с UglifyJs
- Методы API доступны напрямую:
В версии 1:
```javascript
window.CryptoPro.call('getSystemInfo');
```
В версии 2 (UMD):
```javascript
window.cryptoPro.getSystemInfo();
```
В версии 2 (ES Modules):
```javascript
import { getSystemInfo } from 'crypto-pro';
getSystemInfo();
```
<a name="developers"></a> <a name="developers"></a>
# Тем, кто хочет помочь # Тем, кто хочет помочь
Буду благодарен за расширение/улучшение/доработку API. Буду благодарен за расширение/улучшение/доработку API.
@ -168,7 +258,7 @@ npm i
npm link ../../ npm link ../../
npm start npm start
``` ```
> После выполнения `npm link ../../` в директории `examples/script-tag/node_modules` папка `crypto-pro-js` станет ярлыком, > После выполнения `npm link ../../` в директории `examples/script-tag/node_modules` папка `crypto-pro` станет ярлыком,
> указывающим на папку содержащую локально собранный пакет. > указывающим на папку содержащую локально собранный пакет.
<a name="tests-execution"></a> <a name="tests-execution"></a>
@ -178,6 +268,32 @@ npm start
npm test npm test
``` ```
<a name="examples-testing"></a>
## Проверка работы примеров с React и Angular
React и Angular используют версию сборки пакета в формате ES модулей из директории `lib/`.
Для их запуска необходимо сначала собрать пакет выполнив:
```bash
npm run build
```
После этого из папки `examples/angular` или `examples/react` залинковать пакет:
```bash
cd examples/angular
npm i
npm link ../../
```
И запустить пример в одном из двух режимов. В режиме разработки:
```bash
npm start
```
или в режиме продакшн:
```bash
npm run build
npm run serve
```
<a name="final-check"></a> <a name="final-check"></a>
## Проверка пакета перед публикацией в NPM ## Проверка пакета перед публикацией в NPM
Необходимо протестировать работу в заявленных браузерах, сделав это на локально запакованной версии пакета. Необходимо протестировать работу в заявленных браузерах, сделав это на локально запакованной версии пакета.
@ -202,15 +318,160 @@ cd ../../../package
npm unlink npm unlink
``` ```
<a name="helpful"></a>
# Полезная информация
<a name="csp-install-linux-osx"></a>
## Установка КриптоПРО CSP в Linux / OSX
> Процесс установки в OSX незначительно отличается от Linux, поэтому описание приведено на примере дистрибутива семейства Debian (x64).
Некоторые команды могут потребовать запуска с `sudo`.
Названия файлов и директорий могут отличаться из-за различий в версиях.
После загрузки [КриптоПРО CSP](https://www.cryptopro.ru/products/csp/downloads) для нужной платформы, распакуйте архив:
```bash
tar -xzvf linux-amd64_deb.tgz
chmod 777 -R linux-amd64_deb/
```
Запустите скрипт установки:
```bash
linux-amd64_deb/install.sh
```
Проверьте **отсутствие** `cprocsp-rdr-gui`:
```bash
dpkg -l | grep cprocsp-rdr
```
Установите дополнительно `cprocsp-rdr-gui-gtk`:
```bash
dpkg -i linux-amd64_deb/cprocsp-rdr-gui-gtk-64_4.0.0-4_amd64.deb
```
[Дополнительная информация по установке](https://www.cryptopro.ru/faq/gde-vzyat-dokumentatsiyu-po-ustanovke-kakie-pakety-stavit)
<a name="plugin-install-linux"></a>
## Установка КриптоПРО ЭЦП browser plugin в Linux
Загрузите [КриптоПРО ЭЦП browser plug-in](https://www.cryptopro.ru/products/cades/plugin) и распакуйте его:
```bash
mkdir cades_linux_amd64
tar -xzvf cades_linux_amd64.tar.gz -C cades_linux_amd64
```
Сконвертируйте `rpm` в `deb` пакеты при помощи утилиты `alien`:
```bash
apt-get update && apt-get install alien
cd cades_linux_amd64
alien *
```
Установите пакеты:
```bash
dpkg -i cprocsp-pki-cades_2.0.0-2_amd64.deb
dpkg -i cprocsp-pki-plugin_2.0.0-2_amd64.deb
```
Проверьте наличие файлов плагина:
```bash
ls -la /opt/cprocsp/lib/amd64 | grep libnpcades
lrwxrwxrwx 1 root root 19 Окт 21 12:33 libnpcades.so -> libnpcades.so.2.0.0
lrwxrwxrwx 1 root root 19 Окт 21 12:33 libnpcades.so.2 -> libnpcades.so.2.0.0
-rwxr-xr-x 1 root root 2727236 Июн 8 14:33 libnpcades.so.2.0.0
```
<a name="plugin-install-old-firefox"></a>
### Настройка плагина для Firefox (до версии 52)
> После настройки плагина на страницах, запрашивающих работу с ЭП в панели навигации, рядом с url будет кнопка,
позволяющая "разрешить и запомнить" использование установленного плагина.
```bash
cd /usr/lib/mozilla/plugins
cp /opt/cprocsp/lib/amd64/libnpcades.so.2.0.0 ./
ldd libnpcades.so.2.0.0
cp /opt/cprocsp/lib/amd64/libnpcades.so.2.0.0 ./libnpcades.so
ldd libnpcades.so
```
Перезапустите Firefox, и убедитесь в наличии CryptoPRO Cades plugin (см. Menu -> Addons).
<a name="certificates-install-linux"></a>
## Установка сертификатов в Linux
> В OSX процесс схож с Linux.
Подключите USB носитель с ключевыми контейнерами и проверьте результат команды:
```bash
/opt/cprocsp/bin/amd64/csptest -keyset -enum_cont -fqcn -verifyc
CSP (Type:80) v4.0.9009 KC1 Release Ver:4.0.9797 OS:Linux CPU:AMD64 FastCode:READY:AVX.
AcquireContext: OK. HCRYPTPROV: 16188003
\\.\FLASH\ivanov
\\.\FLASH\petrov
\\.\FLASH\sidorov
\\.\FLASH\vasiliev
\\.\FLASH\smirnov
OK.
Total: SYS: 0,020 sec USR: 0,060 sec UTC: 0,180 sec
```
Скопируйте ключевой контейнер `\\.\FLASH\.\sidorov` на жесткий диск:
```bash
/opt/cprocsp/bin/amd64/csptest -keycopy -contsrc '\\.\FLASH\sidorov' -contdest '\\.\HDIMAGE\sidor'
CSP (Type:80) v4.0.9009 KC1 Release Ver:4.0.9797 OS:Linux CPU:AMD64 FastCode:READY:AVX.
CryptAcquireContext succeeded.HCRYPTPROV: 38556259
CryptAcquireContext succeeded.HCRYPTPROV: 38770755
Total: SYS: 0,000 sec USR: 0,100 sec UTC: 14,920 sec
[ErrorCode: 0x00000000]
```
> Наличие [ErrorCode: 0x00000000] в завершении каждой команды КриптоПРО говорит о ее успешном выполнении.
Проверьте наличие нового контейнера `\\.\HDIMAGE\sidor`:
```bash
/opt/cprocsp/bin/amd64/csptest -keyset -enum_cont -fqcn -verifyc
CSP (Type:80) v4.0.9009 KC1 Release Ver:4.0.9797 OS:Linux CPU:AMD64 FastCode:READY:AVX.
AcquireContext: OK. HCRYPTPROV: 34554467
\\.\FLASH\ivanov
\\.\FLASH\petrov
\\.\FLASH\sidorov
\\.\FLASH\vasiliev
\\.\FLASH\smirnov
\\.\HDIMAGE\sidor
OK.
Total: SYS: 0,010 sec USR: 0,050 sec UTC: 0,130 sec
[ErrorCode: 0x00000000]
```
Установите личный сертификат:
```bash
/opt/cprocsp/bin/amd64/certmgr -inst -cont '\\.\HDIMAGE\sidor'
```
> Возможно в выводе вы ссылку на сертификат УЦ
При необходимости загрузите сертификат удостоверяющего центра и установите его командой:
```bash
/opt/cprocsp/bin/amd64/certmgr -inst -store uroot -file <файл сертификата>.crt
```
После чего, при проверке установленного личного сертификата вы увидите `PrivateKey Link: Yes`:
```bash
/opt/cprocsp/bin/amd64/certmgr -list -store uMy
```
<a name="lisense"></a> <a name="lisense"></a>
# Лицензия # Лицензия
[MIT](/LICENSE) MIT
[license-url]: /LICENSE [npm-url]: https://npmjs.org/package/crypto-pro
[license-image]: https://img.shields.io/github/license/webmasterskaya/crypto-pro-js [npm-version-image]: http://img.shields.io/npm/v/crypto-pro.svg?style=flat
[npm-url]: https://npmjs.org/package/crypto-pro-js [npm-downloads-image]: http://img.shields.io/npm/dm/crypto-pro.svg?style=flat
[npm-version-image]: https://img.shields.io/npm/v/crypto-pro-js.svg?style=flat [downloads-url]: https://npmcharts.com/compare/crypto-pro?minimal=true
[npm-downloads-image]: https://img.shields.io/npm/dm/crypto-pro-js.svg?style=flat [travis-url]: https://travis-ci.org/vgoma/crypto-pro
[downloads-url]: https://npmcharts.com/compare/crypto-pro-js?minimal=true [travis-image]: http://img.shields.io/travis/vgoma/crypto-pro/master.svg?style=flat
[actions-url]: https://github.com/webmasterskaya/crypto-pro-js/actions [coveralls-image]: https://coveralls.io/repos/github/vgoma/crypto-pro/badge.svg?branch=master
[actions-image]: https://img.shields.io/github/workflow/status/webmasterskaya/crypto-pro-js/test?event=push [coveralls-url]: https://coveralls.io/github/vgoma/crypto-pro?branch=master
[donate-image]: https://img.shields.io/badge/%D1%81%D0%BF%D0%B0%D1%81%D0%B8%D0%B1%D0%BE-%E2%82%BD-yellow
[donate-url]: https://money.yandex.ru/to/410011609769902

View File

@ -1,9 +1,8 @@
{ {
"name": "crypto-pro-js", "name": "crypto-pro",
"description": "Асинхронный JavaScript API для работы с КриптоПРО ЭЦП Browser Plug-In. Forked from https://github.com/vgoma/crypto-pro", "description": "API для взаимодействия с КриптоПро",
"main": "./lib/crypto-pro-js.js", "main": "./lib/crypto-pro.js",
"authors": [ "authors": [
"kern.usr <kern.usr@gmail.com>",
"vgoma <vgoma@yandex.ru>" "vgoma <vgoma@yandex.ru>"
], ],
"license": "MIT", "license": "MIT",
@ -11,12 +10,11 @@
"crypto", "crypto",
"cryptopro", "cryptopro",
"crypto-pro", "crypto-pro",
"crypto-pro-js",
"cades", "cades",
"КриптоПро", "КриптоПро",
"Крипто ПРО" "Крипто ПРО"
], ],
"homepage": "https://github.com/webmasterskaya/crypto-pro-js", "homepage": "https://github.com/vgoma/crypto-pro",
"ignore": [ "ignore": [
"**/.*", "**/.*",
"/*.js", "/*.js",

BIN
crypto-pro-esm.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 791 KiB

BIN
crypto-pro-umd.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 740 KiB

View File

@ -1,8 +0,0 @@
/**
* Добавляет присоединенную подпись к подписанному сообщению по отпечатку сертификата
*
* @param thumbprint - отпечаток сертификата
* @param signedMessage - подписанное сообщение
* @returns подпись в формате PKCS#7
*/
export declare const addAttachedSignature: (thumbprint: string, signedMessage: string | ArrayBuffer) => Promise<string>;

View File

@ -1,9 +0,0 @@
/**
* Добавляет отсоединенную подпись хеша к подписанному сообщению по отпечатку сертификата
*
* @param thumbprint - отпечаток сертификата
* @param signedMessage - подписанное сообщение
* @param messageHash - хеш подписываемого сообщения, сгенерированный по ГОСТ Р 34.11-2012 256 бит
* @returns подпись в формате PKCS#7
*/
export declare const addDetachedSignature: (thumbprint: string, signedMessage: string | ArrayBuffer, messageHash: string) => Promise<string>;

View File

@ -1,8 +0,0 @@
/**
* Создает присоединенную подпись сообщения по отпечатку сертификата
*
* @param thumbprint - отпечаток сертификата
* @param message - подписываемое сообщение
* @returns подпись в формате PKCS#7
*/
export declare const createAttachedSignature: (thumbprint: string, unencryptedMessage: string | ArrayBuffer) => Promise<string>;

View File

@ -1,8 +0,0 @@
/**
* Создает отсоединенную подпись хеша по отпечатку сертификата
*
* @param thumbprint - отпечаток сертификата
* @param messageHash - хеш подписываемого сообщения, сгенерированный по ГОСТ Р 34.11-2012 256 бит
* @returns подпись в формате PKCS#7
*/
export declare const createDetachedSignature: (thumbprint: string, messageHash: string) => Promise<string>;

View File

@ -1,9 +0,0 @@
/**
* Создает хеш сообщения по ГОСТ Р 34.11-2012 256 бит
* https://ru.wikipedia.org/wiki/%D0%A1%D1%82%D1%80%D0%B8%D0%B1%D0%BE%D0%B3_(%D1%85%D0%B5%D1%88-%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D1%8F)
*
* @param unencryptedMessage - сообщение для хеширования
*
* @returns хеш
*/
export declare const createHash: (unencryptedMessage: string | ArrayBuffer) => Promise<string>;

9
dist/api/createSignature.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
/**
* Создает подпись base64 строки по отпечатку сертификата
*
* @param thumbprint - отпечаток сертификата
* @param dataBase64 - строковые данные в формате base64
* @param detachedSignature = true - тип подписи открепленная (true) / присоединенная (false)
* @returns подпись
*/
export declare const createSignature: (thumbprint: string, dataBase64: string, detachedSignature?: boolean) => Promise<string>;

View File

@ -1,8 +0,0 @@
/**
* Создает XML подпись для документа в формате XML
*
* @param thumbprint - отпечаток сертификата
* @param unencryptedMessage - подписываемое сообщение в формате XML
* @returns подпись
*/
export declare const createXMLSignature: (thumbprint: string, unencryptedMessage: string) => Promise<string>;

View File

@ -1,8 +0,0 @@
import { Certificate } from './certificate';
/**
* Возвращает список сертификатов, доступных пользователю из пользовательского хранилища и закрытых ключей, не установленных в системе, без фильтрации по дате и наличию приватного ключа
*
* @param resetCache = false - позволяет сбросить кэш ранее полученных сертификатов
* @returns список сертификатов
*/
export declare const getAllCertificates: (resetCache?: boolean) => Promise<Certificate[]>;

View File

@ -1,9 +0,0 @@
import { Certificate } from './certificate';
/**
* Начиная с версии плагина 2.0.13292 есть возможность получить сертификаты из закрытых ключей
* Возвращает все сертификаты без фильтрации по дате и наличию приватного ключа
*
* @param resetCache = false - позволяет сбросить кэш ранее полученных сертификатов
* @returns список сертификатов
*/
export declare const getAllContainerCertificates: (resetCache?: boolean) => Promise<Certificate[]>;

View File

@ -1,8 +0,0 @@
import { Certificate } from './certificate';
/**
* Возвращает все сертификаты без фильтрации по дате и наличию приватного ключа
*
* @param resetCache = false - позволяет сбросить кэш ранее полученных сертификатов
* @returns список сертификатов
*/
export declare const getAllUserCertificates: (resetCache?: boolean) => Promise<Certificate[]>;

View File

@ -3,7 +3,6 @@ import { Certificate } from './certificate';
* Возвращает сертификат по отпечатку * Возвращает сертификат по отпечатку
* *
* @param thumbprint - отпечаток сертификата * @param thumbprint - отпечаток сертификата
* @param validOnly - проверять сертификаты по дате и наличию приватного ключа
* @returns сертификат * @returns сертификат
*/ */
export declare const getCertificate: (thumbprint: string, validOnly?: boolean) => Promise<Certificate>; export declare const getCertificate: (thumbprint: string) => Promise<Certificate>;

View File

@ -1,8 +0,0 @@
import { Certificate } from './certificate';
/**
* Возвращает список сертификатов, доступных пользователю из пользовательского хранилища и закрытых ключей, не установленных в системе
*
* @param resetCache = false - позволяет сбросить кэш ранее полученных сертификатов
* @returns список сертификатов
*/
export declare const getCertificates: (resetCache?: boolean) => Promise<Certificate[]>;

View File

@ -1,9 +0,0 @@
import { Certificate } from './certificate';
/**
* Начиная с версии плагина 2.0.13292 есть возможность получить сертификаты из закрытых ключей
* Возвращает список сертификатов, доступных пользователю в системе
*
* @param resetCache = false - позволяет сбросить кэш ранее полученных сертификатов
* @returns список сертификатов
*/
export declare const getContainerCertificates: (resetCache?: boolean) => Promise<Certificate[]>;

View File

@ -1,6 +0,0 @@
/**
* Предоставляет информацию о системе
*
* @returns информацию о CSP
*/
export declare const getCspVersion: () => Promise<string>;

View File

@ -1,6 +0,0 @@
/**
* Предоставляет информацию о системе
*
* @returns информацию о плагине
*/
export declare const getPluginVersion: () => Promise<string>;

14
dist/api/index.d.ts vendored
View File

@ -1,18 +1,6 @@
export * from './getCertificate'; export * from './getCertificate';
export * from './getUserCertificates'; export * from './getUserCertificates';
export * from './getAllUserCertificates';
export * from './getContainerCertificates';
export * from './getAllContainerCertificates';
export * from './getCertificates';
export * from './getAllCertificates';
export * from './getSystemInfo'; export * from './getSystemInfo';
export * from './isValidSystemSetup'; export * from './isValidSystemSetup';
export * from './createXMLSignature'; export * from './createSignature';
export * from './createDetachedSignature';
export * from './addDetachedSignature';
export * from './createAttachedSignature';
export * from './addAttachedSignature';
export * from './createHash';
export * from './certificate'; export * from './certificate';
export * from './getCspVersion';
export * from './getPluginVersion';

View File

@ -2,10 +2,6 @@ export declare const OIDS_DICTIONARY: {
'1.2.643.2.2.34.6': string; '1.2.643.2.2.34.6': string;
'1.2.643.2.39.1.1': string; '1.2.643.2.39.1.1': string;
'1.2.643.3.131.1.1': string; '1.2.643.3.131.1.1': string;
'1.2.643.100.4': string;
'1.2.643.100.1': string;
'1.2.643.100.5': string;
'1.2.643.100.3': string;
'1.2.643.3.141.1.1': string; '1.2.643.3.141.1.1': string;
'1.2.643.3.141.1.2': string; '1.2.643.3.141.1.2': string;
'1.2.643.3.2.100.65.13.11': string; '1.2.643.3.2.100.65.13.11': string;

View File

@ -1,7 +0,0 @@
// Type definitions for crypto-pro-js 2.3.3
// Project: crypto-pro-js
// Definitions by: Artem Vasilev https://github.com/kernusr
export as namespace cryptoPro;
export * from './api';

6071
dist/crypto-pro-js.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

7
dist/crypto-pro.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
// Type definitions for crypto-pro 2.0.5
// Project: crypto-pro
// Definitions by: Vitalii Goma https://github.com/vgoma
export as namespace cryptoPro;
export * from './api';

2530
dist/crypto-pro.js vendored Normal file

File diff suppressed because it is too large Load Diff

1
dist/crypto-pro.js.map vendored Normal file

File diff suppressed because one or more lines are too long

2
dist/crypto-pro.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1
dist/crypto-pro.min.js.map vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
export declare const _extractCommonName: (subjectName: string) => string | undefined; export declare const _extractCommonName: (subjectName: string) => string;

View File

@ -1 +1 @@
export declare const _extractMeaningfulErrorMessage: (error: Error) => string | null; export declare const _extractMeaningfulErrorMessage: (error: Error) => string;

View File

@ -1,7 +0,0 @@
/**
* Возвращает сертификат в формате Cades по отпечатку из хранилища закрытого ключа
*
* @param thumbprint - отпечаток сертификата
* @returns сертификат в формате Cades
*/
export declare const _getCadesContainerCert: (thumbprint: string) => Promise<any>;

View File

@ -1,7 +0,0 @@
/**
* Возвращает сертификат в формате Cades по отпечатку из хранилища пользователя
*
* @param thumbprint - отпечаток сертификата
* @returns сертификат в формате Cades
*/
export declare const _getCadesUserCert: (thumbprint: string) => Promise<any>;

View File

@ -0,0 +1,13 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false

46
examples/angular/.gitignore vendored Normal file
View File

@ -0,0 +1,46 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
/node_modules
# profiling files
chrome-profiler-events*.json
speed-measure-plugin*.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db

View File

@ -0,0 +1,27 @@
# Angular
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.0.7.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).

View File

@ -0,0 +1,124 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"angular": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": true,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "angular:build"
},
"configurations": {
"production": {
"browserTarget": "angular:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "angular:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "angular:serve"
},
"configurations": {
"production": {
"devServerTarget": "angular:serve:production"
}
}
}
}
}},
"defaultProject": "angular"
}

View File

@ -0,0 +1,12 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# You can see what browsers were selected by your queries by running:
# npx browserslist
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11 # For IE 9-11 support, remove 'not'.

View File

@ -0,0 +1,32 @@
// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
/**
* @type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
browserName: 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};

View File

@ -0,0 +1,23 @@
import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('angular app is running!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});

View File

@ -0,0 +1,11 @@
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo(): Promise<unknown> {
return browser.get(browser.baseUrl) as Promise<unknown>;
}
getTitleText(): Promise<string> {
return element(by.css('app-root .content span')).getText() as Promise<string>;
}
}

View File

@ -0,0 +1,13 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/e2e",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}

View File

@ -0,0 +1,32 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/angular'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};

13350
examples/angular/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,51 @@
{
"name": "crypto-pro-example-angular",
"version": "0.0.0",
"description": "Пример использования пакета crypto-pro в typescript проекте с angular",
"scripts": {
"serve": "static --host-address localhost --port 8082 dist/angular",
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~9.0.7",
"@angular/common": "~9.0.7",
"@angular/compiler": "~9.0.7",
"@angular/core": "~9.0.7",
"@angular/forms": "~9.0.7",
"@angular/platform-browser": "~9.0.7",
"@angular/platform-browser-dynamic": "~9.0.7",
"@angular/router": "~9.0.7",
"crypto-pro": "2.0.5",
"rxjs": "~6.5.4",
"tslib": "^1.10.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.900.7",
"@angular/cli": "~9.0.7",
"@angular/compiler-cli": "~9.0.7",
"@angular/language-service": "~9.0.7",
"@types/node": "^12.11.1",
"@types/jasmine": "~3.5.0",
"@types/jasminewd2": "~2.0.3",
"codelyzer": "^5.1.2",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~2.1.0",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.2",
"node-static": "0.7.11",
"protractor": "~5.4.3",
"ts-node": "~8.3.0",
"tslint": "~5.18.0",
"typescript": "~3.7.5"
}
}

View File

@ -0,0 +1 @@
<app-crypto-pro></app-crypto-pro>

View File

@ -0,0 +1,24 @@
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'angular'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('angular');
});
});

View File

@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular';
}

View File

@ -0,0 +1,20 @@
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CryptoProComponent } from './crypto-pro/crypto-pro.component';
@NgModule({
declarations: [
AppComponent,
CryptoProComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

View File

@ -0,0 +1,34 @@
<select name="certificate"
[(ngModel)]="thumbprint">
<option value="null" disabled>Не выбран</option>
<option *ngFor="let cert of certificateList"
[value]="cert.thumbprint">
{{cert.name}}
</option>
</select>
<button type="button"
[disabled]="!thumbprint"
(click)="createSignature(thumbprint)">
Создать подпись
</button>
<button type="button"
[disabled]="!thumbprint"
(click)="showCertInfo(thumbprint)">
Информация о сертификате
</button>
<pre *ngIf="certInfo">{{certInfo | json}}</pre>
<br>
<textarea name="signature"
[(ngModel)]="signature"
cols="100"
rows="30"></textarea>
<pre *ngIf="error">{{error}}</pre>
<pre *ngIf="systemInfo">{{systemInfo | json}}</pre>

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CryptoProComponent } from './crypto-pro.component';
describe('CryptoProComponent', () => {
let component: CryptoProComponent;
let fixture: ComponentFixture<CryptoProComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CryptoProComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CryptoProComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,99 @@
import { Component, OnInit } from '@angular/core';
import {
getCertificate,
getUserCertificates,
getSystemInfo,
isValidSystemSetup,
createSignature,
SystemInfo,
Certificate
} from 'crypto-pro';
@Component({
selector: 'app-crypto-pro',
templateUrl: './crypto-pro.component.html',
styleUrls: ['./crypto-pro.component.css']
})
export class CryptoProComponent implements OnInit {
public certificateList: Certificate[] = [];
public thumbprint: string = null;
public signature: string;
public systemInfo: SystemInfo & {
isValidSystemSetup: boolean;
};
public error: string;
public certInfo;
constructor() { }
public ngOnInit(): void {
this.displayCertificates();
this.displaySystemInfo();
}
public async createSignature(thumbprint) {
// Вычислинный hash по ГОСТ Р 34.11-94 для строки: "abc"
const hash = 'b285056dbf18d7392d7677369524dd14747459ed8143997e163b2986f92fd42c';
const hashBase64 = window.btoa(hash);
try {
this.signature = await createSignature(thumbprint, hashBase64);
} catch (error) {
this.error = error.message;
}
}
public async showCertInfo(thumbprint) {
try {
const certificate = await getCertificate(thumbprint);
this.certInfo = {
name: certificate.name,
issuerName: certificate.issuerName,
subjectName: certificate.subjectName,
thumbprint: certificate.thumbprint,
validFrom: certificate.validFrom,
validTo: certificate.validTo,
isValid: await certificate.isValid(),
version: await certificate.getCadesProp('Version'),
base64: await certificate.exportBase64(),
algorithm: await certificate.getAlgorithm(),
extendedKeyUsage: await certificate.getExtendedKeyUsage(),
ownerInfo: await certificate.getOwnerInfo(),
issuerInfo: await certificate.getIssuerInfo(),
decodedExtendedKeyUsage: await certificate.getDecodedExtendedKeyUsage(),
'1.3.6.1.4.1.311.80.1': await certificate.hasExtendedKeyUsage('1.3.6.1.4.1.311.80.1'),
'[\'1.3.6.1.5.5.7.3.2\', \'1.3.6.1.4.1.311.10.3.12\']': await certificate.hasExtendedKeyUsage([
'1.3.6.1.5.5.7.3.2',
'1.3.6.1.4.1.311.10.3.12'
]),
'1.3.6.1.4.1.311.80.2': await certificate.hasExtendedKeyUsage('1.3.6.1.4.1.311.80.2'),
'\'1.3.6.1.5.5.7.3.3\', \'1.3.6.1.4.1.311.10.3.12\'': await certificate.hasExtendedKeyUsage([
'1.3.6.1.5.5.7.3.3',
'1.3.6.1.4.1.311.10.3.12'
]),
};
} catch (error) {
this.error = error.message;
}
}
private async displayCertificates() {
try {
this.certificateList = await getUserCertificates();
} catch (error) {
this.error = error.message;
}
}
private async displaySystemInfo() {
try {
this.systemInfo = {
...await getSystemInfo(),
isValidSystemSetup: await isValidSystemSetup()
};
} catch (error) {
this.error = error.message;
}
}
}

View File

View File

@ -0,0 +1,3 @@
export const environment = {
production: true
};

View File

@ -0,0 +1,16 @@
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.

Binary file not shown.

After

Width:  |  Height:  |  Size: 948 B

View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@ -0,0 +1,12 @@
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));

View File

@ -0,0 +1,63 @@
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/

View File

@ -0,0 +1 @@
/* You can add global styles to this file, and also import other style files */

View File

@ -0,0 +1,25 @@
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: {
context(path: string, deep?: boolean, filter?: RegExp): {
keys(): string[];
<T>(id: string): T;
};
};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

View File

@ -0,0 +1,14 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}

View File

@ -0,0 +1,23 @@
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"lib": [
"es2018",
"dom"
]
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}

View File

@ -0,0 +1,18 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"src/test.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}

View File

@ -0,0 +1,91 @@
{
"extends": "tslint:recommended",
"rules": {
"array-type": false,
"arrow-parens": false,
"deprecation": {
"severity": "warning"
},
"component-class-suffix": true,
"contextual-lifecycle": true,
"directive-class-suffix": true,
"directive-selector": [
true,
"attribute",
"app",
"camelCase"
],
"component-selector": [
true,
"element",
"app",
"kebab-case"
],
"import-blacklist": [
true,
"rxjs/Rx"
],
"interface-name": false,
"max-classes-per-file": false,
"max-line-length": [
true,
140
],
"member-access": false,
"member-ordering": [
true,
{
"order": [
"static-field",
"instance-field",
"static-method",
"instance-method"
]
}
],
"no-consecutive-blank-lines": false,
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-empty": false,
"no-inferrable-types": [
true,
"ignore-params"
],
"no-non-null-assertion": true,
"no-redundant-jsdoc": true,
"no-switch-case-fall-through": true,
"no-var-requires": false,
"object-literal-key-quotes": [
true,
"as-needed"
],
"object-literal-sort-keys": false,
"ordered-imports": false,
"quotemark": [
true,
"single"
],
"trailing-comma": false,
"no-conflicting-lifecycle": true,
"no-host-metadata-property": true,
"no-input-rename": true,
"no-inputs-metadata-property": true,
"no-output-native": true,
"no-output-on-prefix": true,
"no-output-rename": true,
"no-outputs-metadata-property": true,
"template-banana-in-box": true,
"template-no-negated-async": true,
"use-lifecycle-interface": true,
"use-pipe-transform-interface": true
},
"rulesDirectory": [
"codelyzer"
]
}

1
examples/react/.env Normal file
View File

@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true

23
examples/react/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

68
examples/react/README.md Normal file
View File

@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

15010
examples/react/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
{
"name": "crypto-pro-example-react",
"version": "0.1.0",
"description": "Пример использования пакета crypto-pro в javascript проекте с react",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "4.2.4",
"@testing-library/react": "9.5.0",
"@testing-library/user-event": "7.2.1",
"crypto-pro": "2.0.5",
"react": "^16.13.1",
"react-app-polyfill": "1.0.6",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"devDependencies": {
"node-static": "0.7.11"
},
"scripts": {
"serve": "static --host-address localhost --port 8081 build",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

View File

@ -0,0 +1,76 @@
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], function () {
factory(root);
});
} else factory(root);
// node.js has always supported base64 conversions, while browsers that support
// web workers support base64 too, but you may never know.
})(typeof exports !== "undefined" ? exports : this, function (root) {
if (root.atob) {
// Some browsers' implementation of atob doesn't support whitespaces
// in the encoded string (notably, IE). This wraps the native atob
// in a function that strips the whitespaces.
// The original function can be retrieved in atob.original
try {
root.atob(" ");
} catch (e) {
root.atob = (function (atob) {
var func = function (string) {
return atob(String(string).replace(/[\t\n\f\r ]+/g, ""));
};
func.original = atob;
return func;
})(root.atob);
}
return;
}
// base64 character set, plus padding character (=)
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// Regular expression to check formal correctness of base64 encoded strings
b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
root.btoa = function (string) {
string = String(string);
var bitmap, a, b, c,
result = "", i = 0,
rest = string.length % 3; // To determine the final padding
for (; i < string.length;) {
if ((a = string.charCodeAt(i++)) > 255
|| (b = string.charCodeAt(i++)) > 255
|| (c = string.charCodeAt(i++)) > 255)
throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");
bitmap = (a << 16) | (b << 8) | c;
result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63)
+ b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
}
// If there's need of padding, replace the last 'A's with equal signs
return rest ? result.slice(0, rest - 3) + "===".substring(rest) : result;
};
root.atob = function (string) {
// atob can work with strings with whitespaces, even inside the encoded part,
// but only \t, \n, \f, \r and ' ', which can be stripped.
string = String(string).replace(/[\t\n\f\r ]+/g, "");
if (!b64re.test(string))
throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
// Adding the padding if missing, for semplicity
string += "==".slice(2 - (string.length & 3));
var bitmap, result = "", r1, r2, i = 0;
for (; i < string.length;) {
bitmap = b64.indexOf(string.charAt(i++)) << 18 | b64.indexOf(string.charAt(i++)) << 12
| (r1 = b64.indexOf(string.charAt(i++))) << 6 | (r2 = b64.indexOf(string.charAt(i++)));
result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255)
: r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255)
: String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
}
return result;
};
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -0,0 +1,45 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<!-- Полифилл для работы демо в IE9 -->
<script src="atob-btoa.js"></script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

22
examples/react/src/App.js Normal file
View File

@ -0,0 +1,22 @@
import React from 'react';
import './App.css';
import CryptoPro from './components/CryptoPro';
function App() {
return (
<CryptoPro>{({certificate, setCertificate, signature, setSignature, error, setError}) =>
<>
<CryptoPro.CertList onChange={setCertificate} onError={setError}/>
<CryptoPro.Sign certificate={certificate} onSign={setSignature} onError={setError}>
Создать подпись
</CryptoPro.Sign>
<CryptoPro.CertInfo certificate={certificate} onError={setError}/>
<textarea value={signature} readOnly cols="100" rows="30"/>
<pre>{error}</pre>
<CryptoPro.SystemInfo onError={setError}/>
</>
}</CryptoPro>
);
}
export default App;

View File

@ -0,0 +1,9 @@
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
xtest('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@ -0,0 +1,55 @@
import React, { useState } from 'react';
function CertInfo({certificate, onError}) {
const [certInfo, setCertInfo] = useState(null);
async function showCertInfo() {
try {
setCertInfo({
name: certificate.name,
issuerName: certificate.issuerName,
subjectName: certificate.subjectName,
thumbprint: certificate.thumbprint,
validFrom: certificate.validFrom,
validTo: certificate.validTo,
isValid: await certificate.isValid(),
version: await certificate.getCadesProp('Version'),
base64: await certificate.exportBase64(),
algorithm: await certificate.getAlgorithm(),
extendedKeyUsage: await certificate.getExtendedKeyUsage(),
ownerInfo: await certificate.getOwnerInfo(),
issuerInfo: await certificate.getIssuerInfo(),
decodedExtendedKeyUsage: await certificate.getDecodedExtendedKeyUsage(),
'1.3.6.1.4.1.311.80.1': await certificate.hasExtendedKeyUsage('1.3.6.1.4.1.311.80.1'),
"['1.3.6.1.5.5.7.3.2', '1.3.6.1.4.1.311.10.3.12']": await certificate.hasExtendedKeyUsage([
'1.3.6.1.5.5.7.3.2',
'1.3.6.1.4.1.311.10.3.12'
]),
'1.3.6.1.4.1.311.80.2': await certificate.hasExtendedKeyUsage('1.3.6.1.4.1.311.80.2'),
"'1.3.6.1.5.5.7.3.3', '1.3.6.1.4.1.311.10.3.12'": await certificate.hasExtendedKeyUsage([
'1.3.6.1.5.5.7.3.3',
'1.3.6.1.4.1.311.10.3.12'
]),
});
} catch (error) {
onError(error.message);
}
}
return (
<>
<button
type="button"
onClick={showCertInfo}
disabled={!certificate}>
Информация о сертификате
</button>
<br/>
{certInfo ? (
<pre>{JSON.stringify(certInfo, null, ' ')}</pre>
) : null}
</>
);
}
export default CertInfo;

View File

@ -0,0 +1,31 @@
import React, { useState, useEffect } from 'react';
import { getUserCertificates } from 'crypto-pro';
function CertList({onChange, onError}) {
const [certificates, setCertificates] = useState([]);
function selectCertificate(event) {
onChange(certificates.find(({thumbprint}) => thumbprint === event.target.value));
}
useEffect(() => {
(async () => {
try {
setCertificates(await getUserCertificates());
} catch (error) {
onError(error.message);
}
})();
}, [onError]);
return (
<select onChange={selectCertificate}>
<option defaultValue={null}>Не выбран</option>
{certificates.map(({name, thumbprint}) =>
<option key={thumbprint} value={thumbprint}>{name}</option>
)}
</select>
);
}
export default CertList;

View File

@ -0,0 +1,27 @@
import React from 'react';
import { createSignature } from 'crypto-pro';
function Sign({certificate, onSign, onError, children}) {
async function sign() {
// Вычислинный hash по ГОСТ Р 34.11-94 для строки: "abc"
const hash = 'b285056dbf18d7392d7677369524dd14747459ed8143997e163b2986f92fd42c';
const hashBase64 = window.btoa(hash);
try {
onSign(await createSignature(certificate.thumbprint, hashBase64));
} catch (error) {
onError(error.message);
}
}
return (
<button
type="button"
disabled={!certificate}
onClick={sign}>
{children}
</button>
);
}
export default Sign;

View File

@ -0,0 +1,29 @@
import React, { useState, useEffect } from 'react';
import { getSystemInfo, isValidSystemSetup } from 'crypto-pro';
function SystemInfo({onError}) {
const [systemInfo, setSystemInfo] = useState(null);
useEffect(() => {
(async () => {
try {
setSystemInfo({
...await getSystemInfo(),
isValidSystemSetup: await isValidSystemSetup()
});
} catch (error) {
onError(error.message);
}
})();
}, [onError]);
if (!systemInfo) {
return null;
}
return (
<pre>{JSON.stringify(systemInfo, null, ' ')}</pre>
);
}
export default SystemInfo;

View File

@ -0,0 +1,27 @@
import { useState } from 'react';
import CertList from './CertList';
import CertInfo from './CertInfo';
import Sign from './Sign';
import SystemInfo from './SystemInfo';
const CryptoPro = ({children}) => {
const [certificate, setCertificate] = useState(null);
const [signature, setSignature] = useState('');
const [error, setError] = useState('');
return children({
certificate,
setCertificate,
signature,
setSignature,
error,
setError
});
};
CryptoPro.CertList = CertList;
CryptoPro.Sign = Sign;
CryptoPro.CertInfo = CertInfo;
CryptoPro.SystemInfo = SystemInfo;
export default CryptoPro;

View File

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View File

@ -0,0 +1,20 @@
import 'react-app-polyfill/ie9';
import 'react-app-polyfill/stable';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

View File

@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,141 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}

View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';

View File

@ -1,280 +1,8 @@
{ {
"name": "crypto-pro-example-es5-script-tag", "name": "crypto-pro-example-es5-script-tag",
"version": "2.3.3", "version": "0.0.0",
"lockfileVersion": 2, "lockfileVersion": 1,
"requires": true, "requires": true,
"packages": {
"": {
"name": "crypto-pro-example-es5-script-tag",
"version": "2.3.3",
"dependencies": {
"crypto-pro-js": "^2.3.3"
},
"devDependencies": {
"node-static": "0.7.11",
"symlink-dir": "3.1.2"
}
},
"node_modules/balanced-match": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
"integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
"dev": true
},
"node_modules/better-path-resolve": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/better-path-resolve/-/better-path-resolve-1.0.0.tgz",
"integrity": "sha512-pbnl5XzGBdrFU/wT4jqmJVPn2B6UHPBOhzMQkY/SPUPB6QtUXtmBHBIwCbXJol93mOpGMnQyP/+BB19q04xj7g==",
"dev": true,
"dependencies": {
"is-windows": "^1.0.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/colors": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz",
"integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==",
"dev": true,
"engines": {
"node": ">=0.1.90"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
"dev": true
},
"node_modules/crypto-pro-js": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/crypto-pro-js/-/crypto-pro-js-2.3.3.tgz",
"integrity": "sha512-ge6PXRw6pu2kXeaqwEpHvmQEuSRQWJcVfQfPfF5gGONIi+jUHFsvkeS5ojFcKKBDqFHnYUQXFZ1aMKDGdoVRqg==",
"engines": {
"node": "~16"
}
},
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
"dev": true
},
"node_modules/glob": {
"version": "7.1.6",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz",
"integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==",
"dev": true,
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.0.4",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"engines": {
"node": "*"
}
},
"node_modules/graceful-fs": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz",
"integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==",
"dev": true
},
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
"dev": true,
"dependencies": {
"once": "^1.3.0",
"wrappy": "1"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"dev": true
},
"node_modules/is-windows": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz",
"integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==",
"dev": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/make-dir": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.0.2.tgz",
"integrity": "sha512-rYKABKutXa6vXTXhoV18cBE7PaewPXHe/Bdq4v+ZLMhxbWApkFFplT0LcbMW+6BbjnQXzZ/sAvSE/JdguApG5w==",
"dev": true,
"dependencies": {
"semver": "^6.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"dev": true,
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"dev": true,
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/minimist": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz",
"integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=",
"dev": true
},
"node_modules/node-static": {
"version": "0.7.11",
"resolved": "https://registry.npmjs.org/node-static/-/node-static-0.7.11.tgz",
"integrity": "sha512-zfWC/gICcqb74D9ndyvxZWaI1jzcoHmf4UTHWQchBNuNMxdBLJMDiUgZ1tjGLEIe/BMhj2DxKD8HOuc2062pDQ==",
"dev": true,
"dependencies": {
"colors": ">=0.6.0",
"mime": "^1.2.9",
"optimist": ">=0.3.4"
},
"bin": {
"static": "bin/cli.js"
},
"engines": {
"node": ">= 0.4.1"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
"dev": true,
"dependencies": {
"wrappy": "1"
}
},
"node_modules/optimist": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz",
"integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=",
"dev": true,
"dependencies": {
"minimist": "~0.0.1",
"wordwrap": "~0.0.2"
}
},
"node_modules/path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=",
"dev": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/rename-overwrite": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/rename-overwrite/-/rename-overwrite-2.0.2.tgz",
"integrity": "sha512-XodkUmbg11ZzZoAkYfJYEmj8FscfeRL2KHGALeDSB76ia8A1zqQq0+WkcepXm7QkuzmW0CE3uiFUBr/UJfin+w==",
"dev": true,
"dependencies": {
"graceful-fs": "^4.1.11",
"rimraf": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/rimraf": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
"dev": true,
"dependencies": {
"glob": "^7.1.3"
},
"bin": {
"rimraf": "bin.js"
}
},
"node_modules/semver": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
"integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
}
},
"node_modules/symlink-dir": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/symlink-dir/-/symlink-dir-3.1.2.tgz",
"integrity": "sha512-wuqI+beQTU3XQq6bHTg4tcFiXlAN5uWNus+R0/I/R9O/ORpVHdCo2JQp04dCexBIb94VarosKFU+kjVEgzIQpQ==",
"dev": true,
"dependencies": {
"better-path-resolve": "^1.0.0",
"graceful-fs": "^4.1.11",
"make-dir": "^3.0.0",
"rename-overwrite": "^2.0.1"
},
"bin": {
"symlink-dir": "dist/cli.js"
},
"engines": {
"node": ">=8.15"
}
},
"node_modules/wordwrap": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz",
"integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=",
"dev": true,
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
"dev": true
}
},
"dependencies": { "dependencies": {
"balanced-match": { "balanced-match": {
"version": "1.0.0", "version": "1.0.0",
@ -313,10 +41,10 @@
"integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
"dev": true "dev": true
}, },
"crypto-pro-js": { "crypto-pro": {
"version": "2.3.3", "version": "2.0.5",
"resolved": "https://registry.npmjs.org/crypto-pro-js/-/crypto-pro-js-2.3.3.tgz", "resolved": "https://registry.npmjs.org/crypto-pro/-/crypto-pro-2.0.5.tgz",
"integrity": "sha512-ge6PXRw6pu2kXeaqwEpHvmQEuSRQWJcVfQfPfF5gGONIi+jUHFsvkeS5ojFcKKBDqFHnYUQXFZ1aMKDGdoVRqg==" "integrity": "sha512-YZbVNt9ZmE75H97gdqS2ZGW8xnuHxdvQxLH/SmMQIizIBLmMIylOhY3HvgEUxnrIkL64/m6vrG5H2w7pGTb17Q=="
}, },
"fs.realpath": { "fs.realpath": {
"version": "1.0.0", "version": "1.0.0",
@ -382,9 +110,9 @@
"dev": true "dev": true
}, },
"minimatch": { "minimatch": {
"version": "3.1.2", "version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
"dev": true, "dev": true,
"requires": { "requires": {
"brace-expansion": "^1.1.7" "brace-expansion": "^1.1.7"

View File

@ -1,10 +1,10 @@
{ {
"name": "crypto-pro-example-es5-script-tag", "name": "crypto-pro-example-es5-script-tag",
"version": "2.3.3", "version": "0.0.0",
"description": "Пример использования пакета crypto-pro через тэг script", "description": "Пример использования пакета crypto-pro через тэг script",
"private": true, "private": true,
"scripts": { "scripts": {
"link-library": "symlink-dir ./node_modules/crypto-pro-js/dist ./public/dist", "link-library": "symlink-dir ./node_modules/crypto-pro/dist ./public/dist",
"serve": "static --host-address localhost --port 8080 public", "serve": "static --host-address localhost --port 8080 public",
"start": "npm run link-library && npm run serve" "start": "npm run link-library && npm run serve"
}, },
@ -13,6 +13,6 @@
"symlink-dir": "3.1.2" "symlink-dir": "3.1.2"
}, },
"dependencies": { "dependencies": {
"crypto-pro-js": "^2.3.3" "crypto-pro": "2.0.5"
} }
} }

Some files were not shown because too many files have changed in this diff Show More