String passing and simple replacement encryption between C++ and JS in WebAssembly

Operating system: ubuntu 22.04 (yes, this dog thing, where a lot of new bugs are generated)

Languages ​​used: C++14, html (self-study, mainly the script part)

Use the compiler: gcc, g++, emcc (this is a tutorial to install yourself), cmake

Use IDE: Clion2018.3

Browser: Firefox or Google is recommended

Not much nonsense, just upload the code~

main.cpp

#include <stdio.h>
#include <iostream>
#include <emscripten.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>

#ifndef EM_PORT_API
#	if defined(__EMSCRIPTEN__)
#		include <emscripten.h>
#		if defined(__cplusplus)
#			define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE
#		else
#			define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE
#		endif
#	else
#		if defined(__cplusplus)
#			define EM_PORT_API(rettype) extern "C" rettype
#		else
#			define EM_PORT_API(rettype) rettype
#		endif
#	endif
#endif

//autor:cxx
//测试运行
EM_PORT_API(void) test()
{
    std::cout<<"hello world!"<<std::endl;
}

//测试1
EM_PORT_API(char*) outName(char *n)
{
    char xhName[] = "xuanhun";
    strcat(n, xhName);
    return n;
}
//KS加密
EM_PORT_API(char*) ksencry(char *c,int n)
{
    char res[]="";
    for(int i=0;i<=strlen(c)-1;i++) {
        c[i] = c[i] + n % 26;
        if (c[i] > 'z') n -= 26;
    }

    strcat(res,c);
    return res;
}

//KS解密
EM_PORT_API(char*) ksdecry(char *c,int n)
{
    char res[]="";
    for(int i=0;i<=strlen(c)-1;i++) {
        c[i] = c[i] - n % 26;
        if (c[i] > 'z') n -= 26;
    }

    strcat(res,c);
    return res;
}

//其他测试方案...

Here I explain a lot of references and macros at the beginning, which are to be specified in order to use C or C++ functions in JS. In addition, the header file emscripten.h needs to import the absolute path into cmakelist.txt when installing emsdk. Otherwise, some functions will not be available. The encryption and decryption functions written here are just simple Caesar ciphers for testing, but they can be replaced with other high-level ciphers, such as AES and RSA, which require key generation.

After writing the C++ file, it needs to be compiled. The compilation statement is as follows:

emcc main.cpp -o ./build/forUpdate.js -s EXPORTED_FUNCTIONS="['_malloc','_free']" -s WASM=1

Generate two files forUpdate.js and forUpdate.wasm in the build folder, where the former will be referenced.

Create the file forUpdate.html, and write the styles and conversion code in it.

forUpdate.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ForUpdateTest</title>
</head>
<body>
<script>
    function f1(k,b) {

        var ptr =allocate(intArrayFromString(k),ALLOC_NORMAL);

        var resP=_ksencry(ptr,b);

        console.log("KS加密结果"+UTF8ToString(resP));

        document.getElementById("textshow").value += "KS加密结果:"+UTF8ToString(resP)+ "\n\r";

        return UTF8ToString(resP);

        _free(ptr);
    }

    function f2(k,b) {

        var ptr =allocate(intArrayFromString(k),ALLOC_NORMAL);

        var resP=_ksdecry(ptr,b);

        console.log("KS解密结果"+UTF8ToString(resP));

        document.getElementById("textshow").value += "KS解密结果:"+UTF8ToString(resP)+"\n\r";

        _free(ptr);
    }

    function f3() {
        var msg =document.getElementById('input').value;

        console.log('获取到字符串:'+msg);

        document.getElementById("textshow").value += '获取到字符串:'+msg + "\n\r";

        return msg;
    }

    function f4()
    {
        var msg =document.getElementById('bit').value;

        console.log('获取到替换位数:'+msg);

        document.getElementById("textshow").value += '获取到替换位数:'+msg +"\n\r";

        return msg;
    }

    function f5() {

        document.getElementById("textshow").value ="";

        console.log("清空文本域");
    }

</script>

<script async type="text/javascript" src="build/forUpdate.js"></script>

<div>请在输入框里输入需要加密的字符串和替换位数!</div>
<br/>
<form>

    <input type="text" id ="input" placeholder="请输入字符串" maxlength="20"/>
    <input type="text" id ="bit" placeholder="请输入替换位数" maxlength="20"/>

</form>


<br/>
<input type="button" value="KS加密" onclick="f1(f3(),f4())" />
<input type="button" value="KS解密" onclick="f2(f1(f3(),f4()),f4())" />
<br/>
<br/>


<form>
    结果展示:<textarea name="description" id="textshow" cols="30" rows="6" placeholder="过程"> </textarea>
    <input type="button" value="清空" onclick="f5()" />
</form>


</body>
</html>

allocate to open up space for pointers, this step is very important. This step may need to be written in the export function. My emcc does not need it. If you want to write it, you can write it like this. You can also write other functions you want to export. You can search for details.

emcc main.cpp -o ./build/forUpdate.js -s EXPORTED_FUNCTIONS="['_malloc','_free','allocate']" -s WASM=1

Others are very simple access to control values, which can be viewed on the console or in the text field. Here, all the step statements are printed and can be modified.

Basic result display:

 

 

You're done, it turns out that the direct value transfer is to output the address code of UTF-8, people are dying. Later, it was found that it was necessary to use pointers to carry over, and then use the conversion function to output normally.

broken thoughts

Next week, I want to see if I can send emails on the front end by writing a C++ email function and quoting the compiled JS file? Give it a try. After all, it seems theoretically possible. However, WebAssembly only supports http and websocket connections, and there are cross-domain restrictions. I don’t know if it can connect to other ports. If it is not a local port, it may be restricted.

Guess you like

Origin blog.csdn.net/daxuanzi515/article/details/125966697