crypto.uts 2.22 KB
import { Logger } from "../services/logger/LoggerCore.uts";
const logger = Logger.getInstance();

// #ifdef APP-ANDROID
import { useCrypto } from '@/uni_modules/lime-crypto'
// ✅ UVUE 类型导入:lime-crypto 模块类型导出存在问题,使用本地定义的类型
import type { ICrypto } from '../types/lime-crypto-types.uts'
const crypto = useCrypto()
// #endif

// #ifndef APP-ANDROID
// ✅ UVUE 类型导入:lime-crypto 模块类型导出存在问题,使用本地定义的类型
import type { ICrypto } from '../types/lime-crypto-types.uts'
import { CryptoImpl } from '../uni_modules/lime-crypto/common/Crypto'
const crypto: ICrypto = new CryptoImpl()
// #endif
export async function decryptAES(str: string | null, keyAES: string): Promise<string | null> {
  if (str == null || str === "") return str
  try {
	const key = crypto.enc.Utf8.parse(keyAES)
    // const iv = crypto.enc.Utf8.parse(key.toString().substring(0, 16));
    var decrypt = crypto.AES.decrypt(str, key, {
    //   iv: iv,
      mode: crypto.mode.ECB,
      padding: crypto.pad.Pkcs7
    })
    return crypto.enc.Utf8.stringify(decrypt).toString()
  } catch (e) {
    const errorMsg = e != null ? `${e}` : "Unknown error"
    logger.error('AES decryption failed:' + errorMsg)
    return str
  }
}
const RSA_PUBLIC_KEY_DER_B64 =
    "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdHnzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ=="

export function encryptLoginPassword(plain: string): string | null {
    if (plain == null || plain === "") {
        return null
    }

    try {
        const RSA = crypto.RSA

        // 设置公钥(lime-crypto 支持 Base64 格式的公钥)
        RSA.setPublicKey(RSA_PUBLIC_KEY_DER_B64)

        // 使用 RSA 加密(默认使用 PKCS1 填充)
        const encrypted = RSA.encrypt(plain)

        if (encrypted == null || encrypted === "") {
            console.error("[uts-simgle-login-rsa] RSA encryption returned empty result")
            return null
        }

        // lime-crypto 的 RSA.encrypt 返回的是 Base64 字符串
        return encrypted.toString()

    } catch (e) {
        console.error("[uts-simgle-login-rsa] encryptLoginPassword exception:", e)
        return null
    }
}