Compare commits

...

9 Commits

Author SHA1 Message Date
4f0e3504d1 For bug 68532 2024-07-08 01:53:47 +03:00
f70b5c0939 Merge pull request #1580 from ONLYOFFICE/hotfix/v8.1.1
Hotfix/v8.1.1
2024-06-27 23:34:50 -07:00
e674248d94 Add plugin for private rooms without desktop 2024-01-10 18:48:49 +03:00
522564eb72 Develop... 2024-01-10 00:08:49 +03:00
498b5da2b6 Rebuild module 2024-01-09 20:29:08 +03:00
39d46ca94e Fix typo 2024-01-09 20:15:49 +03:00
8813f65345 Develop new engone for private rooms 2024-01-09 20:12:09 +03:00
ec12f550af Fix typo 2024-01-09 14:13:37 +03:00
0de4c876af Develop new engone for private rooms 2024-01-09 13:34:42 +03:00
25 changed files with 7657 additions and 1076 deletions

View File

@ -352,7 +352,18 @@
}
this.lockPageNumForFontsLoader(pageIndex, UpdateFontsSource.Page);
let retValue = Module["_GetGlyphs"](this.nativeFile, pageIndex);
let isCrashed = false;
let retValue = null;
try
{
retValue = Module["_GetGlyphs"](this.nativeFile, pageIndex);
}
catch (err)
{
retValue = null;
isCrashed = true;
}
// there is no need to delete the result; this buffer is used as a text buffer
// for text commands on other pages. After receiving ALL text pages,
// you need to call destroyTextInfo()
@ -362,10 +373,11 @@
{
// waiting fonts
retValue = null;
isCrashed = false;
}
if (null == retValue)
return null;
return isCrashed ? [] : null;
let lenArray = new Int32Array(Module["HEAP8"].buffer, retValue, 5);
let len = lenArray[0];

View File

@ -72,27 +72,19 @@ public:
}
public:
std::string Sign(unsigned char* pData, unsigned int nSize)
virtual bool Sign(unsigned char* pData, unsigned int nSize, unsigned char*& pDataDst, unsigned int& nSizeDst)
{
NSOpenSSL::CMemoryData data = NSOpenSSL::Sign(pData, (int)nSize, m_pem_key);
if (!data.Data)
return "";
return false;
char* pBase64 = NULL;
int nBase64Len = 0;
NSFile::CBase64Converter::Encode(data.Data, (int)data.Size, pBase64, nBase64Len, NSBase64::B64_BASE64_FLAG_NONE);
nSizeDst = (unsigned int)data.Size;
pDataDst = new BYTE[nSizeDst];
memcpy(pDataDst, data.Data, nSizeDst);
data.Free();
std::string sReturn(pBase64, nBase64Len);
delete[] pBase64;
return sReturn;
}
virtual std::string Sign(const std::string& sXml)
{
return Sign((BYTE*)sXml.c_str(), (unsigned int)sXml.length());
return true;
}
virtual bool SignPKCS7(unsigned char* pData, unsigned int nSize,

View File

@ -93,7 +93,7 @@
<div id="id_header" style="position:absolute;left:0;top:0;width:100%;height:40px;margin:0px;padding:0px;">
<div id="id_mode_sign" class="tab_mode defaultlable" style="left:0px;">
<div id="id_text_sign">Signerergergwerg</div>
<div id="id_text_sign">Sign</div>
</div>
<div class="tab_separator" style="left:33%;"></div>

View File

@ -4,8 +4,11 @@ import base;
base.replaceInFile("./deploy/engine.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){window.cryptoJS.onLoad();}];");
base.replaceInFile("./deploy/engine.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){window.cryptoJS.onLoad();}];");
base.replaceInFile("./deploy/engine.js", "function getBinaryPromise()", "function getBinaryPromise2()");
base.replaceInFile("./deploy/engine.js", "function getBinaryPromise(", "function getBinaryPromise2(");
base.replaceInFile("./deploy/engine_ie.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){window.cryptoJS.onLoad();}];");
base.replaceInFile("./deploy/engine_ie.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){window.cryptoJS.onLoad();}];");
base.replaceInFile("./deploy/engine_ie.js", "function getBinaryPromise()", "function getBinaryPromise2()");
base.replaceInFile("./deploy/engine_ie.js", "function getBinaryPromise(", "function getBinaryPromise2(");
base.cmd_in_dir("../../../../../../Common/js", "python", ["./min.py", "./../../DesktopEditor/xmlsec/src/wasm/oform_plugin/module/deploy/engine.js", "WHITESPACE_ONLY"])
base.cmd_in_dir("../../../../../../Common/js", "python", ["./min.py", "./../../DesktopEditor/xmlsec/src/wasm/oform_plugin/module/deploy/engine_ie.js", "WHITESPACE_ONLY"])

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -8,7 +8,7 @@
function toBase64(buf)
{
if(typeof buf === "string")
if (typeof buf === "string")
{
let old = buf;
buf = [];
@ -80,31 +80,47 @@
return byteArray;
}
function pointerToString(ptr, isDestroy)
{
if (0 === ptr)
return "";
let end = ptr;
let heap = Module["HEAP8"];
while (heap[end] !== 0)
++end;
let res = "".fromUtf8(heap, ptr, end - ptr);
if (isDestroy === true)
Module["_Crypto_Free"](ptr);
return res;
}
function CryptoJS()
{
this.isModuleInit = false;
};
CryptoJS.prototype.onLoad = function()
{
this.isModuleInit = true;
};
CryptoJS.prototype.generateKeys = function(password, salt)
CryptoJS.prototype.generateKeys = function(alg)
{
if (!this.isModuleInit)
return null;
if (!salt)
salt = toBase64(random(32));
let salt = this.createSalt();
let algPtr = "ed25519".toUtf8Pointer();
let passwordPtr = password.toUtf8Pointer();
let algPtr = alg.toUtf8Pointer();
let saltPtr = salt.toUtf8Pointer();
let keys = Module["_Crypto_CreateKeys"](algPtr.ptr, passwordPtr.ptr, saltPtr.ptr);
let keys = Module["_Crypto_CreateKeys"](algPtr.ptr, saltPtr.ptr);
algPtr.free();
passwordPtr.free();
saltPtr.free();
if (keys === 0)
@ -127,82 +143,250 @@
Module["_Crypto_Free"](keys);
return {
"salt" : salt,
"salt" : salt,
"privateKey" : privateKey,
"publicKey" : publicKey
"publicKey" : publicKey
};
};
CryptoJS.prototype.sign = function(privateKey, password, salt, xml)
CryptoJS.prototype.sign = function(privateKeyEnc, salt, version, xml)
{
if (!this.isModuleInit)
return null;
let privateKeyPtr = privateKey.toUtf8Pointer();
let passwordPtr = password.toUtf8Pointer();
let privateKeyPtr = privateKeyEnc.toUtf8Pointer();
let saltPtr = salt.toUtf8Pointer();
let xmlPtr = xml.toUtf8Pointer();
let signData = Module["_Crypto_Sign"](privateKeyPtr.ptr, passwordPtr.ptr, saltPtr.ptr,
xmlPtr.ptr, xmlPtr.length);
let signData = Module["_Crypto_Sign"](privateKeyPtr.ptr, saltPtr.ptr,
version, xmlPtr.ptr, xmlPtr.length);
privateKeyPtr.free();
passwordPtr.free();
saltPtr.free();
xmlPtr.free();
if (signData === 0)
return null;
let heap = Module["HEAP8"];
let currentStart = signData;
let currentEnd = currentStart;
while (heap[currentEnd] != 0)
currentEnd++;
let signString = "".fromUtf8(heap, currentStart, currentEnd - currentStart);
Module["_Crypto_Free"](signData);
return signString;
return pointerToString(signData, true);
};
CryptoJS.prototype.changePassword = function(privateKey, passwordOld, passwordNew, salt)
CryptoJS.prototype.changePassword = function(privateKeyEnc, salt, version, passwordNew)
{
if (!this.isModuleInit)
return null;
let privateKeyPtr = privateKey.toUtf8Pointer();
let passwordOldPtr = passwordOld.toUtf8Pointer();
let passwordNewPtr = passwordNew.toUtf8Pointer();
let privateKeyPtr = privateKeyEnc.toUtf8Pointer();
let saltPtr = salt.toUtf8Pointer();
let privateKeyEnc = Module["_Crypto_ChangePassword"](privateKeyPtr.ptr,
passwordOldPtr.ptr, passwordNewPtr.ptr, saltPtr.ptr);
let passwordNewPtr = passwordNew.toUtf8Pointer();
let privateKeyEncPtr = Module["_Crypto_ChangePassword"](privateKeyPtr.ptr, saltPtr.ptr, version, passwordNewPtr.ptr);
privateKeyPtr.free();
passwordOldPtr.free();
saltPtr.free();
passwordNewPtr.free();
saltPtr.free();
if (privateKeyEnc === 0)
return null;
return pointerToString(privateKeyEncPtr, true);
};
let heap = Module["HEAP8"];
CryptoJS.prototype.setMasterPassword = function(password)
{
let passwordPtr = password.toUtf8Pointer();
Module["_SetMasterPassword"](passwordPtr.ptr);
passwordPtr.free();
};
let currentStart = privateKeyEnc;
let currentEnd = currentStart;
while (heap[currentEnd] != 0)
currentEnd++;
CryptoJS.prototype.setAesPassword = function(password)
{
let passwordPtr = password.toUtf8Pointer();
Module["_SetAesPassword"](passwordPtr.ptr, 0);
passwordPtr.free();
};
CryptoJS.prototype.aesDecryptChanges = function(version, data)
{
let dataPtr = data.toUtf8Pointer();
let result = Module["_AES_Decode2"](version, dataPtr.ptr, dataPtr.length);
passwordPtr.free();
return pointerToString(result, true);
};
CryptoJS.prototype.aesEncryptChanges = function(version, data)
{
let dataPtr = data.toUtf8Pointer();
let result = Module["_AES_Encode2"](version, dataPtr.ptr, dataPtr.length);
passwordPtr.free();
return pointerToString(result, true);
};
CryptoJS.prototype.createSalt = function()
{
return toBase64(random(32));
};
CryptoJS.prototype.generateSignKeys = function()
{
return this.generateKeys("ed25519");
};
CryptoJS.prototype.generateCryptKeys = function()
{
return this.generateKeys("x25519");
};
CryptoJS.prototype.aesDecrypt = function(version, salt, data)
{
let saltPtr = salt.toUtf8Pointer();
let dataPtr = Module["_malloc"](data.length);
Module["HEAP8"].set(dataPtr, data);
let privateKeyString = "".fromUtf8(heap, currentStart, currentEnd - currentStart);
let buffer = Module["_AES_Decode"](version, 0, saltPtr.ptr, dataPtr, data.length);
saltPtr.free();
Module["_free"](dataPtr);
Module["_Crypto_Free"](privateKeyEnc);
return privateKeyString;
if (!buffer)
return null;
let result = new Uint8Array(Module["HEAPU8"].buffer,
Module["_MemoryBlockGetData"](buffer),
Module["_MemoryBlockGetSize"](buffer));
Module["_MemoryBlockDestroy"](buffer);
return result;
};
CryptoJS.prototype.aesDecryptString = function(version, salt, data)
{
let saltPtr = salt.toUtf8Pointer();
let dataPtr = data.toUtf8Pointer();
let result = Module["_AES_Decode"](version, 0, saltPtr.ptr, dataPtr.ptr, dataPtr.length);
saltPtr.free();
dataPtr.free();
return pointerToString(result, true);
};
CryptoJS.prototype.aesDecryptBase64 = function(version, salt, data)
{
let saltPtr = salt.toUtf8Pointer();
let dataPtr = data.toUtf8Pointer();
let result = Module["_AES_DecodeBase64"](version, saltPtr.ptr, dataPtr.ptr);
saltPtr.free();
dataPtr.free();
return pointerToString(result, true);
};
CryptoJS.prototype.aesEncrypt = function(version, salt, data)
{
let saltPtr = salt.toUtf8Pointer();
let dataPtr = Module["_malloc"](data.length);
Module["HEAP8"].set(data, dataPtr);
let buffer = Module["_AES_Encode"](version, 0, saltPtr.ptr, dataPtr, data.length);
saltPtr.free();
Module["_free"](dataPtr);
if (!buffer)
return null;
let result = new Uint8Array(Module["HEAPU8"].buffer,
Module["_MemoryBlockGetData"](buffer),
Module["_MemoryBlockGetSize"](buffer));
Module["_MemoryBlockDestroy"](buffer);
return result;
};
CryptoJS.prototype.aesEncryptString = function(version, salt, data)
{
let saltPtr = salt.toUtf8Pointer();
let dataPtr = data.toUtf8Pointer();
let result = Module["_AES_Encode"](version, 0, saltPtr.ptr, dataPtr.ptr, dataPtr.length);
saltPtr.free();
dataPtr.free();
return pointerToString(result, true);
};
CryptoJS.prototype.aesEncryptBase64 = function(version, salt, data)
{
let saltPtr = salt.toUtf8Pointer();
let dataPtr = data.toUtf8Pointer();
let result = Module["_AES_EncodeBase64"](version, 0, saltPtr, dataPtr);
saltPtr.free();
dataPtr.free();
return pointerToString(result, true);
};
// Crypt/Decrypt
CryptoJS.prototype.decryptWithPrivateKey = function(version, privateKeyEnc, salt, data)
{
let keyEncPtr = privateKeyEnc.toUtf8Pointer();
let saltPtr = salt.toUtf8Pointer();
let buffer = null;
if (typeof data === "string")
{
let dataPtr = data.toUtf8Pointer();
buffer = Module["_DecryptWithPrivateKeyBase64"](version, keyEncPtr.ptr, saltPtr.ptr, data.ptr, data.length);
dataPtr.free();
}
else
{
let dataPtr = Module["_malloc"](data.length);
Module["HEAP8"].set(data, dataPtr);
buffer = Module["_DecryptWithPrivateKey"](version, keyEncPtr.ptr, saltPtr.ptr, dataPtr, data.length);
Module["_free"](dataPtr);
}
keyEncPtr.free();
return pointerToString(buffer, true);
};
CryptoJS.prototype.cryptWithPublicKey = function(version, publicKey, data)
{
let keyPtr = publicKey.toUtf8Pointer();
let buffer = null;
if (typeof data === "string")
{
let dataPtr = data.toUtf8Pointer();
buffer = Module["_EncryptWithPublicKeyBase64"](version, keyPtr.ptr, data.ptr, data.length);
dataPtr.free();
}
else
{
let dataPtr = Module["_malloc"](data.length);
Module["HEAP8"].set(data, dataPtr);
buffer = Module["_EncryptWithPublicKey"](version, keyPtr.ptr, dataPtr, data.length);
Module["_free"](dataPtr);
}
keyPtr.free();
return pointerToString(buffer, true);
};
window.cryptoJS = new CryptoJS();
window.CryptoJS = {
Version : {
"1" : 0,
"Error" : 1
},
Algorithm : {
ED25519 : "ed25519",
X25519 : "x25519",
}
};
//module
})(window, undefined);

View File

@ -69,11 +69,11 @@ extern "C" {
// Memory
WASM_EXPORT void* Crypto_Malloc(unsigned int size)
{
return ::malloc(size);
return NSOpenSSL::openssl_alloc(size);
}
WASM_EXPORT void Crypto_Free(void* p)
{
if (p) ::free(p);
if (p) NSOpenSSL::openssl_free((unsigned char*)p);
}
#ifndef DISABLE_XMLSEC
@ -189,9 +189,280 @@ WASM_EXPORT void Crypto_DestroyCertificate(void* cert)
#endif
WASM_EXPORT void MemoryBlockDestroy(NSOpenSSL::CMemoryData* block)
{
block->Free();
delete block;
}
WASM_EXPORT unsigned char* MemoryBlockGetData(NSOpenSSL::CMemoryData* block)
{
return block->Data;
}
WASM_EXPORT int MemoryBlockGetSize(NSOpenSSL::CMemoryData* block)
{
return (int)block->Size;
}
char* MemoryBlockToBase64(NSOpenSSL::CMemoryData* block, bool destroy = false)
{
int nLenDst = NSBase64::Base64EncodeGetRequiredLength((int)block->Size, NSBase64::B64_BASE64_FLAG_NOCRLF);
unsigned char* pDataDst = NSOpenSSL::openssl_alloc(nLenDst + 1);
if (FALSE == NSBase64::Base64Encode(block->Data, (int)block->Size, pDataDst, &nLenDst, NSBase64::B64_BASE64_FLAG_NOCRLF))
{
NSOpenSSL::openssl_free(pDataDst);
return NULL;
}
pDataDst[nLenDst] = 0;
if (destroy)
{
block->Free();
delete block;
}
return (char*)pDataDst;
}
std::string g_master_password = "";
BYTE* g_aes_key = NULL;
// methods for private rooms
WASM_EXPORT void SetMasterPassword(const char* password)
{
g_master_password = std::string(password);
}
WASM_EXPORT void SetAesPassword(const char* password, const char* salt)
{
if (NULL != g_aes_key)
NSOpenSSL::openssl_free(g_aes_key);
g_aes_key = NULL;
if (NULL == password)
return;
std::string sPassword = std::string(password);
g_aes_key = NSOpenSSL::PBKDF2_desktop_GCM(std::string(password), salt ? std::string(salt) : "");
}
// AES - decode/encode with master password (g_master_password)
WASM_EXPORT NSOpenSSL::CMemoryData* AES_Decode(int version, const char* password, const char* salt, const unsigned char* data, const int& data_len)
{
std::string pass = (NULL == password) ? g_master_password : std::string(password);
if (pass.empty())
return NULL;
unsigned char* key = NSOpenSSL::PBKDF2_desktop_GCM(pass, std::string(salt));
if (!key)
return NULL;
NSOpenSSL::CMemoryData* buffer = new NSOpenSSL::CMemoryData();
NSOpenSSL::AES_Decrypt_desktop_GCM(key, data, data_len, *buffer);
NSOpenSSL::openssl_free(key);
if (!buffer->Data)
{
delete buffer;
buffer = NULL;
}
return buffer;
}
WASM_EXPORT char* AES_DecodeBase64(int version, const char* password, const char* salt, const char* data_base64)
{
unsigned char* data = NULL;
int data_len = 0;
if (!NSFile::CBase64Converter::Decode(data_base64, (int)strlen(data_base64), data, data_len))
return NULL;
NSOpenSSL::CMemoryData* buffer = AES_Decode(version, password, salt, data, data_len);
if (!buffer)
return NULL;
delete [] data;
return MemoryBlockToBase64(buffer, true);
}
WASM_EXPORT NSOpenSSL::CMemoryData* AES_Decode2(int version, const unsigned char* data, const int& data_len)
{
unsigned char* input_ptr = NULL;
int input_ptr_len = 0;
bool bBase64 = NSFile::CBase64Converter::Decode((char*)data, data_len, input_ptr, input_ptr_len);
if (!bBase64)
return NULL;
NSOpenSSL::CMemoryData buffer;
bool bResult = AES_Decrypt_desktop_GCM(g_aes_key, input_ptr, input_ptr_len, buffer);
RELEASEARRAYOBJECTS(input_ptr);
if (!bResult)
return NULL;
NSOpenSSL::CMemoryData* result = new NSOpenSSL::CMemoryData();
result->Data = buffer.Data;
result->Size = buffer.Size;
return result;
}
WASM_EXPORT NSOpenSSL::CMemoryData* AES_Encode(int version, const char* password, const char* salt, const unsigned char* data, const int& data_len)
{
std::string pass = (NULL == password) ? g_master_password : std::string(password);
if (pass.empty())
return NULL;
unsigned char* key = NSOpenSSL::PBKDF2_desktop_GCM(pass, std::string(salt));
if (!key)
return NULL;
NSOpenSSL::CMemoryData* buffer = new NSOpenSSL::CMemoryData();
NSOpenSSL::AES_Encrypt_desktop_GCM(key, data, data_len, *buffer);
NSOpenSSL::openssl_free(key);
if (!buffer->Data)
{
delete buffer;
buffer = NULL;
}
return buffer;
}
WASM_EXPORT char* AES_EncodeBase64(int version, const char* password, const char* salt, const char* data_base64)
{
unsigned char* data = NULL;
int data_len = 0;
if (!NSFile::CBase64Converter::Decode(data_base64, (int)strlen(data_base64), data, data_len))
return NULL;
NSOpenSSL::CMemoryData* buffer = AES_Encode(version, password, salt, data, data_len);
if (!buffer)
return NULL;
delete [] data;
return MemoryBlockToBase64(buffer, true);
}
WASM_EXPORT NSOpenSSL::CMemoryData* AES_Encode2(int version, const unsigned char* data, const int& data_len)
{
NSOpenSSL::CMemoryData buffer;
bool bResult = AES_Encrypt_desktop_GCM(g_aes_key, data, data_len, buffer);
if (!bResult)
return NULL;
int data_len_base64 = NSBase64::Base64EncodeGetRequiredLength((int)buffer.Size, NSBase64::B64_BASE64_FLAG_NOCRLF);
char* data_base64 = (char*)NSOpenSSL::openssl_alloc(data_len_base64);
if (!data_base64)
{
buffer.Free();
return NULL;
}
if (!NSBase64::Base64Encode(buffer.Data, (int)buffer.Size, (BYTE*)data_base64, &data_len_base64, NSBase64::B64_BASE64_FLAG_NOCRLF))
{
buffer.Free();
NSOpenSSL::openssl_free((unsigned char*)data_base64);
return NULL;
}
if (!NSFile::CBase64Converter::Encode(buffer.Data, (int)buffer.Size, data_base64, data_len_base64, NSBase64::B64_BASE64_FLAG_NOCRLF))
{
buffer.Free();
return NULL;
}
NSOpenSSL::CMemoryData* result = new NSOpenSSL::CMemoryData();
result->Data = (unsigned char*)data_base64;
result->Size = (size_t)data_len_base64;
return result;
}
// Crypt/Decrypt
WASM_EXPORT NSOpenSSL::CMemoryData* DecryptWithPrivateKey(const int version, const char* encoded_private_key_base64,
const char* salt, const unsigned char* data, const int data_len)
{
unsigned char* encoded_private_key = NULL;
int encoded_private_key_len = 0;
if (!NSFile::CBase64Converter::Decode(encoded_private_key_base64, (int)strlen(encoded_private_key_base64),
encoded_private_key, encoded_private_key_len))
return NULL;
NSOpenSSL::CMemoryData* buffer = AES_Decode(NULL, salt, NULL, encoded_private_key, encoded_private_key_len);
delete [] encoded_private_key;
if (!buffer)
return NULL;
std::string private_key = std::string((char*)buffer->Data, buffer->Size);
buffer->Free();
delete buffer;
NSOpenSSL::CMemoryData res = NSOpenSSL::Decrypt(data, data_len, private_key);
NSOpenSSL::CMemoryData* result = new NSOpenSSL::CMemoryData();
result->Data = res.Data;
result->Size = res.Size;
return result;
}
WASM_EXPORT NSOpenSSL::CMemoryData* DecryptWithPrivateKeyBase64(const int version, const char* encoded_private_key_base64,
const char* salt, const char* data_base64, const int data_len_base64)
{
unsigned char* data = NULL;
int data_len = 0;
if (!NSFile::CBase64Converter::Decode(data_base64, data_len_base64, data, data_len))
return NULL;
NSOpenSSL::CMemoryData* result = DecryptWithPrivateKey(version, encoded_private_key_base64, salt, data, data_len);
delete [] data;
return result;
}
WASM_EXPORT NSOpenSSL::CMemoryData* EncryptWithPublicKey(const int version, const char* public_key_base64,
const unsigned char* data, const int data_len)
{
unsigned char* public_key = NULL;
int public_key_len = 0;
if (!NSFile::CBase64Converter::Decode(public_key_base64, (int)strlen(public_key_base64), public_key, public_key_len))
return NULL;
std::string publicKeyStr = std::string((char*)public_key, public_key_len);
delete [] public_key;
NSOpenSSL::CMemoryData res = NSOpenSSL::Enrypt(data, data_len, publicKeyStr);
NSOpenSSL::CMemoryData* result = new NSOpenSSL::CMemoryData();
result->Data = res.Data;
result->Size = res.Size;
return result;
}
WASM_EXPORT NSOpenSSL::CMemoryData* EncryptWithPublicKeyBase64(const int version, const char* publicKey64, const char* data64, const int data64_len)
{
unsigned char* data = NULL;
int data_len = 0;
if (!NSFile::CBase64Converter::Decode(data64, data64_len, data, data_len))
return NULL;
NSOpenSSL::CMemoryData* result = EncryptWithPublicKey(version, publicKey64, data, data_len);
delete [] data;
return result;
}
// methods for oform signatures
// создаем ключи, приватный шифруем паролем, результат - две base64 строки
WASM_EXPORT char* Crypto_CreateKeys(const char* alg, const char* password, const char* salt)
WASM_EXPORT char* Crypto_CreateKeys(const char* alg, const char* salt)
{
std::string publicKey;
std::string privateKey;
@ -200,7 +471,7 @@ WASM_EXPORT char* Crypto_CreateKeys(const char* alg, const char* password, const
return NULL;
std::string privateKeyEnc;
NSOpenSSL::AES_Encrypt_desktop_GCM(password, privateKey, privateKeyEnc, salt);
NSOpenSSL::AES_Encrypt_desktop_GCM(g_master_password, privateKey, privateKeyEnc, salt);
char* pDataPublicBase64 = NULL;
int nDataPublicBase64Len = 0;
@ -219,47 +490,55 @@ WASM_EXPORT char* Crypto_CreateKeys(const char* alg, const char* password, const
return result;
}
WASM_EXPORT char* Crypto_Sign(const char* privateKeyEnc, const char* password, const char* salt, const char* data, int dataLen)
WASM_EXPORT char* Crypto_Sign(const char* encoded_private_key_base64, const char* salt, const int version, const char* data, int data_len)
{
std::string sPrivateKey = NSInternal::DecodePrivateKey(std::string(privateKeyEnc), std::string(password), std::string(salt));
if (sPrivateKey.empty())
unsigned char* encoded_private_key = NULL;
int encoded_private_key_len = 0;
if (!NSFile::CBase64Converter::Decode(encoded_private_key_base64, (int)strlen(encoded_private_key_base64),
encoded_private_key, encoded_private_key_len))
return NULL;
if (0 == dataLen)
dataLen = (int)strlen(data);
NSOpenSSL::CMemoryData* buffer = AES_Decode(version, salt, NULL, encoded_private_key, encoded_private_key_len);
delete [] encoded_private_key;
NSOpenSSL::CMemoryData dataSign = NSOpenSSL::Sign((const unsigned char*)data, dataLen, sPrivateKey);
int nDataSignBase64Len = NSBase64::Base64EncodeGetRequiredLength((int)dataSign.Size, NSBase64::B64_BASE64_FLAG_NOCRLF);
char* pDataSignBase64 = (char*)Crypto_Malloc(nDataSignBase64Len + 1);
memset(pDataSignBase64, 0, nDataSignBase64Len + 1);
if (FALSE == NSBase64::Base64Encode(dataSign.Data, (int)dataSign.Size, (BYTE*)pDataSignBase64, &nDataSignBase64Len, NSBase64::B64_BASE64_FLAG_NOCRLF))
{
dataSign.Free();
Crypto_Free((void*)pDataSignBase64);
if (!buffer)
return NULL;
}
dataSign.Free();
return pDataSignBase64;
std::string private_key = std::string((char*)buffer->Data, buffer->Size);
buffer->Free();
delete buffer;
NSOpenSSL::CMemoryData dataSign = NSOpenSSL::Sign((const unsigned char*)data, data_len, private_key);
NSOpenSSL::CMemoryData* result = new NSOpenSSL::CMemoryData();
result->Data = dataSign.Data;
result->Size = dataSign.Size;
return MemoryBlockToBase64(result, true);
}
WASM_EXPORT char* Crypto_ChangePassword(const char* privateKeyEnc, const char* passwordOld, const char* passwordNew, const char* salt)
WASM_EXPORT char* Crypto_ChangePassword(const char* encoded_private_key_base64, const char* salt, int version, const char* password_new)
{
std::string sPrivateKey = NSInternal::DecodePrivateKey(std::string(privateKeyEnc), std::string(passwordOld), std::string(salt));
if (sPrivateKey.empty())
unsigned char* private_key_enc = NULL;
int private_key_enc_len = 0;
if (!NSFile::CBase64Converter::Decode(encoded_private_key_base64, (int)strlen(encoded_private_key_base64), private_key_enc, private_key_enc_len))
return NULL;
std::string sPrivateKeyEnc = "";
NSOpenSSL::AES_Encrypt_desktop_GCM(std::string(passwordNew), sPrivateKey, sPrivateKeyEnc, std::string(salt));
NSOpenSSL::CMemoryData* buffer = AES_Decode(version, NULL, salt, private_key_enc, private_key_enc_len);
delete [] private_key_enc;
size_t nEncLen = sPrivateKeyEnc.length();
char* result = (char*)Crypto_Malloc((unsigned int)(nEncLen + 1));
memcpy(result, sPrivateKeyEnc.c_str(), nEncLen);
result[nEncLen] = '\0';
if (!buffer)
return NULL;
return result;
std::string sOldPassword = g_master_password;
g_master_password = std::string(password_new);
NSOpenSSL::CMemoryData* bufferResult = AES_Encode(version, NULL, salt, buffer->Data, (int)buffer->Size);
buffer->Free();
delete buffer;
g_master_password = sOldPassword;
return MemoryBlockToBase64(bufferResult, true);
}
#ifdef __cplusplus
@ -274,11 +553,14 @@ int main()
if (true)
{
int nVersion = 0;
std::string sSalt = "123546789";
std::string sPassword = "qwerty";
std::string sPasswordNew = "qwerty2";
char* pGeneratedKeys = Crypto_CreateKeys("ed25519", sPassword.c_str(), sSalt.c_str());
SetMasterPassword(sPassword.c_str());
char* pGeneratedKeys = Crypto_CreateKeys("ed25519", sSalt.c_str());
if (NULL == pGeneratedKeys)
return 1;
@ -298,12 +580,12 @@ int main()
std::string sSignData = "hello world!";
char* pSignData = Crypto_Sign(sPrivateKeyEnc.c_str(), sPassword.c_str(), sSalt.c_str(), sSignData.c_str(), (int)sSignData.length());
char* pSignData = Crypto_Sign(sPrivateKeyEnc.c_str(), sSalt.c_str(), 0, sSignData.c_str(), (int)sSignData.length());
std::string sSignature(pSignData);
Crypto_Free(pSignData);
char* pNewPrivateKey = Crypto_ChangePassword(sPrivateKeyEnc.c_str(), sPassword.c_str(), sPasswordNew.c_str(), sSalt.c_str());
char* pNewPrivateKey = Crypto_ChangePassword(sPrivateKeyEnc.c_str(), sSalt.c_str(), nVersion, sPasswordNew.c_str());
std::string sPrivateKeyEncNew(pNewPrivateKey);

View File

@ -0,0 +1,27 @@
{
"name" : "PrivateRoom",
"guid" : "asc.{F2402876-659F-47FB-A646-67B49F2B5715}",
"variations" : [
{
"description" : "onlychain",
"url" : "index.html",
"icons" : ["icon.png", "icon@2x.png", "icon.png", "icon@2x.png"],
"isViewer" : true,
"EditorsSupport" : ["word", "cell", "slide"],
"isVisual" : false,
"isModal" : false,
"isInsideMode" : false,
"initDataType" : "desktop",
"initData" : "encryption",
"cryptoMode" : "2",
"isUpdateOleOnResize" : false,
"buttons" : []
}
]
}

View File

@ -0,0 +1,120 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
(function(window,undefined){var printErr=undefined;var print=undefined;var fetch="undefined"!==typeof window?window.fetch:"undefined"!==typeof self?self.fetch:null;var getBinaryPromise=null;function internal_isLocal(){if(window.navigator&&window.navigator.userAgent.toLowerCase().indexOf("ascdesktopeditor")<0)return false;if(window.location&&window.location.protocol=="file:")return true;if(window.document&&window.document.currentScript&&0==window.document.currentScript.src.indexOf("file:///"))return true;
return false}if(internal_isLocal()){fetch=undefined;getBinaryPromise=function(){var wasmPath="ascdesktop://fonts/"+wasmBinaryFile.substr(8);return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest;xhr.open("GET",wasmPath,true);xhr.responseType="arraybuffer";if(xhr.overrideMimeType)xhr.overrideMimeType("text/plain; charset=x-user-defined");else xhr.setRequestHeader("Accept-Charset","x-user-defined");xhr.onload=function(){if(this.status==200)resolve(new Uint8Array(this.response))};xhr.send(null)})}}else getBinaryPromise=
function(){return getBinaryPromise2.apply(undefined,arguments)};(function(){if(undefined!==String.prototype.fromUtf8&&undefined!==String.prototype.toUtf8)return;var STRING_UTF8_BUFFER_LENGTH=1024;var STRING_UTF8_BUFFER=new ArrayBuffer(STRING_UTF8_BUFFER_LENGTH);String.prototype.fromUtf8=function(buffer,start,len){if(undefined===start)start=0;if(undefined===len)len=buffer.length-start;var result="";var index=start;var end=start+len;while(index<end){var u0=buffer[index++];if(!(u0&128)){result+=String.fromCharCode(u0);
continue}var u1=buffer[index++]&63;if((u0&224)==192){result+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=buffer[index++]&63;if((u0&240)==224)u0=(u0&15)<<12|u1<<6|u2;else u0=(u0&7)<<18|u1<<12|u2<<6|buffer[index++]&63;if(u0<65536)result+=String.fromCharCode(u0);else{var ch=u0-65536;result+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return result};String.prototype.toUtf8=function(isNoEndNull,isUseBuffer){var inputLen=this.length;var testLen=6*inputLen+1;var tmpStrings=isUseBuffer&&testLen<
STRING_UTF8_BUFFER_LENGTH?STRING_UTF8_BUFFER:new ArrayBuffer(testLen);var code=0;var index=0;var outputIndex=0;var outputDataTmp=new Uint8Array(tmpStrings);var outputData=outputDataTmp;while(index<inputLen){code=this.charCodeAt(index++);if(code>=55296&&code<=57343&&index<inputLen)code=65536+((code&1023)<<10|1023&this.charCodeAt(index++));if(code<128)outputData[outputIndex++]=code;else if(code<2048){outputData[outputIndex++]=192|code>>6;outputData[outputIndex++]=128|code&63}else if(code<65536){outputData[outputIndex++]=
224|code>>12;outputData[outputIndex++]=128|code>>6&63;outputData[outputIndex++]=128|code&63}else if(code<2097151){outputData[outputIndex++]=240|code>>18;outputData[outputIndex++]=128|code>>12&63;outputData[outputIndex++]=128|code>>6&63;outputData[outputIndex++]=128|code&63}else if(code<67108863){outputData[outputIndex++]=248|code>>24;outputData[outputIndex++]=128|code>>18&63;outputData[outputIndex++]=128|code>>12&63;outputData[outputIndex++]=128|code>>6&63;outputData[outputIndex++]=128|code&63}else if(code<
2147483647){outputData[outputIndex++]=252|code>>30;outputData[outputIndex++]=128|code>>24&63;outputData[outputIndex++]=128|code>>18&63;outputData[outputIndex++]=128|code>>12&63;outputData[outputIndex++]=128|code>>6&63;outputData[outputIndex++]=128|code&63}}if(isNoEndNull!==true)outputData[outputIndex++]=0;return new Uint8Array(tmpStrings,0,outputIndex)};function StringPointer(pointer,len){this.ptr=pointer;this.length=len}StringPointer.prototype.free=function(){if(0!==this.ptr)Module["_free"](this.ptr)};
String.prototype.toUtf8Pointer=function(isNoEndNull){var tmp=this.toUtf8(isNoEndNull,true);var pointer=Module["_malloc"](tmp.length);if(0==pointer)return null;Module["HEAP8"].set(tmp,pointer);return new StringPointer(pointer,tmp.length)}})();function toBase64(buf){if(typeof buf==="string"){var old=buf;buf=[];for(var i=0,len=old.length;i<len;i++)buf.push(old.charCodeAt(i))}var chars="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var chars_map=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,-1,-1,-1,-1,-1,-1,-1,9,10,11,12,13,14,15,16,-1,17,18,19,20,21,-1,22,23,24,25,26,27,28,29,30,31,32,-1,-1,-1,-1,-1,-1,33,34,35,36,37,38,39,40,41,42,43,-1,44,45,46,47,48,49,50,51,52,53,54,55,56,57,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];var result=[];for(var i$0=0,len$1=buf.length;i$0<len$1;i$0++){var carry=buf[i$0];for(var j=0;j<result.length;++j){var x=(chars_map[result[j]]<<8)+carry;result[j]=chars.charCodeAt(x%58);carry=x/58>>0}while(carry){result.push(chars.charCodeAt(carry%58));carry=carry/58>>0}}var char1="1".charCodeAt(0);
for(var i$2=0,len$3=buf.length;i$2<len$3;i$2++)if(buf[i$2])break;else result.push(char1);result.reverse();return String.fromCharCode.apply(null,result)}function random(length){var byteArray=new Uint8Array(length);var engine=window.crypto||window.msCrypto;if(engine)engine.getRandomValues(byteArray);else for(var i=0;i<length;i++)byteArray[i]=Math.random()*256>>0;return byteArray}function pointerToString(ptr,isDestroy){if(0===ptr)return"";var end=ptr;var heap=Module["HEAP8"];while(heap[end]!==0)++end;
var res="".fromUtf8(heap,ptr,end-ptr);if(isDestroy===true)Module["_Crypto_Free"](ptr);return res}function CryptoJS(){this.isModuleInit=false}CryptoJS.prototype.onLoad=function(){this.isModuleInit=true};CryptoJS.prototype.generateKeys=function(alg){if(!this.isModuleInit)return null;var salt=this.createSalt();var algPtr=alg.toUtf8Pointer();var saltPtr=salt.toUtf8Pointer();var keys=Module["_Crypto_CreateKeys"](algPtr.ptr,saltPtr.ptr);algPtr.free();saltPtr.free();if(keys===0)return null;var heap=Module["HEAP8"];
var currentStart=keys;var currentEnd=currentStart;while(heap[currentEnd]!=0)currentEnd++;var publicKey="".fromUtf8(heap,currentStart,currentEnd-currentStart);currentStart=currentEnd+1;currentEnd=currentStart;while(heap[currentEnd]!=0)currentEnd++;var privateKey="".fromUtf8(heap,currentStart,currentEnd-currentStart);Module["_Crypto_Free"](keys);return{"salt":salt,"privateKey":privateKey,"publicKey":publicKey}};CryptoJS.prototype.sign=function(privateKeyEnc,salt,version,xml){if(!this.isModuleInit)return null;
var privateKeyPtr=privateKeyEnc.toUtf8Pointer();var saltPtr=salt.toUtf8Pointer();var xmlPtr=xml.toUtf8Pointer();var signData=Module["_Crypto_Sign"](privateKeyPtr.ptr,saltPtr.ptr,version,xmlPtr.ptr,xmlPtr.length);privateKeyPtr.free();saltPtr.free();xmlPtr.free();return pointerToString(signData,true)};CryptoJS.prototype.changePassword=function(privateKeyEnc,salt,version,passwordNew){if(!this.isModuleInit)return null;var privateKeyPtr=privateKeyEnc.toUtf8Pointer();var saltPtr=salt.toUtf8Pointer();var passwordNewPtr=
passwordNew.toUtf8Pointer();var privateKeyEncPtr=Module["_Crypto_ChangePassword"](privateKeyPtr.ptr,saltPtr.ptr,version,passwordNewPtr.ptr);privateKeyPtr.free();saltPtr.free();passwordNewPtr.free();return pointerToString(privateKeyEncPtr,true)};CryptoJS.prototype.setMasterPassword=function(password){var passwordPtr=password.toUtf8Pointer();Module["_SetMasterPassword"](passwordPtr);Module["_Crypto_Free"](passwordPtr)};CryptoJS.prototype.createSalt=function(){return toBase64(random(32))};CryptoJS.prototype.generateSignKeys=
function(){return this.generateKeys("ed25519")};CryptoJS.prototype.generateCryptKeys=function(){return this.generateKeys("x25519")};CryptoJS.prototype.aesDecrypt=function(version,salt,data){var saltPtr=salt.toUtf8Pointer();var dataPtr=Module["_malloc"](data.length);Module["HEAP8"].set(dataPtr,data);var buffer=Module["_AES_Decode"](version,saltPtr.ptr,dataPtr,data.length);saltPtr.free();Module["_free"](dataPtr);if(!buffer)return null;var result=new Uint8Array(Module["HEAPU8"].buffer,Module["_MemoryBlockGetData"](buffer),
Module["_MemoryBlockGetSize"](buffer));Module["_MemoryBlockDestroy"](buffer);return result};CryptoJS.prototype.aesDecryptBase64=function(version,salt,data){var saltPtr=salt.toUtf8Pointer();var dataPtr=data.toUtf8Pointer();var result=Module["_AES_DecodeBase64"](version,saltPtr.ptr,dataPtr.ptr);saltPtr.free();dataPtr.free();return pointerToString(result,true)};CryptoJS.prototype.aesEncrypt=function(version,salt,data){var saltPtr=salt.toUtf8Pointer();var dataPtr=Module["_malloc"](data.length);Module["HEAP8"].set(data,
dataPtr);var buffer=Module["_AES_Encode"](version,saltPtr.ptr,dataPtr,data.length);saltPtr.free();Module["_free"](dataPtr);if(!buffer)return null;var result=new Uint8Array(Module["HEAPU8"].buffer,Module["_MemoryBlockGetData"](buffer),Module["_MemoryBlockGetSize"](buffer));Module["_MemoryBlockDestroy"](buffer);return result};CryptoJS.prototype.aesEncryptBase64=function(version,salt,data){var saltPtr=salt.toUtf8Pointer();var dataPtr=data.toUtf8Pointer();var result=Module["_AES_EncodeBase64"](version,
saltPtr,dataPtr);saltPtr.free();dataPtr.free();return pointerToString(result,true)};CryptoJS.prototype.decryptWithPrivateKey=function(version,privateKeyEnc,salt,data){var keyEncPtr=privateKeyEnc.toUtf8Pointer();var saltPtr=salt.toUtf8Pointer();var buffer=null;if(typeof data==="string"){var dataPtr=data.toUtf8Pointer();buffer=Module["_DecryptWithPrivateKeyBase64"](version,keyEncPtr.ptr,saltPtr.ptr,data.ptr,data.length);dataPtr.free()}else{var dataPtr$4=Module["_malloc"](data.length);Module["HEAP8"].set(data,
dataPtr$4);buffer=Module["_DecryptWithPrivateKey"](version,keyEncPtr.ptr,saltPtr.ptr,dataPtr$4,data.length);Module["_free"](dataPtr$4)}keyEncPtr.free();return pointerToString(buffer,true)};CryptoJS.prototype.cryptWithPublicKey=function(version,publicKey,data){var keyPtr=publicKey.toUtf8Pointer();var buffer=null;if(typeof data==="string"){var dataPtr=data.toUtf8Pointer();buffer=Module["_EncryptWithPublicKeyBase64"](version,keyPtr.ptr,data.ptr,data.length);dataPtr.free()}else{var dataPtr$5=Module["_malloc"](data.length);
Module["HEAP8"].set(data,dataPtr$5);buffer=Module["_EncryptWithPublicKey"](version,keyPtr.ptr,dataPtr$5,data.length);Module["_free"](dataPtr$5)}keyPtr.free();return pointerToString(buffer,true)};window.cryptoJS=new CryptoJS;window.CryptoJS={Version:{1:0,"Error":1},Algorithm:{ED25519:"ed25519",X25519:"x25519"}};var Module=typeof Module!="undefined"?Module:{};var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow;
};var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;if(Module["ENVIRONMENT"])throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");var scriptDirectory="";function locateFile(path){if(Module["locateFile"])return Module["locateFile"](path,scriptDirectory);return scriptDirectory+path}var read_,readAsync,readBinary;
if(ENVIRONMENT_IS_SHELL){if(typeof process=="object"&&typeof require==="function"||typeof window=="object"||typeof importScripts=="function")throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");if(typeof read!="undefined")read_=read;readBinary=function(f){if(typeof readbuffer=="function")return new Uint8Array(readbuffer(f));var data=read(f,"binary");
assert(typeof data=="object");return data};readAsync=function(f,onload,onerror){setTimeout(function(){return onload(readBinary(f))})};if(typeof clearTimeout=="undefined")globalThis.clearTimeout=function(id){};if(typeof setTimeout=="undefined")globalThis.setTimeout=function(f){return typeof f=="function"?f():abort()};if(typeof scriptArgs!="undefined")arguments_=scriptArgs;else if(typeof arguments!="undefined")arguments_=arguments;if(typeof quit=="function")quit_=function(status,toThrow){setTimeout(function(){if(!(toThrow instanceof
ExitStatus)){var toLog=toThrow;if(toThrow&&typeof toThrow=="object"&&toThrow.stack)toLog=[toThrow,toThrow.stack];err("exiting due to exception: "+toLog)}quit(status)});throw toThrow;};if(typeof print!="undefined"){if(typeof console=="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER)scriptDirectory=self.location.href;else if(typeof document!="undefined"&&document.currentScript)scriptDirectory=
document.currentScript.src;if(scriptDirectory.indexOf("blob:")!==0)scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1);else scriptDirectory="";if(!(typeof window=="object"||typeof importScripts=="function"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");{read_=function(url){var xhr=new XMLHttpRequest;
xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER)readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)};readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;
xhr.send(null)}}}else throw new Error("environment detection error");var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;checkIncomingModuleAPI();if(Module["arguments"])arguments_=Module["arguments"];legacyModuleProp("arguments","arguments_");if(Module["thisProgram"])thisProgram=Module["thisProgram"];legacyModuleProp("thisProgram","thisProgram");if(Module["quit"])quit_=Module["quit"];
legacyModuleProp("quit","quit_");assert(typeof Module["memoryInitializerPrefixURL"]=="undefined","Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead");assert(typeof Module["pthreadMainPrefixURL"]=="undefined","Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead");assert(typeof Module["cdInitializerPrefixURL"]=="undefined","Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead");assert(typeof Module["filePackagePrefixURL"]==
"undefined","Module.filePackagePrefixURL option was removed, use Module.locateFile instead");assert(typeof Module["read"]=="undefined","Module.read option was removed (modify read_ in JS)");assert(typeof Module["readAsync"]=="undefined","Module.readAsync option was removed (modify readAsync in JS)");assert(typeof Module["readBinary"]=="undefined","Module.readBinary option was removed (modify readBinary in JS)");assert(typeof Module["setWindowTitle"]=="undefined","Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)");
assert(typeof Module["TOTAL_MEMORY"]=="undefined","Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY");legacyModuleProp("asm","wasmExports");legacyModuleProp("read","read_");legacyModuleProp("readAsync","readAsync");legacyModuleProp("readBinary","readBinary");legacyModuleProp("setWindowTitle","setWindowTitle");assert(!ENVIRONMENT_IS_WORKER,"worker environment detected but not enabled at build time. Add 'worker' to `-sENVIRONMENT` to enable.");assert(!ENVIRONMENT_IS_NODE,"node environment detected but not enabled at build time. Add 'node' to `-sENVIRONMENT` to enable.");
assert(!ENVIRONMENT_IS_SHELL,"shell environment detected but not enabled at build time. Add 'shell' to `-sENVIRONMENT` to enable.");var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];legacyModuleProp("wasmBinary","wasmBinary");if(typeof WebAssembly!="object")abort("no native wasm support detected");var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition)abort("Assertion failed"+(text?": "+text:""))}var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,
HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}assert(!Module["STACK_SIZE"],"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time");
assert(typeof Int32Array!="undefined"&&typeof Float64Array!=="undefined"&&Int32Array.prototype.subarray!=undefined&&Int32Array.prototype.set!=undefined,"JS engine does not provide full typed array support");assert(!Module["wasmMemory"],"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally");assert(!Module["INITIAL_MEMORY"],"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically");function writeStackCookie(){var max=_emscripten_stack_get_end();
assert((max&3)==0);if(max==0)max+=4;HEAPU32[max>>2]=34821223;HEAPU32[max+4>>2]=2310721022;HEAPU32[0>>2]=1668509029}function checkStackCookie(){if(ABORT)return;var max=_emscripten_stack_get_end();if(max==0)max+=4;var cookie1=HEAPU32[max>>2];var cookie2=HEAPU32[max+4>>2];if(cookie1!=34821223||cookie2!=2310721022)abort("Stack overflow! Stack cookie has been overwritten at "+ptrToString(max)+", expected hex dwords 0x89BACDFE and 0x2135467, but received "+ptrToString(cookie2)+" "+ptrToString(cookie1));
if(HEAPU32[0>>2]!=1668509029)abort("Runtime error: The application has corrupted its heap memory area (address zero)!")}(function(){var h16=new Int16Array(1);var h8=new Int8Array(h16.buffer);h16[0]=25459;if(h8[0]!==115||h8[1]!==99)throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)";})();var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[function(){window.cryptoJS.onLoad()}];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]==
"function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length)addOnPreRun(Module["preRun"].shift())}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){assert(!runtimeInitialized);runtimeInitialized=true;checkStackCookie();callRuntimeCallbacks(__ATINIT__)}function postRun(){checkStackCookie();if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length)addOnPostRun(Module["postRun"].shift())}callRuntimeCallbacks(__ATPOSTRUN__)}
function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}assert(Math.imul,"This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");assert(Math.fround,"This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");assert(Math.clz32,"This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");
assert(Math.trunc,"This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;var runDependencyTracking={};function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"])Module["monitorRunDependencies"](runDependencies);if(id){assert(!runDependencyTracking[id]);runDependencyTracking[id]=1;if(runDependencyWatcher===null&&typeof setInterval!=
"undefined")runDependencyWatcher=setInterval(function(){if(ABORT){clearInterval(runDependencyWatcher);runDependencyWatcher=null;return}var shown=false;for(var dep in runDependencyTracking){if(!shown){shown=true;err("still waiting on run dependencies:")}err("dependency: "+dep)}if(shown)err("(end of list)")},1E4)}else err("warning: run dependency added without ID")}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"])Module["monitorRunDependencies"](runDependencies);
if(id){assert(runDependencyTracking[id]);delete runDependencyTracking[id]}else err("warning: run dependency removed without ID");if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){if(Module["onAbort"])Module["onAbort"](what);what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;var e=new WebAssembly.RuntimeError(what);
throw e;}var FS={error:function(){abort("Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM")},init:function(){FS.error()},createDataFile:function(){FS.error()},createPreloadedFile:function(){FS.error()},createLazyFile:function(){FS.error()},open:function(){FS.error()},mkdev:function(){FS.error()},registerDevice:function(){FS.error()},
analyzePath:function(){FS.error()},ErrnoError:function(){FS.error()}};Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;var dataURIPrefix="data:application/octet-stream;base64,";var isDataURI=function(filename){return filename.startsWith(dataURIPrefix)};var isFileURI=function(filename){return filename.startsWith("file://")};function createExportWrapper(name){return function(){assert(runtimeInitialized,"native function `"+name+"` called before runtime initialization");
var f=wasmExports[name];assert(f,"exported native function `"+name+"` not found");return f.apply(null,arguments)}}var wasmBinaryFile;wasmBinaryFile="engine.wasm";if(!isDataURI(wasmBinaryFile))wasmBinaryFile=locateFile(wasmBinaryFile);function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(file);throw"both async and sync fetching of the wasm failed";}function getBinaryPromise2(binaryFile){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||
ENVIRONMENT_IS_WORKER))if(typeof fetch=="function")return fetch(binaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"])throw"failed to load wasm binary file at '"+binaryFile+"'";return response["arrayBuffer"]()}).catch(function(){return getBinarySync(binaryFile)});return Promise.resolve().then(function(){return getBinarySync(binaryFile)})}function instantiateArrayBuffer(binaryFile,imports,receiver){return getBinaryPromise(binaryFile).then(function(binary){return WebAssembly.instantiate(binary,
imports)}).then(function(instance){return instance}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);if(isFileURI(wasmBinaryFile))err("warning: Loading from a file URI ("+wasmBinaryFile+") is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing");abort(reason)})}function instantiateAsync(binary,binaryFile,imports,callback){if(!binary&&
typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&typeof fetch=="function")return fetch(binaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,imports);return result.then(callback,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(binaryFile,imports,callback)})});return instantiateArrayBuffer(binaryFile,imports,callback)}
function createWasm(){var info={"env":wasmImports,"wasi_snapshot_preview1":wasmImports};function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["memory"];assert(wasmMemory,"memory not found in wasm exports");updateMemoryViews();addOnInit(wasmExports["__wasm_call_ctors"]);removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");var trueModule=Module;function receiveInstantiationResult(result){assert(Module===trueModule,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?");
trueModule=null;receiveInstance(result["instance"])}if(Module["instantiateWasm"])try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}instantiateAsync(wasmBinary,wasmBinaryFile,info,receiveInstantiationResult);return{}}function legacyModuleProp(prop,newName,incomming){incomming=incomming===void 0?true:incomming;if(!Object.getOwnPropertyDescriptor(Module,prop))Object.defineProperty(Module,prop,{configurable:true,
get:function(){var extra=incomming?" (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)":"";abort("`Module."+prop+"` has been replaced by `"+newName+"`"+extra)}})}function ignoredModuleProp(prop){if(Object.getOwnPropertyDescriptor(Module,prop))abort("`Module."+prop+"` was supplied but `"+prop+"` not included in INCOMING_MODULE_JS_API")}function isExportedByForceFilesystem(name){return name==="FS_createPath"||name==="FS_createDataFile"||
name==="FS_createPreloadedFile"||name==="FS_unlink"||name==="addRunDependency"||name==="FS_createLazyFile"||name==="FS_createDevice"||name==="removeRunDependency"}function missingGlobal(sym,msg){if(typeof globalThis!=="undefined")Object.defineProperty(globalThis,sym,{configurable:true,get:function(){warnOnce("`"+sym+"` is not longer defined by emscripten. "+msg);return undefined}})}missingGlobal("buffer","Please use HEAP8.buffer or wasmMemory.buffer");missingGlobal("asm","Please use wasmExports instead");
function missingLibrarySymbol(sym){if(typeof globalThis!=="undefined"&&!Object.getOwnPropertyDescriptor(globalThis,sym))Object.defineProperty(globalThis,sym,{configurable:true,get:function(){var msg="`"+sym+"` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line";var librarySymbol=sym;if(!librarySymbol.startsWith("_"))librarySymbol="$"+sym;msg+=" (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='"+librarySymbol+"')";if(isExportedByForceFilesystem(sym))msg+=
". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";warnOnce(msg);return undefined}});unexportedRuntimeSymbol(sym)}function unexportedRuntimeSymbol(sym){if(!Object.getOwnPropertyDescriptor(Module,sym))Object.defineProperty(Module,sym,{configurable:true,get:function(){var msg="'"+sym+"' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)";if(isExportedByForceFilesystem(sym))msg+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";
abort(msg)}})}function js_random(buf,num){var byteArray=new Uint8Array(num);var engine=self.crypto||self.msCrypto;engine.getRandomValues(byteArray);Module["HEAP8"].set(byteArray,buf);return 1}function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}var callRuntimeCallbacks=function(callbacks){while(callbacks.length>0)callbacks.shift()(Module)};var noExitRuntime=Module["noExitRuntime"]||true;var ptrToString=function(ptr){assert(typeof ptr===
"number");ptr>>>=0;return"0x"+ptr.toString(16).padStart(8,"0")};var warnOnce=function(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}};function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24;this.set_type=function(type){HEAPU32[this.ptr+4>>2]=type};this.get_type=function(){return HEAPU32[this.ptr+4>>2]};this.set_destructor=function(destructor){HEAPU32[this.ptr+8>>2]=destructor};this.get_destructor=function(){return HEAPU32[this.ptr+
8>>2]};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+12>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+12>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+13>>0]!=0};this.init=function(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)};this.set_adjusted_ptr=function(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr};this.get_adjusted_ptr=
function(){return HEAPU32[this.ptr+16>>2]};this.get_exception_ptr=function(){var isPointer=___cxa_is_pointer_type(this.get_type());if(isPointer)return HEAPU32[this.excPtr>>2];var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.excPtr}}var exceptionLast=0;var uncaughtExceptionCount=0;var ___cxa_throw=function(ptr,type,destructor){var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;assert(false,"Exception thrown, but exception catching is not enabled. Compile with -sNO_DISABLE_EXCEPTION_CATCHING or -sEXCEPTION_CATCHING_ALLOWED=[..] to catch.")};
var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;var UTF8ArrayToString=function(heapOrArray,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder)return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr));var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==
192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224)u0=(u0&15)<<12|u1<<6|u2;else{if((u0&248)!=240)warnOnce("Invalid UTF-8 leading byte "+ptrToString(u0)+" encountered when deserializing a UTF-8 string in wasm memory to a JS string!");u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536)str+=String.fromCharCode(u0);else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=function(ptr,maxBytesToRead){assert(typeof ptr==
"number","UTF8ToString expects a number (got "+typeof ptr+")");return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""};var SYSCALLS={varargs:undefined,get:function(){assert(SYSCALLS.varargs!=undefined);var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret},getp:function(){return SYSCALLS.get()},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;return 0}var ___syscall_fstat64=function(fd,buf){abort("it should not be possible to operate on streams when !SYSCALLS_REQUIRE_FILESYSTEM")};
var stringToUTF8Array=function(str,heap,outIdx,maxBytesToWrite){assert(typeof str==="string","stringToUTF8Array expects a string (got "+typeof str+")");if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=
128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;if(u>1114111)warnOnce("Invalid Unicode code point "+ptrToString(u)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).");heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};
var ___syscall_getdents64=function(fd,dirp,count){abort("it should not be possible to operate on streams when !SYSCALLS_REQUIRE_FILESYSTEM")};function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;return 0}var ___syscall_lstat64=function(path,buf){abort("it should not be possible to operate on streams when !SYSCALLS_REQUIRE_FILESYSTEM")};var ___syscall_newfstatat=function(dirfd,path,buf,flags){abort("it should not be possible to operate on streams when !SYSCALLS_REQUIRE_FILESYSTEM")};function ___syscall_openat(dirfd,
path,flags,varargs){SYSCALLS.varargs=varargs;abort("it should not be possible to operate on streams when !SYSCALLS_REQUIRE_FILESYSTEM")}var ___syscall_stat64=function(path,buf){abort("it should not be possible to operate on streams when !SYSCALLS_REQUIRE_FILESYSTEM")};var nowIsMonotonic=true;var __emscripten_get_now_is_monotonic=function(){return nowIsMonotonic};var convertI32PairToI53Checked=function(lo,hi){assert(lo==lo>>>0||lo==(lo|0));assert(hi===(hi|0));return hi+2097152>>>0<4194305-!!lo?(lo>>>
0)+hi*4294967296:NaN};function __munmap_js(addr,len,prot,flags,fd,offset_low,offset_high){var offset=convertI32PairToI53Checked(offset_low,offset_high)}var _abort=function(){abort("native code called abort()")};var _emscripten_date_now=function(){return Date.now()};var _emscripten_get_now;_emscripten_get_now=function(){return performance.now()};var _emscripten_memcpy_js=function(dest,src,num){return HEAPU8.copyWithin(dest,src,src+num)};var getHeapMax=function(){return 2147483648};var growMemory=function(size){var b=
wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){err("growMemory: Attempted to grow heap from "+b.byteLength+" bytes to "+size+" bytes, but got error: "+e)}};var _emscripten_resize_heap=function(requestedSize){var oldSize=HEAPU8.length;requestedSize>>>=0;assert(requestedSize>oldSize);var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){err("Cannot enlarge memory, requested "+requestedSize+" bytes, but the limit is "+
maxHeapSize+" bytes!");return false}var alignUp=function(x,multiple){return x+(multiple-x%multiple)%multiple};for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement)return true}err("Failed to grow the heap from "+oldSize+" bytes to "+newSize+" bytes, not enough memory!");
return false};var ENV={};var getExecutableName=function(){return thisProgram||"./this.program"};var getEnvStrings=function(){if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV)if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x];var strings=[];for(var x in env)strings.push(x+
"="+env[x]);getEnvStrings.strings=strings}return getEnvStrings.strings};var stringToAscii=function(str,buffer){for(var i=0;i<str.length;++i){assert(str.charCodeAt(i)===(str.charCodeAt(i)&255));HEAP8[buffer++>>0]=str.charCodeAt(i)}HEAP8[buffer>>0]=0};var _environ_get=function(__environ,environ_buf){var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=function(penviron_count,
penviron_buf_size){var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){return bufSize+=string.length+1});HEAPU32[penviron_buf_size>>2]=bufSize;return 0};var _fd_close=function(fd){abort("fd_close called without SYSCALLS_REQUIRE_FILESYSTEM")};var _fd_read=function(fd,iov,iovcnt,pnum){abort("fd_read called without SYSCALLS_REQUIRE_FILESYSTEM")};function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,
offset_high);return 70}var printCharBuffers=[null,[],[]];var printChar=function(stream,curr){var buffer=printCharBuffers[stream];assert(buffer);if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else buffer.push(curr)};var flush_NO_FILESYSTEM=function(){_fflush(0);if(printCharBuffers[1].length)printChar(1,10);if(printCharBuffers[2].length)printChar(2,10)};var _fd_write=function(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=
HEAPU32[iov+4>>2];iov+=8;for(var j=0;j<len;j++)printChar(fd,HEAPU8[ptr+j]);num+=len}HEAPU32[pnum>>2]=num;return 0};function checkIncomingModuleAPI(){ignoredModuleProp("fetchSettings")}var wasmImports={__cxa_throw:___cxa_throw,__syscall_fcntl64:___syscall_fcntl64,__syscall_fstat64:___syscall_fstat64,__syscall_getdents64:___syscall_getdents64,__syscall_ioctl:___syscall_ioctl,__syscall_lstat64:___syscall_lstat64,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_stat64:___syscall_stat64,
_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_munmap_js:__munmap_js,abort:_abort,emscripten_date_now:_emscripten_date_now,emscripten_get_now:_emscripten_get_now,emscripten_memcpy_js:_emscripten_memcpy_js,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,fd_close:_fd_close,fd_read:_fd_read,fd_seek:_fd_seek,fd_write:_fd_write,js_random:js_random};var wasmExports=createWasm();var ___wasm_call_ctors=createExportWrapper("__wasm_call_ctors");
var _malloc=Module["_malloc"]=createExportWrapper("malloc");var _free=Module["_free"]=createExportWrapper("free");var ___errno_location=createExportWrapper("__errno_location");var _ntohs=createExportWrapper("ntohs");var _fflush=Module["_fflush"]=createExportWrapper("fflush");var _Crypto_Malloc=Module["_Crypto_Malloc"]=createExportWrapper("Crypto_Malloc");var _Crypto_Free=Module["_Crypto_Free"]=createExportWrapper("Crypto_Free");var _Crypto_CreateKeys=Module["_Crypto_CreateKeys"]=createExportWrapper("Crypto_CreateKeys");
var _Crypto_Sign=Module["_Crypto_Sign"]=createExportWrapper("Crypto_Sign");var _Crypto_ChangePassword=Module["_Crypto_ChangePassword"]=createExportWrapper("Crypto_ChangePassword");var _htonl=createExportWrapper("htonl");var _htons=createExportWrapper("htons");var setTempRet0=createExportWrapper("setTempRet0");var _emscripten_stack_init=function(){return(_emscripten_stack_init=wasmExports["emscripten_stack_init"])()};var _emscripten_stack_get_free=function(){return(_emscripten_stack_get_free=wasmExports["emscripten_stack_get_free"])()};
var _emscripten_stack_get_base=function(){return(_emscripten_stack_get_base=wasmExports["emscripten_stack_get_base"])()};var _emscripten_stack_get_end=function(){return(_emscripten_stack_get_end=wasmExports["emscripten_stack_get_end"])()};var stackSave=createExportWrapper("stackSave");var stackRestore=createExportWrapper("stackRestore");var stackAlloc=createExportWrapper("stackAlloc");var _emscripten_stack_get_current=function(){return(_emscripten_stack_get_current=wasmExports["emscripten_stack_get_current"])()};
var ___cxa_is_pointer_type=createExportWrapper("__cxa_is_pointer_type");var dynCall_jiiii=Module["dynCall_jiiii"]=createExportWrapper("dynCall_jiiii");var dynCall_jiji=Module["dynCall_jiji"]=createExportWrapper("dynCall_jiji");var ___start_em_js=Module["___start_em_js"]=317612;var ___stop_em_js=Module["___stop_em_js"]=317811;var missingLibrarySymbols=["writeI53ToI64","writeI53ToI64Clamped","writeI53ToI64Signaling","writeI53ToU64Clamped","writeI53ToU64Signaling","readI53FromI64","readI53FromU64","convertI32PairToI53",
"convertU32PairToI53","zeroMemory","exitJS","isLeapYear","ydayFromDate","arraySum","addDays","inetPton4","inetNtop4","inetPton6","inetNtop6","readSockaddr","writeSockaddr","getHostByName","initRandomFill","randomFill","getCallstack","emscriptenLog","convertPCtoSourceLocation","readEmAsmArgs","jstoi_q","jstoi_s","listenOnce","autoResumeAudioContext","dynCallLegacy","getDynCaller","dynCall","handleException","keepRuntimeAlive","runtimeKeepalivePush","runtimeKeepalivePop","callUserCallback","maybeExit",
"asmjsMangle","asyncLoad","alignMemory","mmapAlloc","handleAllocatorInit","HandleAllocator","getNativeTypeSize","STACK_SIZE","STACK_ALIGN","POINTER_SIZE","ASSERTIONS","getCFunc","ccall","cwrap","uleb128Encode","sigToWasmTypes","generateFuncType","convertJsFunctionToWasm","getEmptyTableSlot","updateTableMap","getFunctionAddress","addFunction","removeFunction","reallyNegative","unSign","strLen","reSign","formatString","lengthBytesUTF8","intArrayFromString","intArrayToString","AsciiToString","UTF16ToString",
"stringToUTF16","lengthBytesUTF16","UTF32ToString","stringToUTF32","lengthBytesUTF32","stringToNewUTF8","stringToUTF8OnStack","writeArrayToMemory","registerKeyEventCallback","maybeCStringToJsString","findEventTarget","findCanvasEventTarget","getBoundingClientRect","fillMouseEventData","registerMouseEventCallback","registerWheelEventCallback","registerUiEventCallback","registerFocusEventCallback","fillDeviceOrientationEventData","registerDeviceOrientationEventCallback","fillDeviceMotionEventData",
"registerDeviceMotionEventCallback","screenOrientation","fillOrientationChangeEventData","registerOrientationChangeEventCallback","fillFullscreenChangeEventData","registerFullscreenChangeEventCallback","JSEvents_requestFullscreen","JSEvents_resizeCanvasForFullscreen","registerRestoreOldStyle","hideEverythingExceptGivenElement","restoreHiddenElements","setLetterbox","softFullscreenResizeWebGLRenderTarget","doRequestFullscreen","fillPointerlockChangeEventData","registerPointerlockChangeEventCallback",
"registerPointerlockErrorEventCallback","requestPointerLock","fillVisibilityChangeEventData","registerVisibilityChangeEventCallback","registerTouchEventCallback","fillGamepadEventData","registerGamepadEventCallback","registerBeforeUnloadEventCallback","fillBatteryEventData","battery","registerBatteryEventCallback","setCanvasElementSize","getCanvasElementSize","demangle","demangleAll","jsStackTrace","stackTrace","checkWasiClock","wasiRightsToMuslOFlags","wasiOFlagsToMuslOFlags","createDyncallWrapper",
"safeSetTimeout","setImmediateWrapped","clearImmediateWrapped","polyfillSetImmediate","getPromise","makePromise","idsToPromises","makePromiseCallback","findMatchingCatch","setMainLoop","getSocketFromFD","getSocketAddress","heapObjectForWebGLType","heapAccessShiftForWebGLHeap","webgl_enable_ANGLE_instanced_arrays","webgl_enable_OES_vertex_array_object","webgl_enable_WEBGL_draw_buffers","webgl_enable_WEBGL_multi_draw","emscriptenWebGLGet","computeUnpackAlignedImageSize","colorChannelsInGlTextureFormat",
"emscriptenWebGLGetTexPixelData","__glGenObject","emscriptenWebGLGetUniform","webglGetUniformLocation","webglPrepareUniformLocationsBeforeFirstUse","webglGetLeftBracePos","emscriptenWebGLGetVertexAttrib","__glGetActiveAttribOrUniform","writeGLArray","registerWebGlEventCallback","runAndAbortIfError","SDL_unicode","SDL_ttfContext","SDL_audio","ALLOC_NORMAL","ALLOC_STACK","allocate","writeStringToMemory","writeAsciiToMemory"];missingLibrarySymbols.forEach(missingLibrarySymbol);var unexportedSymbols=
["run","addOnPreRun","addOnInit","addOnPreMain","addOnExit","addOnPostRun","addRunDependency","removeRunDependency","FS_createFolder","FS_createPath","FS_createLazyFile","FS_createLink","FS_createDevice","FS_readFile","out","err","callMain","abort","wasmMemory","wasmExports","stackAlloc","stackSave","stackRestore","getTempRet0","setTempRet0","writeStackCookie","checkStackCookie","convertI32PairToI53Checked","ptrToString","getHeapMax","growMemory","ENV","MONTH_DAYS_REGULAR","MONTH_DAYS_LEAP","MONTH_DAYS_REGULAR_CUMULATIVE",
"MONTH_DAYS_LEAP_CUMULATIVE","ERRNO_CODES","ERRNO_MESSAGES","setErrNo","DNS","Protocols","Sockets","timers","warnOnce","UNWIND_CACHE","readEmAsmArgsArray","getExecutableName","wasmTable","noExitRuntime","freeTableIndexes","functionsInTableMap","setValue","getValue","PATH","PATH_FS","UTF8Decoder","UTF8ArrayToString","UTF8ToString","stringToUTF8Array","stringToUTF8","stringToAscii","UTF16Decoder","JSEvents","specialHTMLTargets","currentFullscreenStrategy","restoreOldWindowedStyle","ExitStatus","getEnvStrings",
"flush_NO_FILESYSTEM","promiseMap","uncaughtExceptionCount","exceptionLast","exceptionCaught","ExceptionInfo","Browser","wget","SYSCALLS","tempFixedLengthArray","miniTempWebGLFloatBuffers","miniTempWebGLIntBuffers","GL","emscripten_webgl_power_preferences","AL","GLUT","EGL","GLEW","IDBStore","SDL","SDL_gfx","allocateUTF8","allocateUTF8OnStack"];unexportedSymbols.forEach(unexportedRuntimeSymbol);var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=
runCaller};function stackCheckInit(){_emscripten_stack_init();writeStackCookie()}function run(){if(runDependencies>0)return;stackCheckInit();preRun();if(runDependencies>0)return;function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();assert(!Module["_main"],'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]');postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");
setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else doRun();checkStackCookie()}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0)Module["preInit"].pop()()}run()})(window,undefined);

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>onlypass</title>
<script type="text/javascript" src="../pluginBase.js"></script>
<script type="text/javascript" src="./scripts/storage.js"></script>
<script type="text/javascript" src="./scripts/code.js"></script>
<script type="text/javascript" src="./scripts/plugin.js"></script>
<script type="text/javascript" src="worker.js"></script>
</head>
<body>
</body>
</html>

View File

@ -0,0 +1,40 @@
/**
*
* (c) Copyright Ascensio System SIA 2020
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
(function(window, undefined)
{
(function()
{
let url = "./engine/engine";
let useWasm = false;
let webAsmObj = window["WebAssembly"];
if (typeof webAsmObj === "object" && typeof webAsmObj["Memory"] === "function")
{
if ((typeof webAsmObj["instantiateStreaming"] === "function") || (typeof webAsmObj["instantiate"] === "function"))
useWasm = true;
}
url += (useWasm ? ".js" : "_ie.js");
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
})();
})(window, undefined);

View File

@ -0,0 +1,72 @@
(function(window, undefined){
const decryptHeader = "DECRYPTED;";
const encryptHeader = "ENCRYPTED;";
const decryptHeaderLen = decryptHeader.length;
const encryptHeaderLen = encryptHeader.length;
var currentPassword = "";
window.Asc.plugin.init = function(obj)
{
if (!obj)
return;
switch (obj.type)
{
case "generatePassword":
{
this.executeMethod("OnEncryption", [{ type : "generatePassword", password : generate_password() }]);
break;
}
case "getPasswordByFile":
{
this.executeMethod("OnEncryption", [{ type : "getPasswordByFile", password : getPasswordByFile(obj.hash) }]);
break;
}
case "setPasswordByFile":
{
this.executeMethod("StartAction", ["Block", "Save to localstorage..."], function() {
setPasswordByFile(obj.hash, obj.password);
setTimeout(function() {
// send end action with delay
window.Asc.plugin.executeMethod("EndAction", ["Block", "Save to localstorage..."]);
}, 200);
});
break;
}
case "encryptData":
{
var check = { valid : true };
for (var i = 0; i < obj.data.length; i++)
obj.data[i] = obj.data[i].encryptData(check);
this.executeMethod("OnEncryption", [{ type : "encryptData", data : obj.data, check: check.valid }]);
break;
}
case "decryptData":
{
var check = { valid : true };
for (var i = 0; i < obj.data.length; i++)
{
if (obj.data[i]["change"])
obj.data[i]["change"] = obj.data[i]["change"].decryptData(check);
else
obj.data[i] = obj.data[i].decryptData(check);
}
this.executeMethod("OnEncryption", [{ type : "decryptData", data : obj.data, check: check.valid }]);
break;
}
default:
break;
}
};
window.Asc.plugin.button = function(id)
{
this.executeCommand("close", "");
};
})(window, undefined);

View File

@ -0,0 +1,236 @@
"use strict";
(function(exports){
exports.AscCrypto = exports.AscCrypto || {};
var AscCrypto = exports.AscCrypto;
CryptoJS.Storage = {};
// command types
AscCrypto.Storage.CommandType = {
Sign : "sign",
Crypt : "crypt"
};
AscCrypto.Storage.CurrentVersion = 1;
// Common Functions
function randomBytes = function(count)
{
var array = new Uint8Array(count);
if (window.crypto && window.crypto.getRandomValues)
window.crypto.getRandomValues(array);
else
{
for (var i = 0; i < count; i++)
array[i] = (0x100 * Math.random()) >> 0;
}
return array;
};
function toBase58(buf)
{
if(typeof buf === "string")
{
let old = buf;
buf = [];
for (let i = 0, len = old.length; i < len; i++)
buf.push(old.charCodeAt(i));
}
const chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const chars_map = [
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1,
-1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1,
-1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
];
let result = [];
for (let i = 0, len = buf.length; i < len; i++)
{
let carry = buf[i];
for (let j = 0; j < result.length; ++j)
{
const x = (chars_map[result[j]] << 8) + carry;
result[j] = chars.charCodeAt(x % 58);
carry = (x / 58) >> 0;
}
while (carry)
{
result.push(chars.charCodeAt(carry % 58));
carry = (carry / 58) >> 0;
}
}
let char1 = "1".charCodeAt(0);
for (let i = 0, len = buf.length; i < len; i++)
{
if (buf[i])
break;
else
result.push(char1);
}
result.reverse();
return String.fromCharCode.apply(null, result);
};
function StorageItem()
{
this.Id = "";
this.Type = AscCrypto.Storage.CommandType.Sign;
this.Date = "";
this.Version = AscCrypto.Storage.CurrentVersion;
this.PublicKey = "";
this.PrivateKey = "";
this.Salt = "";
}
StorageItem.prototype.generate = function(type)
{
let item = new StorageItem();
item.Id = toBase58(randomBytes(20));
item.Type = type;
let date = new Date();
item.Date = date.toISOString();
let keys = null;
switch (type)
{
case AscCrypto.Storage.CommandType.Sign:
{
keys = window.cryptoJS.generateSignKeys();
break;
}
case AscCrypto.Storage.CommandType.Crypt:
{
keys = window.cryptoJS.generateCryptKeys();
break;
}
default:
break;
}
if (keys)
{
item.PublicKey = keys.publicKey;
item.PrivateKey = keys.privateKey;
item.Salt = keys.salt;
}
return item;
};
function StorageLocalStorage()
{
}
// store
StorageLocalStorage.prototype.getStorageValue = function()
{
try
{
return JSON.parse(window.localStorage.getItem("oo-crypto-object"));
}
catch (e)
{
return [];
}
};
StorageLocalStorage.prototype.setStorageValue = function(value)
{
try
{
window.localStorage.setItem("oo-crypto-object", JSON.stringify(value));
return true;
}
catch (e)
{
}
return false;
};
// commands
StorageLocalStorage.prototype.add = function(items)
{
let value = this.getStorageValue();
this.setStorageValue(value.concat(items));
};
StorageLocalStorage.prototype.replace = function(items)
{
let value = this.getStorageValue();
let id2index = {};
for (let i = 0, len = value.length; i < len; ++i)
id2index[value[i].Id] = i;
for (let i = 0, len = items.length; i < len; ++i)
{
let index = id2index[items[i].Id];
if (undefined !== index)
value[index] = items[i];
}
};
StorageLocalStorage.prototype.get = function(item)
{
let value = this.getStorageValue();
let result = [];
for (let i = 0, len = value.length; i < len; ++i)
{
let isAdd = true;
for (let i in item)
{
if (item.hasOwnProperty(i) && item[i] !== value[i])
{
isAdd = false;
break;
}
}
if (isAdd)
result.push(value[i]);
}
return result;
};
StorageLocalStorage.prototype.getByType = function(type)
{
return this.get({ Type : type });
};
StorageLocalStorage.prototype.remove = function(id)
{
let value = this.getStorageValue();
for (let i = 0, len = value.length; i < len; ++i)
{
if (value[i].Id === id)
{
value.splice(i, 1);
break;
}
}
this.setStorageValue(value);
};
AscCrypto.Storage.Item = StorageItem;
AscCrypto.Storage.LocalStorage = StorageLocalStorage;
})(window);

View File

@ -0,0 +1,9 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"Old Password" : "Old Password",
"New Password" : "New Password",
"OK" : "OK"
}

View File

@ -0,0 +1,9 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"Old Password" : "Old Password",
"New Password" : "New Password",
"OK" : "OK"
}

View File

@ -0,0 +1,9 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"Old Password" : "Old Password",
"New Password" : "New Password",
"OK" : "OK"
}

View File

@ -0,0 +1,9 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"Old Password" : "Old Password",
"New Password" : "New Password",
"OK" : "OK"
}

View File

@ -0,0 +1,7 @@
[
"cs-CS",
"de-DE",
"es-ES",
"fr-FR",
"ru-RU"
]

View File

@ -0,0 +1,7 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"New Password" : "New Password"
}

View File

@ -0,0 +1,131 @@
(function(window, undefined){
window.AscCrypto = window.AscCrypto || {};
if (window.AscCrypto.CryptoWorker)
return;
var filePassword = "";
window.AscCrypto.CryptoWorker = {};
window.AscCrypto.CryptoWorker.User = null;
// random password generation
function _generatePassword()
{
let guidValues = [];
if (!window.crypto || !window.crypto.getRandomValues)
{
for (let i = 0; i < 8; ++i)
guidValues.push(((1 + Math.random()) * 0x10000) >> 0);
}
else
{
let tmp = new Uint16Array(8);
window.crypto.getRandomValues(tmp);
for (let i = 0; i < 8; ++i)
guidValues.push(0x10000 + tmp[i]);
}
var index = 0;
function s4() {
return guidValues[index++].toString(16).substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
// create record for current user
function _generateCurrentUserRecord = function()
{
if (!this.User)
return null;
return [{ publicKey : this.User[1].replace(/\n/g, "&#xA"), userId : this.User[2] }];
};
// read user info
window.AscCrypto.CryptoWorker.init = function()
{
this.User = window.AscDesktopEditor.CryptoCloud_GetUserInfo();
};
// create from passwords
window.AscCrypto.CryptoWorker.generateDocInfo = function(users, password)
{
if (!Array.isArray(users) || users.length === 0)
users = _generateCurrentUserRecord();
if (!Array.isArray(users))
return "";
var result = "ONLYOFFICE CryptoEngine (Version 1)\n\n";
for (var i = 0, len = users.length; i < len; i++)
{
if (users[i].publicKey)
{
result += (users[i].userId + "\n");
result += (window.AscDesktopEditor.CryproRSA_EncryptPublic(users[i].publicKey, password) + "\n\n");
}
}
return result;
};
// decrypt password from docinfo
window.AscCrypto.CryptoWorker.readPassword = function(docinfo)
{
if (docinfo == null)
docinfo = "";
var user = this.User[2];
var index = docinfo.indexOf(user);
if (-1 == index)
return "";
var delimeter = "<!--break-->";
var start = docinfo.indexOf(delimeter, index);
if (-1 == index)
return "";
var end = docinfo.indexOf(delimeter, start + 1);
if (-1 == end)
return "";
var encPassword = docinfo.substring(start + delimeter.length, end);
return window.AscDesktopEditor.CryproRSA_DecryptPrivate(this.User[0], encPassword);
};
// запрос на новый пароль
window.AscCrypto.CryptoWorker.createPassword = function(oldPassword)
{
return oldPassword ? oldPassword : _generatePassword();
};
window.AscCrypto.CryptoWorker.generatePassword = function(oldPassword)
{
let _password = this.createPassword(oldPassword);
window.AscDesktopEditor.cloudCryptoCommandMainFrame({ type: "getsharingkeys" }, function(obj){
window.Asc.plugin.onSystemMessage({
type : "generatePassword",
password : _password,
docinfo : (obj.keys && obj.keys.length) ? worker.generateDocInfo(obj.keys, _password) : ""
});
});
};
// шифрование изменений
window.AscCrypto.CryptoWorker.cryptInit = function(password)
{
window.AscDesktopEditor.CryptoAES_Init(password);
};
window.AscCrypto.CryptoWorker.encrypt = function(data)
{
return window.AscDesktopEditor.CryptoAES_Encrypt(data);
};
window.AscCrypto.CryptoWorker.decrypt = function(data)
{
return window.AscDesktopEditor.CryptoAES_Decrypt(data);
};
// init
window.AscCrypto.CryptoWorker.init();
})(window, undefined);

View File

@ -432,9 +432,11 @@ namespace PdfReader
if (bResult)
{
#ifndef BUILDING_WASM_MODULE
// Шрифт нашелся, но пока им пользоваться нельзя, потому что он загружается в параллельном потоке
while (!pEntry->bAvailable)
NSThreads::Sleep(10);
#endif
}
RELEASEOBJECT(pCS);
@ -449,9 +451,11 @@ namespace PdfReader
if (bResult)
{
#ifndef BUILDING_WASM_MODULE
// Шрифт нашелся, но пока им пользоваться нельзя, потому что он загружается в параллельном потоке
while (!(*ppEntry)->bAvailable)
NSThreads::Sleep(10);
#endif
}
if (!bResult)