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)。

相关内容

热门资讯

Android Studio ... 要解决Android Studio 4无法检测到Java代码,无法打开SDK管理器和设置的问题,可以...
安装tensorflow mo... 要安装tensorflow models object-detection软件包和pandas的每个...
安装了Laravelbackp... 检查是否创建了以下自定义文件并进行正确的配置config/backpack/base.phpconf...
安装了centos后会占用多少... 安装了CentOS后会占用多少内存取决于多个因素,例如安装的软件包、系统配置和运行的服务等。通常情况...
按照Laravel方式通过Pr... 在Laravel中,我们可以通过定义关系和使用查询构建器来选择模型。首先,我们需要定义Profile...
按照分类ID显示Django子... 在Django中,可以使用filter函数根据分类ID来筛选子类别。以下是一个示例代码:首先,假设你...
Android Studio ... 要给出包含代码示例的解决方法,我们可以使用Markdown语法来展示代码。下面是一个示例解决方案,其...
Android Retrofi... 问题描述:在使用Android Retrofit进行GET调用时,获取的响应为空,即使服务器返回了正...
Alexa技能在返回响应后出现... 在开发Alexa技能时,如果在返回响应后出现问题,可以按照以下步骤进行排查和解决。检查代码中的错误处...
Airflow Dag文件夹 ... 要忽略Airflow中的笔记本检查点,可以在DAG文件夹中使用以下代码示例:from airflow...