跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[Rust] 用 Rust 封装一个 sm4 加解密 wasm SDK

发表于

在前端使用加解密方式容易暴露密钥(或许一定会),但是如果把密钥藏起来,藏到二进制中或许就不容易被发现了。

alt

sm4-sdk

是我用来验证想法的 demo ,下面介绍大概思路,以及有些踩坑的内容

一、基本情况

1 、使用 wasm-pack 这个工具来创建项目,编译成 web 类型

wasm-pack new sm4-sdk
wasm-pack build --target web

2 、使用了一个简单的国密库

cargo add smcrypto

经过一番研究发现它的 Padding 模式是 PKCS5Padding

3 、使用dotenv达成编译阶段注入变量的目的

从前端的工程化的一些经验中借鉴来的,dotenv支持从环境变量和.env文件读取变量,

cargo add dotenv
// file config.rs
use dotenv_codegen::dotenv;

pub const KEY: &str = dotenv!("SM4_SDK_KEY");
pub const IV: &str = dotenv!("SM4_SDK_IV");

4 、如何使用

克隆这个项目,将.env.example修改为.env文件,修改里面的密钥内容,执行

wasm-pack build --target web

二、踩坑

1 、安装wasm-pack

安装wasm-pack命令有两种方式,通过cargo或者npm

如果是 windows 环境,建议设置 default host 等设为msvc

// file settings.toml
default_host_triple = "x86_64-pc-windows-msvc"
default_toolchain = "stable-x86_64-pc-windows-msvc"

2 、使用github action自动打包

希望通过github action的环境变量提供给项目打包时使用,可能dotenv没有支持好,可能是我配置不对。不过不折腾的方式是配置repository secrets,使用时新建一个.env文件

// file workflows/wasm-pack.yml
      - name: create env file
        run: |
          touch .env
          echo SM4_SDK_KEY=${{ secrets.SM4_SDK_KEY }} >> .env
          echo SM4_SDK_IV=${{ secrets.SM4_SDK_IV }} >> .env

三、如何使用

参考项目中的example.html的做法,这个项目并没有上传到 npm 上,

<script type="module">
    import init, { encrypt_to_base64, decrypt_from_base64 } from './pkg/sm4_sdk.js';

    const run = async () => {
        await init();
        const origin = "hello world";
        const encoded_str = encrypt_to_base64(origin);
        console.log(encoded_str); // ${encoded_str}
        const decoded_str = decrypt_from_base64(encoded_str);
        console.log(decoded_str === origin);
        appendResult(encoded_str);
    }

    run(); // checkout console for result
</script>

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.