AES CBC:JavaScript/CryptoJS加密 -> Golang解密
创始人
2024-07-29 11:30:34
0

以下是使用CryptoJS进行AES CBC加密,然后使用Golang进行解密的示例代码:

JavaScript/CryptoJS加密:

// 引入CryptoJS库
const CryptoJS = require('crypto-js');

// 定义加密函数
function encryptAES_CBC(message, key, iv) {
    // 转换为字节数组
    const keyBytes = CryptoJS.enc.Utf8.parse(key);
    const ivBytes = CryptoJS.enc.Utf8.parse(iv);

    // 加密
    const ciphertext = CryptoJS.AES.encrypt(message, keyBytes, {
        iv: ivBytes,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });

    // 返回加密后的密文(Base64格式)
    return ciphertext.toString();
}

// 加密消息
const message = 'Hello, World!';
const key = '1234567890123456';
const iv = '1234567890123456';
const encryptedMessage = encryptAES_CBC(message, key, iv);

console.log('加密后的消息:', encryptedMessage);

Golang解密:

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
)

// 定义解密函数
func decryptAES_CBC(ciphertext, key, iv string) (string, error) {
	// 将密文和密钥进行Base64解码
	ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return "", err
	}
	keyBytes := []byte(key)
	ivBytes := []byte(iv)

	// 创建AES解密器
	block, err := aes.NewCipher(keyBytes)
	if err != nil {
		return "", err
	}

	// 创建CBC解密实例
	mode := cipher.NewCBCDecrypter(block, ivBytes)

	// 解密密文
	plaintext := make([]byte, len(ciphertextBytes))
	mode.CryptBlocks(plaintext, ciphertextBytes)

	// 去除填充数据
	paddingSize := int(plaintext[len(plaintext)-1])
	plaintext = plaintext[:len(plaintext)-paddingSize]

	// 返回解密后的明文
	return string(plaintext), nil
}

func main() {
	// 解密消息
	ciphertext := "p6p3R6IP2o4RiR7NFQ2yGQ=="
	key := "1234567890123456"
	iv := "1234567890123456"
	decryptedMessage, err := decryptAES_CBC(ciphertext, key, iv)
	if err != nil {
		fmt.Println("解密失败:", err)
		return
	}

	fmt.Println("解密后的消息:", decryptedMessage)
}

在上述代码中,我们使用CryptoJS的AES加密算法进行加密,然后使用Golang的crypto/aes和crypto/cipher库进行解密。注意,加密和解密使用相同的密钥和初始化向量(IV)。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...