跳到主要内容

回调解密 demo

Java

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


public class CallbackAes {

public static byte[] pkcs7Padding(byte[] ciphertext, int blockSize) {
int padding = blockSize - ciphertext.length % blockSize;
byte[] padtext = repeat((byte) padding, padding);
ciphertext = append(ciphertext, padtext);
return ciphertext;
}

public static byte[] repeat(byte val, int count) {
byte[] result = new byte[count];
for (int i = 0; i < count; i++) {
result[i] = val;
}
return result;
}

public static byte[] append(byte[] a, byte[] b) {
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}

public static byte[] pkcs7UnPadding(byte[] origData) {
int length = origData.length;
int unpadding = origData[length - 1];
byte[] result = new byte[length - unpadding];
System.arraycopy(origData, 0, result, 0, result.length);
return result;
}

public static byte[] aesEncrypt(byte[] origData, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
origData = pkcs7Padding(origData, blockSize);
SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
byte[] iv = new byte[blockSize];
System.arraycopy(key, 0, iv, 0, iv.length);
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(origData);
return Base64.getEncoder().encode(encrypted);
}

public static byte[] aesDecrypt(byte[] crypted, byte[] key) throws Exception {
byte[] decoded = Base64.getDecoder().decode(crypted);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
byte[] iv = new byte[blockSize];
System.arraycopy(key, 0, iv, 0, iv.length);
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] origData = cipher.doFinal(decoded);
return pkcs7UnPadding(origData);
}

public static void main(String[] args) throws Exception {
// 传入CallbackUrlKey
byte[] key = "***************".getBytes();
// 传入密文,如果接收到的数据是{"encrypt":"base64后的密文"}
byte[] origData = aesDecrypt("base64后的密文".getBytes(StandardCharsets.UTF_8), key);
// 打印解密后的内容,格式为json
System.out.println(new String(origData, StandardCharsets.UTF_8));
}
}

备注: 如果解密时报错 Illegal key size,可尝试以下方式解决。

  1. 可尝试将jdk升级到到1.8.0_162及以上版本之上
  2. 如果jdk版本为1.8.0_151 或 1.8.0_152,可加入以下代码开启支持: Security.setProperty("crypto.policy", "unlimited")
  3. 可下载以下jar包置于${java.home}/jre/lib/security/

PHP

<?php
require_once __DIR__.'/../../../vendor/autoload.php';

class Aes
{
public $key = '';
public $iv = '';

public function __construct($config)
{
foreach($config as $k => $v){
$this->$k = $v;
}
$this->iv = substr($this->key, 0, 16);
}

//解密
public function aesDe($data){
return openssl_decrypt(base64_decode($data), $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
}
}

$config = [
'key' => '********************', // 此处填入CallbackUrlKey
'method' => 'AES-256-CBC' //加密方式
];

$obj = new Aes($config);

// 此处填入收到的密文,如果接收到的数据是{"encrypt":"base64后的密文"}
$data = 'base64后的密文';

echo $obj->aesDe($data);//解密

Golang

package v20201111

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

func AesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS7UnPadding(origData)
return origData, nil
}

// PKCS7UnPadding 去除填充
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unPadding := int(origData[length-1])
return origData[:(length - unPadding)]
}

func TestDecrypt(t *testing.T) {
// 传入CallbackUrlKey
key := "***********"
// 传入密文,如果接收到的数据是{"encrypt":"base64后的密文"}
content := "base64后的密文"

// base64解密
crypted, err := base64.StdEncoding.DecodeString(content)
if err != nil {
fmt.Printf("base64 DecodeString returned: %s", err)
return
}

origData, err := AesDecrypt(crypted, []byte(key))
if err != nil {
fmt.Printf("AesDecrypt returned: %s", err)
return
}
fmt.Printf("%s", string(origData))
}

Python

# -*- coding: utf-8 -*-
import base64

from Cryptodome.Cipher import AES


def decode_aes256(data, encryption_key):
iv = encryption_key[0:16]
aes = AES.new(encryption_key, AES.MODE_CBC, iv)
d = aes.decrypt(data)
unpad = lambda s: s[0:-ord(d[-1:])]
return unpad(d)

# 此处传入密文,如果接收到的数据是{"encrypt":"base64后的密文"}
data = 'base64后的密文'
data = base64.b64decode(data)
# 此处传入CallbackUrlKey
e = decode_aes256(data, bytes('**************************************************', encoding="utf8"))
print(type(e))
print(str(e, encoding="utf8"))

C#

using System;
using System.Security.Cryptography;
using System.Text;
namespace TencentCloudExamples
{

class EssCallback
{

static void Main1(string[] args)
{
try
{
// 传入CallbackUrlKey
String key = "*************";
// 传入密文,如果接收到的数据是{"encrypt":"base64后的密文"}
String content = "base64后的密文";

String plaintext = AESDecrypt(content, Encoding.ASCII.GetBytes(key));

Console.WriteLine(plaintext);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.Read();

}

public static string AESDecrypt(string encryptStr, byte[] key)
{
byte[] toEncryptArray = Convert.FromBase64String(encryptStr);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = key;
byte[] iv = new byte[16];
Array.Copy(key, iv, iv.Length);
rDel.IV = iv;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString(resultArray);
}

}

}

Node.js

const crypto = require('crypto');

//如果接收到的数据是{"encrypt":"base64后的密文"}
const base64EncryptedData = 'base64后的密文';

const key = '传入CallbackUrlKey';
const rawKey = Buffer.from(key, 'utf-8');
const iv = rawKey.slice(0, 16); // 使用密钥的前16字节作为IV

/**
* 解密函数
* @param {String} encryptedBase64Data - Base64编码的加密数据
* @param {Buffer} key - 解密的密钥
* @param {Buffer} iv - 初始化向量
* @return {String} - 解密后的文本
*/
function decrypt(encryptedBase64Data, key, iv) {
const encryptedText = Buffer.from(encryptedBase64Data, 'base64');
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encryptedText, 'binary', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}

// 解密示例
const decryptedData = decrypt(base64EncryptedData, rawKey, iv);
console.log('解密后的数据:', decryptedData);

// 尝试解析JSON,捕获任何错误防止脚本崩溃
try {
const jsonData = JSON.parse(decryptedData);
console.log('JSON 数据:', jsonData);
} catch (error) {
console.error('解析 JSON 数据时出错:', error);
}
购买咨询
微信客服
4006-808-062
4006-808-062