### Install and Initialize CryptoPro, JaCarta-2, or RuToken Provider
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Demonstrates how to install RusCryptoJS using npm and initialize different cryptographic providers like CryptoPro, JaCarta-2, and RuToken. Shows example outputs for each provider's initialization.
```javascript
// Installation
npm install ruscryptojs
// ES6 Module Import
import { CryptoPro, JaCarta2, RuToken, DN } from 'ruscryptojs';
// Browser Script Tag
//
//
// Initialize CryptoPro Provider
const cryptoPro = new CryptoPro();
const info = await cryptoPro.init();
console.log(info);
// Output: { version: "2.0.15400", manifestV3: true }
// Initialize JaCarta-2 Provider
const jacarta2 = new JaCarta2();
const info = await jacarta2.init();
console.log(info);
// Output: {
// version: "4.3.0",
// serialNumber: "123456",
// label: "MyToken",
// type: "gost2",
// flags: { hasFlash: true }
// }
// Initialize RuToken Provider
const rutoken = new RuToken();
const info = await rutoken.init();
console.log(info);
// Output: {
// version: "3.0.0",
// serial: "123456",
// reader: "ACS CCID USB Reader",
// label: "RuToken",
// type: 1,
// model: "Rutoken ECP"
// }
```
--------------------------------
### Complete CryptoPro Workflow Example in JavaScript
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Demonstrates the full certificate lifecycle using CryptoPro, from CSR generation to document signing and verification. It initializes the provider, enables PIN caching, generates a CSR, simulates receiving a certificate, installs it, retrieves its info, lists certificates, signs and verifies a document, encrypts and decrypts sensitive data, and finally cleans up resources. Requires the 'ruscryptojs' library.
```javascript
import { CryptoPro, DN } from 'ruscryptojs';
async function completeWorkflow() {
// 1. Initialize provider
const cryptoPro = new CryptoPro();
const info = await cryptoPro.init();
console.log(`Initialized CryptoPro version ${info.version}`);
// 2. Enable PIN caching
await cryptoPro.bind("12345");
// 3. Generate CSR
const dn = new DN();
dn.CN = "Иванов Иван Иванович";
dn.O = "ООО Системы";
dn.C = "RU";
dn.SNILS = "12345678901";
const ekuOids = [
"1.3.6.1.5.5.7.3.2", // Client Authentication
"1.3.6.1.5.5.7.3.4" // Email Protection
];
const { csr } = await cryptoPro.generateCSR(dn, ekuOids, {
providerType: 80 // GOST R 34.10-2012
});
console.log("CSR generated:", csr.substring(0, 50) + "...");
// 4. Send CSR to CA and receive certificate (simulated)
// const certBase64 = await sendToCA(csr);
const certBase64 = "MIIDZjCCAhCgAwIBAgIBATAKBg..."; // From CA
// 5. Install certificate
const thumbprint = await cryptoPro.writeCertificate(certBase64);
console.log("Certificate installed with thumbprint:", thumbprint);
// 6. Get certificate info
const certInfo = await cryptoPro.certificateInfo(thumbprint);
console.log(`Certificate valid from ${certInfo.ValidFromDate} to ${certInfo.ValidToDate}`);
// 7. List all certificates
const certificates = await cryptoPro.listCertificates();
console.log(`Found ${certificates.length} certificate(s)`)
// 8. Sign document
const document = "Contract No. 123/2025 dated 2025-01-15";
const documentBase64 = btoa(unescape(encodeURIComponent(document)));
const signature = await cryptoPro.signData(documentBase64, thumbprint, {
attached: false
});
console.log("Document signed:", signature.substring(0, 50) + "...");
// 9. Verify signature
const isValid = await cryptoPro.verifySign(documentBase64, signature, {
attached: false
});
console.log("Signature valid:", isValid);
// 10. Encrypt sensitive data
const sensitiveData = "Bank account: 40817810099910004312";
const sensitiveBase64 = btoa(unescape(encodeURIComponent(sensitiveData)));
const encrypted = await cryptoPro.encryptData(sensitiveBase64, thumbprint);
console.log("Data encrypted:", encrypted.substring(0, 50) + "...");
// 11. Decrypt data
const decryptedBase64 = await cryptoPro.decryptData(encrypted, thumbprint);
const decrypted = decodeURIComponent(escape(atob(decryptedBase64)));
console.log("Decrypted data:", decrypted);
// 12. Clean up
await cryptoPro.unbind();
console.log("Workflow completed successfully");
}
// Execute workflow with error handling
completeWorkflow().catch(error => {
console.error("Workflow failed:", error.message);
});
```
--------------------------------
### Install Certificates with CryptoPro, JaCarta-2, RuToken
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Writes received certificates from Certificate Authorities into the cryptographic provider's containers. The process varies slightly depending on the provider, with some requiring a key pair identifier obtained during CSR generation.
```javascript
// CryptoPro - Write Certificate
const certBase64 = "MIID..."; // Certificate from CA in base64
const thumbprint = await cryptoPro.writeCertificate(certBase64);
console.log(thumbprint);
// JaCarta-2 - Write Certificate (requires keyPairId from CSR)
const containerId = await jacarta2.writeCertificate(certBase64, keyPairId);
console.log(containerId);
// RuToken - Write Certificate
const certId = await rutoken.writeCertificate(certBase64);
console.log(certId);
```
--------------------------------
### Get Certificate Information and Export
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Fetches detailed information about a specific certificate, including its validity, cryptographic algorithm, issuer, and serial number. Optionally, it can validate the certificate chain. It also allows exporting the certificate in base64 format.
```javascript
// Get detailed certificate information
const certInfo = await cryptoPro.certificateInfo(certId, {
checkValid: true // Validate certificate chain (may be slow with large CRLs)
});
console.log(`Name: ${certInfo.Name}`);
console.log(`Subject: ${certInfo.Subject.CN}`);
console.log(`Issuer: ${certInfo.Issuer.toString()}`);
console.log(`Algorithm: ${certInfo.Algorithm}`);
console.log(`Serial Number: ${certInfo.SerialNumber}`);
console.log(`Thumbprint: ${certInfo.Thumbprint}`);
console.log(`Valid From: ${certInfo.ValidFromDate}`);
console.log(`Valid To: ${certInfo.ValidToDate}`);
console.log(`Has Private Key: ${certInfo.HasPrivateKey}`);
console.log(`Is Valid: ${certInfo.IsValid}`);
console.log(`Provider: ${certInfo.ProviderName}`);
// Export certificate in base64 format
const certBase64 = await cryptoPro.readCertificate(certId);
console.log(certBase64);
```
--------------------------------
### Manage PIN Codes and Bind Tokens with CryptoPro, JaCarta-2, and RuToken
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
This snippet illustrates how to manage PIN codes by enabling caching for multiple operations, thus avoiding repeated prompts. It shows initialization, binding (authentication), performing operations, and unbinding (clearing the cached PIN) for CryptoPro, JaCarta-2, and RuToken.
```javascript
// CryptoPro - Enable PIN caching
await cryptoPro.init();
// Bind enables PIN caching for subsequent operations
const bound = await cryptoPro.bind("12345");
console.log(bound);
// Output: true
// Now operations won't prompt for PIN
const signature = await cryptoPro.signData(dataBase64, certId, {
attached: false
// No pin parameter needed
});
// Unbind to clear cached PIN
const unbound = await cryptoPro.unbind();
console.log(unbound);
// Output: true
// JaCarta-2 - Authentication with bind
await jacarta2.init();
await jacarta2.bind("1234"); // Authenticate on token
// Perform operations without repeated authentication
const csr = await jacarta2.generateCSR(dn);
const sig = await jacarta2.signData(dataBase64, containerId, { attached: false });
await jacarta2.unbind(); // Close session
// RuToken - Login to token
await rutoken.init();
const loginSuccess = await rutoken.bind("1234");
console.log(loginSuccess);
// Output: true
// Operations with authenticated session
const encrypted = await rutoken.encryptData(dataBase64, certId);
const logoutSuccess = await rutoken.unbind();
console.log(logoutSuccess);
// Output: true
```
--------------------------------
### Co-Signing and Adding Signatures (JavaScript)
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Enables co-signing documents with multiple certificates or adding signatures to existing CMS structures. Supports CryptoPro for simultaneous signing and adding signatures, and RuToken for adding signatures to existing CMS.
```javascript
// CryptoPro - Sign with two certificates simultaneously
const certificates = await cryptoPro.listCertificates();
const cert1 = certificates[0].id;
const cert2 = certificates[1].id;
const coSignature = await cryptoPro.signData2(
dataBase64,
cert1,
cert2,
{
attached: false,
pin: "12345", // PIN for first certificate
pin2: "67890" // PIN for second certificate
}
);
console.log(coSignature);
// Output: CMS with signatures from both certificates
// CryptoPro - Add signature to existing signature
const additionalSignature = await cryptoPro.addSign(
dataBase64,
coSignature,
certificates[2].id, // Third certificate
{
attached: false,
pin: "11111"
}
);
// RuToken - Add signature to existing CMS
const firstSignature = await rutoken.signData(dataBase64, certId, {
attached: false
});
const secondCertId = (await rutoken.listCertificates())[1].id;
const coSignedCms = await rutoken.addSign(
dataBase64,
firstSignature,
secondCertId,
{
attached: false
}
);
console.log(coSignedCms);
// Output: CMS with multiple signatures
```
--------------------------------
### List Available Certificates from Cryptographic Providers
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Retrieves a list of all certificates that have associated private keys from the currently configured cryptographic provider. The output includes details such as certificate ID, name, subject, and validity period.
```javascript
// List certificates (all providers have similar interface)
const certificates = await cryptoPro.listCertificates();
certificates.forEach(cert => {
console.log(`ID: ${cert.id}`);
console.log(`Name: ${cert.name}`);
console.log(`Subject: ${cert.subject.toString()}`);
console.log(`Valid From: ${cert.validFrom}`);
console.log(`Valid To: ${cert.validTo}`);
console.log('---');
});
// Access specific certificate
const firstCert = certificates[0];
const certId = firstCert.id;
```
--------------------------------
### Create and Format Distinguished Names (DN) with RusCryptoJS
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Illustrates how to use the DN class from RusCryptoJS to create and format X.500 Distinguished Names, including standard and custom fields. Shows how to convert the DN object to a string representation.
```javascript
import { DN } from 'ruscryptojs';
// Create Distinguished Name with Russian GOST fields
const dn = new DN();
dn.CN = "Иванов Иван Иванович"; // Common Name
dn.O = "ООО Компания"; // Organization
dn.OU = "IT отдел"; // Organizational Unit
dn.C = "RU"; // Country
dn.S = "77 Москва"; // State/Province
dn.L = "Москва"; // Locality
dn.STREET = "ул. Ленина, д. 1"; // Street Address
dn.E = "ivan@company.ru"; // Email
dn.INN = "7712345678"; // Individual Taxpayer Number
dn.OGRN = "1234567890123"; // Primary State Registration Number
dn.SNILS = "12345678901"; // Insurance Number
dn.INNLE = "7712345678"; // Legal Entity INN (requires CSP 5.0+)
dn.OGRNIP = "123456789012345"; // Sole Proprietor OGRN
// Convert to string with proper formatting
console.log(dn.toString());
// Output: CN="Иванов Иван Иванович", O="ООО Компания", OU="IT отдел",
// C=RU, S="77 Москва", L="Москва", STREET="ул. Ленина, д. 1",
// E=ivan@company.ru, INN=7712345678, OGRN=1234567890123,
// SNILS=12345678901
// DN accepts any custom fields
dn.customField = "Custom Value";
```
--------------------------------
### Decrypt Data using Private Key with CryptoPro, JaCarta-2, and RuToken
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Demonstrates how to decrypt data using a private key associated with a certificate container. It covers the process for CryptoPro, JaCarta-2, and RuToken, including necessary bindings and handling of base64 encoded data. Errors during decryption are also handled.
```javascript
// CryptoPro - Decrypt data
const decryptedBase64 = await cryptoPro.decryptData(
encryptedData,
certId,
"12345" // Optional PIN code
);
const decrypted = decodeURIComponent(escape(atob(decryptedBase64)));
console.log(decrypted);
// Output: "Confidential information"
// JaCarta-2 - Decrypt data
await jacarta2.bind("1234");
const decrypted2Base64 = await jacarta2.decryptData(encrypted2, containerId);
const decrypted2 = decodeURIComponent(escape(atob(decrypted2Base64)));
console.log(decrypted2);
// RuToken - Decrypt data
await rutoken.bind("1234");
const decrypted3Base64 = await rutoken.decryptData(encrypted3, certId);
const decrypted3 = decodeURIComponent(escape(atob(decrypted3Base64)));
console.log(decrypted3);
// Handle decryption errors
try {
const result = await cryptoPro.decryptData(encryptedData, wrongCertId);
} catch (error) {
console.error("Decryption failed:", error.message);
// Output: "Decryption failed: Нет доступа к закрытому ключу [0x8009000D]"
}
```
--------------------------------
### Handle Cryptographic Provider Errors with RusCryptoJS
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Demonstrates robust error handling for cryptographic operations using RusCryptoJS. It shows how to catch and log specific errors during initialization, signing, and token binding for CryptoPro, JaCarta-2, and RuToken, including extracting error codes.
```javascript
import { CryptoPro } from 'ruscryptojs';
const cryptoPro = new CryptoPro();
try {
await cryptoPro.init();
} catch (error) {
console.error("Initialization failed:", error.message);
// Output: "КриптоПро ЭЦП Browser plug-in не обнаружен"
}
try {
const signature = await cryptoPro.signData(dataBase64, "invalid-thumbprint", {
attached: false
});
} catch (error) {
console.error("Signing failed:", error.message);
// Possible outputs:
// "Не удается найти сертификат и закрытый ключ [0x8009200B]"
// "Истекла лицензия на КриптоПро CSP [0x8007065B]"
// "Не удается построить цепочку сертификатов [0x800B010A]"
// "Нет доступа к закрытому ключу [0x8009000D]"
// Error code is included in square brackets
const errorCode = error.message.match(/[0x[0-9A-F]+]/i);
if (errorCode) {
console.log("Error code:", errorCode[0]);
}
}
// JaCarta-2 error handling
try {
await jacarta2.init();
} catch (error) {
console.error("JaCarta error:", error.message);
// Examples:
// "Нет подключенных токенов"
// "Подключено 2 токена(ов)"
// "Подключен токен недопустимого типа: 0"
}
// RuToken error handling
try {
await rutoken.bind("wrong-pin");
} catch (error) {
console.error("RuToken error:", error.message);
// Examples:
// "Введен неверный PIN-код"
// "PIN-код заблокирован"
// "Не обнаружено подключенных устройств"
}
```
--------------------------------
### Create Attached Digital Signatures (JavaScript)
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Creates attached digital signatures where the data is included within the signature itself. Supports CryptoPro, JaCarta-2, and RuToken. The output is a base64 CMS with embedded data.
```javascript
// CryptoPro - Attached signature
const attachedSignature = await cryptoPro.signData(dataBase64, certId, {
attached: true,
pin: "12345"
});
console.log(attachedSignature);
// Output: Base64 CMS with embedded data
// JaCarta-2 - Attached signature
const attachedSig2 = await jacarta2.signData(dataBase64, containerId, {
attached: true
});
// RuToken - Attached signature
const attachedSig3 = await rutoken.signData(dataBase64, certId, {
attached: true
});
```
--------------------------------
### Clean Hardware Tokens (JaCarta-2 and RuToken)
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Provides code to erase all containers and certificates from hardware tokens. This functionality is demonstrated for JaCarta-2 and RuToken. It includes warnings about the destructive nature of these operations and emphasizes the need for user confirmation.
```javascript
// JaCarta-2 - Clean all containers
await jacarta2.init();
await jacarta2.bind("1234");
await jacarta2.clean();
console.log("All containers removed from JaCarta token");
await jacarta2.unbind();
// RuToken - Clean token
await rutoken.init();
await rutoken.bind("1234");
const deletedCount = await rutoken.clean();
console.log(`Deleted ${deletedCount} certificate(s) and key pair(s)`);
// Output: Deleted 3 certificate(s) and key pair(s)
await rutoken.unbind();
// Warning: These operations are destructive and cannot be undone!
// Always confirm with user before cleaning tokens
```
--------------------------------
### TypeScript Definitions for ruscryptojs Providers and Interfaces
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Provides comprehensive TypeScript type definitions for various providers (CryptoPro, JaCarta2, RuToken) and interfaces used within the ruscryptojs library. This enables full type safety when developing with TypeScript, ensuring correct usage of methods and types for cryptographic operations.
```typescript
import {
CryptoPro,
JaCarta2,
RuToken,
DN,
InitResultInterface,
CSRInterface,
CSROptionsInterface,
CertificateInfoInterface,
CertListItemInterface,
SignOptionsInterface
} from 'ruscryptojs';
// Use with TypeScript for full type safety
async function typedExample(): Promise {
const cryptoPro: CryptoPro = new CryptoPro();
const initResult: InitResultInterface = await cryptoPro.init();
const dn: DN = new DN();
dn.CN = "Test User";
const csrResult: CSRInterface = await cryptoPro.generateCSR(dn);
const csr: string = csrResult.csr;
const certs: CertListItemInterface[] = await cryptoPro.listCertificates();
const certInfo: CertificateInfoInterface = await cryptoPro.certificateInfo(
certs[0].id
);
const signOptions: SignOptionsInterface = {
attached: false,
pin: "12345"
};
const signature: string = await cryptoPro.signData(
"data",
certs[0].id,
signOptions
);
const isValid: boolean = await cryptoPro.verifySign(
"data",
signature,
signOptions
);
}
```
--------------------------------
### Generate GOST CSRs with CryptoPro, JaCarta-2, RuToken
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Generates GOST-compliant Certificate Signing Requests (CSRs) using different cryptographic providers. Each provider has specific initialization and generation methods, and options for algorithm, PIN, and descriptive markers.
```javascript
import { CryptoPro, JaCarta2, RuToken, DN } from 'ruscryptojs';
// CryptoPro CSR Generation - GOST R 34.10-2012
const cryptoPro = new CryptoPro();
await cryptoPro.init();
const dn = new DN();
dn.CN = "Петров Петр Петрович";
dn.O = "ООО Техно";
dn.C = "RU";
dn.SNILS = "98765432109";
// Generate CSR with GOST-2012 (80) or GOST-2001 (75)
const ekuOids = [
"1.3.6.1.5.5.7.3.2", // Client Authentication
"1.3.6.1.5.5.7.3.4" // Email Protection
];
const { csr } = await cryptoPro.generateCSR(dn, ekuOids, {
providerType: 80, // GOST R 34.10-2012 (256 bit)
pin: "12345" // Optional: PIN code for container
});
console.log(csr);
// JaCarta-2 CSR Generation
const jacarta2 = new JaCarta2();
await jacarta2.init();
await jacarta2.bind("1234"); // User PIN
const dn2 = new DN();
dn2.CN = "Сидоров Сидор Сидорович";
dn2.O = "ООО Альфа";
const { csr: csr2, keyPairId } = await jacarta2.generateCSR(dn2, ekuOids, {
algorithm: "GOST-2012-256", // or "GOST-2001"
description: "Ключ для подписи документов"
});
console.log(keyPairId); // Output: 1 (key pair identifier)
console.log(csr2); // Output: Base64 CSR string
// RuToken CSR Generation with marker
const rutoken = new RuToken();
await rutoken.init();
await rutoken.bind("1234");
const { csr: csr3, keyPairId: certId } = await rutoken.generateCSR(dn, ekuOids, {
algorithm: "GOST3410_2012_256", // or "GOST3410_2001"
marker: "Signing Key 2025"
});
console.log(certId); // Output: Certificate ID string
await rutoken.unbind();
```
--------------------------------
### Create Detached Digital Signatures (JavaScript)
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Generates detached digital signatures for given data using CryptoPro, JaCarta-2, or RuToken. The input data must be base64 encoded. The output is a base64 encoded CMS signature (PKCS#7).
```javascript
// Prepare data to sign (must be base64)
const data = "Important document content";
const dataBase64 = btoa(unescape(encodeURIComponent(data)));
// CryptoPro - Create detached signature
const signature = await cryptoPro.signData(dataBase64, certId, {
attached: false, // Detached signature
pin: "12345" // Optional PIN (cached if bind() was called)
});
console.log(signature);
// Output: Base64-encoded CMS signature (PKCS#7)
// MIIGBgYJKoZIhvcNAQcCoIIF9zCCBfMCAQExDjAMBg...
// JaCarta-2 - Create detached signature
await jacarta2.bind("1234");
const signature2 = await jacarta2.signData(dataBase64, containerId, {
attached: false
});
// RuToken - Create detached signature
await rutoken.bind("1234");
const signature3 = await rutoken.signData(dataBase64, certId, {
attached: false
});
```
--------------------------------
### Verify Digital Signatures (JavaScript)
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Verifies the integrity of both detached and attached digital signatures. It returns a boolean indicating validity. Includes error handling for invalid signatures and supports CryptoPro, JaCarta-2, and RuToken.
```javascript
// Verify detached signature
const isValid = await cryptoPro.verifySign(dataBase64, signature, {
attached: false
});
console.log(isValid);
// Output: true (if signature is valid) or false
// Verify attached signature (data can be empty string)
const isValidAttached = await cryptoPro.verifySign("", attachedSignature, {
attached: true
});
console.log(isValidAttached);
// Output: true or false
// Error handling for invalid signatures
try {
const result = await cryptoPro.verifySign(dataBase64, "invalid-signature", {
attached: false
});
} catch (error) {
console.error("Signature verification failed:", error.message);
// Output: "Signature verification failed: Не удается найти объект или свойство [0x80092004]"
}
// JaCarta-2 and RuToken verification
const isValid2 = await jacarta2.verifySign(dataBase64, signature2, {
attached: false
});
const isValid3 = await rutoken.verifySign(dataBase64, signature3, {
attached: false
});
```
--------------------------------
### Encrypt Data (JavaScript)
Source: https://context7.com/aleksandr-ru/ruscryptojs/llms.txt
Encrypts sensitive data using the recipient's public key, generating a base64-encoded CMS EnvelopedData. Supports CryptoPro, JaCarta-2, and RuToken. Data to be encrypted must be base64 encoded.
```javascript
// CryptoPro - Encrypt data
const sensitiveData = "Confidential information";
const sensitiveDataBase64 = btoa(unescape(encodeURIComponent(sensitiveData)));
const encryptedData = await cryptoPro.encryptData(
sensitiveDataBase64,
certId // Recipient certificate thumbprint
);
console.log(encryptedData);
// Output: Base64-encoded CMS EnvelopedData
// MIIBsAYJKoZIhvcNAQcDoIIBoTCCAZ0CAQAxggE...
// JaCarta-2 - Encrypt data
await jacarta2.bind("1234");
const encrypted2 = await jacarta2.encryptData(sensitiveDataBase64, containerId);
console.log(encrypted2);
// Output: Base64 encrypted CMS
// RuToken - Encrypt data
await rutoken.bind("1234");
const encrypted3 = await rutoken.encryptData(sensitiveDataBase64, certId);
console.log(encrypted3);
// Output: Base64 encrypted CMS
// Encrypt for multiple recipients (CryptoPro)
// Note: Use multiple certificates by chaining operations or
// using underlying CAdES API for advanced scenarios
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.