You need to enable JavaScript to run this app. Go实现AES加密字符串后CryptoJS解密失败如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Go实现AES加密字符串后CryptoJS解密失败如何解决

Go与CryptoJS跨端AES加密解密兼容修复方案

核心不兼容根因

  • 密钥处理逻辑不匹配:Go端直接将密钥字符串逐字节转换为[]byte作为AES密钥;但CryptoJS接收到字符串格式的密钥参数时,会默认执行OpenSSL风格的密钥派生流程,不会直接将字符串转为原始字节密钥,导致两边实际使用的加密密钥完全不同。
  • 密文解析逻辑不匹配:Go端输出hex编码的拼接密文(IV+加密结果),但CryptoJS的AES.decrypt方法默认将第一个入参按Base64编码的OpenSSL格式密文解析,直接传入hex字符串会导致密文解析完全错误。
  • IV传递逻辑不匹配:Go端将随机生成的IV拼接在密文开头,但CryptoJS不会自动从传入的密文中拆分前16字节作为CBC模式所需的IV,导致两边初始化向量不一致。

修复后可正常运行的代码实现

Go端加密代码

原Go端加密核心逻辑无需调整,仅保证输出hex编码的密文即可:

import (
    "crypto/aes"
    "crypto/rand"
    "encoding/hex"
    "errors"
    "io"
    "bytes"
)

func EncryptBody() (encodedmess string, err error) {
    // 32字节ASCII密钥,对应AES-256加密标准
    key := []byte("6368616e676520746869732070617373")

    block, err := aes.NewCipher(key)
    if err != nil {
        return "", err
    }
    // 对明文做PKCS7填充
    plaintext, err := pkcs7Pad([]byte("exampletext"), block.BlockSize())
    if err != nil {
        return "", err
    }
    // 生成随机IV
    ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    iv := ciphertext[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        return "", err
    }
    // CBC模式加密
    bm := cipher.NewCBCEncrypter(block, iv)
    bm.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)

    // 返回hex编码的拼接密文
    return hex.EncodeToString(ciphertext), nil
}

// 原有pkcs7Pad函数逻辑保留即可
func pkcs7Pad(b []byte, blocksize int) ([]byte, error) {
    if blocksize <= 0 {
        return nil, errors.New("invalid blocksize")
    }
    if b == nil || len(b) == 0 {
        return nil, errors.New("invalid PKCS7 data (empty or not padded)")
    }
    n := blocksize - (len(b) % blocksize)
    pb := make([]byte, len(b)+n)
    copy(pb, b)
    copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))
    return pb, nil
}

CryptoJS端解密代码

function decryptData() {
    // Go端输出的hex格式密文
    const data = "3633fbef042b01da5fc4b69d8f038a83130994a898137bb0386604cf2c1cbbe6"
    // 与Go端完全一致的原始密钥字符串
    const keyStr = "6368616e676520746869732070617373"

    // 解析hex格式密文
    const cipherWordArray = CryptoJS.enc.Hex.parse(data)
    // 拆分密文前16字节为CBC模式所需的IV
    const iv = CryptoJS.lib.WordArray.create(cipherWordArray.words.slice(0, 4), 16)
    // 拆分剩余部分为实际加密内容
    const encryptedContent = CryptoJS.lib.WordArray.create(
        cipherWordArray.words.slice(4),
        cipherWordArray.sigBytes - 16
    )
    // 将密钥字符串转为原始字节WordArray,跳过CryptoJS默认的密钥派生逻辑
    const key = CryptoJS.enc.Utf8.parse(keyStr)

    // 执行解密
    const decrypted = CryptoJS.AES.decrypt(
        { ciphertext: encryptedContent },
        key,
        {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        }
    )

    // 转换为UTF8格式拿到原始明文
    const plaintext = decrypted.toString(CryptoJS.enc.Utf8)
    console.log("解密结果: ", plaintext)
    return plaintext
}

通用注意事项

  • 密钥长度必须严格匹配AES标准:16字节对应AES-128、24字节对应AES-192、32字节对应AES-256,当前使用的密钥字符串刚好为32个ASCII字符,符合长度要求。
  • 禁止直接将字符串作为CryptoJS的密钥参数:传入字符串会触发CryptoJS的EVP_BytesToKey派生流程,必须通过CryptoJS.enc.Utf8.parse将密钥转为WordArray格式,才能和Go端的原始字节密钥逻辑对齐。
  • 密文编码格式必须两端统一:Go端输出hex编码的密文,CryptoJS端就必须用CryptoJS.enc.Hex.parse解析,不要默认按Base64格式解析。
  • IV必须在解密时显式传入:由于Go端将IV拼接在密文开头,CryptoJS不会自动拆分识别,需要手动提取后作为解密参数传入。

内容的提问来源于stack exchange,提问作者Matthis Holleville

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.03 14:24:05