开发 地图小程序OPENAPI 实用工具 事件回调加密解密工具

事件回调加解密工具 最后更新时间: 2024年03月08日

Java 代码实现

CryptUtilPublic.java


package com.amap.wia.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/*
 *
 *  @author yangdi
 *
 * AES 加密解密工具类
 * 秘钥长度:  支持任意长度
 * 算法:  AES/ECB/PKCS5Padding
 * 字符编码: utf-8
 * 多语言统一: java,  python, php 统一
 * 开放范围: open api 对外场景
 *
 * @notice: 由于对外,所以以下代码中任何一个配置参数都不要随意改,要考虑好兼容性
 *
 * @description: 对外开放的class 名字为: EncryptUtil, 位于 com.amap.wia.openapi.test.lib.EncryptUtil
 *
 *
 */
public class CryptUtilPublic {

    /** 密钥长度: 128, 192 or 256,默认128,不要随意改 */
    private static final int KEY_SIZE = 128;

    private static final Base64 base64 = new Base64();

    /** 加密/解密算法名称 */
    private static final String ALGORITHM = "AES"; // AES = AES/ECB/PKCS5Padding

    /** 随机数生成器(RNG)算法名称 */
    private static final String RNG_ALGORITHM = "SHA1PRNG";


    /**
     * 生成密钥对象
     */
    private static SecretKey generateKey(String key) throws Exception {

        // 创建安全随机数生成器
        SecureRandom random = SecureRandom.getInstance(RNG_ALGORITHM);
        // 设置 密钥key的字节数组 作为安全随机数生成器的种子
        random.setSeed(key.getBytes());
        // 创建 AES算法生成器
        KeyGenerator gen = KeyGenerator.getInstance(ALGORITHM);
        // 初始化算法生成器
        gen.init(KEY_SIZE, random);
        return gen.generateKey();
    }
    /**
     *
     * @param originalData 原始文本
     * @param key
     * @return
     * @throws Exception
     */

    public static String encrypt(String originalData, String key) throws Exception {
        byte[] plainBytes = originalData.getBytes(StandardCharsets.UTF_8);
        if (plainBytes.length == 0) {
            return "";
        }
        if (key == null || key.length()== 0) {
            return "";
        }

        SecretKey secKey = generateKey(key);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secKey);
        byte[] cipherBytes = cipher.doFinal(plainBytes);

        return base64encode(cipherBytes);
    }

    protected static byte[] base64decode(String str) {
        return base64.decode(str);
    }

    protected static String base64encode(byte[] bytes) {
        return base64.encodeToString(bytes);
    }
    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {


        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }


    public static String decrypt(String encrypedData, String key) throws Exception {

        byte[] cipherBytes = base64decode(encrypedData);
        SecretKey secKey = generateKey(key);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secKey);

        byte[] plainBytes = cipher.doFinal(cipherBytes);
        return new String(plainBytes, StandardCharsets.UTF_8);
    }

   public static void main(String[] args) {
       try {
           String originalData = "14464614210中文的001";
           String key = "asdfasdasdfsdfasdf23434tgsdfhxcvau4IKf";
           String encrypedData = encrypt(originalData, key);

           String decryptedText = decrypt(encrypedData, key);
           System.out.println("original value: " + originalData);
           System.out.println("encrypted value: " + encrypedData);
           System.out.println("original value: " + decryptedText);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

}

Java 代码运行结果输出:

original value: 14464614210中文的001
encrypted value: fH+Z38VD9uLdGLqpbm6InWxpDIYNyVnlzZHkfo9vK2k=
original value: 14464614210中文的001

python 代码实现

CryptUtilPublic.py (python3)

# AES-ECB加密
import hashlib
import base64
from crypto.Cipher import AES


class EncryptUtil:
    def __init__(self, key):
        self.key = self.get_sha1prng_key(key) # 初始化密钥
        self.length = AES.block_size  # 初始化数据块大小
        self.aes = AES.new(self.key, AES.MODE_ECB)  # 初始化AES,ECB模式的实例
        # 截断函数,去除填充的字符
        self.unpad = lambda date: date[0:-ord(date[-1])]
    # 使用SHA1方法生成的随机数,对key做处理
    def get_sha1prng_key(self, key):
        signature = hashlib.sha1(key.encode("utf-8")).digest()
        signature = hashlib.sha1(signature).digest()

        return signature[:16]

    def pad(self, text):
        """
        #填充函数,使被加密数据的字节码长度是block_size的整数倍
        """
        count = len(text.encode('utf-8'))
        add = self.length - (count % self.length)
        entext = text + (chr(add) * add)
        return entext

    def encrypt(self, originalData):  # 加密函数
        res = self.aes.encrypt(self.pad(originalData).encode("utf8"))
        encryptString = base64.b64encode(res).decode("utf8")
        return encryptString

    def decrypt(self, encrypedData):  # 解密函数
        res = base64.b64decode(encrypedData.encode("utf8"))
        msg = self.aes.decrypt(res).decode("utf8")
        return self.unpad(msg)

# 秘钥
secret = 'asdfasdasdfsdfasdf23434tgsdfhxcvau4IKf'
eg = EncryptUtil(secret)  # 这里密钥的长度可以是任意长度

data = "14464614210中文的001"
encryptData = eg.encrypt(data)
decryptData = "fH+Z38VD9uLdGLqpbm6InWxpDIYNyVnlzZHkfo9vK2k="
print("original value: " + data)
print("encrypted value: " + encryptData)
print("decrypted value: "+ eg.decrypt(decryptData))

python 代码运行结果输出:

original value: 14464614210中文的001
encrypted value: fH+Z38VD9uLdGLqpbm6InWxpDIYNyVnlzZHkfo9vK2k=
decrypted value: 14464614210中文的001

PHP代码实现

EncryptUtil.php

<?php
/**
 * EncryptUtil  对称加密
 * 对齐 Java的 AES/ECB/PKCS5Padding
 */
class EncryptUtil{
    /**
     * encrypt aes加密
     * @param    $originalData 要加密的数据
     * @param    $secretKey   加密的秘钥 
     * @return   
     */
    public static function encrypt($originalData, $secretKey){
        $secretKey = self::_sha1prng($secretKey);
        $iv = '';
        $data = openssl_encrypt($originalData, 'AES-128-ECB', $secretKey, OPENSSL_RAW_DATA, $iv);
        $data = base64_encode($data);
        return $data;
    }

    /**
     * decrypt aes解密
     * @param $encrypedData 要解密的数据
     * @param $secretKey 加密的秘钥 
     * @return  
     */
    public static function decrypt($encrypedData, $secretKey){
        $secretKey = self::_sha1prng($secretKey);
        $iv = '';
        $decrypted = openssl_decrypt(base64_decode($encrypedData), 'AES-128-ECB', $secretKey, OPENSSL_RAW_DATA, $iv);
        return $decrypted;
    }

    /**
     * SHA1PRNG算法
     * @param  $secretKey  加密的秘钥 
     * @return 
     */
    private static function _sha1prng($secretKey){
        return substr(openssl_digest(openssl_digest($secretKey, 'sha1', true), 'sha1', true), 0, 16);
    }
}

$aesModel = new EncryptUtil();
$data = '14464614210中文的001';
$secret = "asdfasdasdfsdfasdf23434tgsdfhxcvau4IKf";
//加密
$encryptData = EncryptUtil::encrypt($data, $secret);
//解密
$decryptData = EncryptUtil::decrypt($encryptData, $secret);
print_r("original value: " . $data."\n");
print("encrypted value: " . $encryptData."\n");
print("decrypted value: ". $decryptData."\n");

$encrypted = 'fH+Z38VD9uLdGLqpbm6InWxpDIYNyVnlzZHkfo9vK2k=';

$secret = 'asdfasdasdfsdfasdf23434tgsdfhxcvau4IKf';

var_dump(EncryptUtil::decrypt($encrypted, $secret));

PHP代码运行结果输出:

original value: 14464614210中文的001
encrypted value: fH+Z38VD9uLdGLqpbm6InWxpDIYNyVnlzZHkfo9vK2k=
decrypted value: 14464614210中文的001

C#代码实现

EncryptUtil.cpp

using System;
using System.Security.Cryptography;
using System.Text;

public class EncryptUtil
{
    private readonly byte[] _key;
    private readonly Aes _aes;

    public EncryptUtil(string key)
    {
        _key = GetSha1PrngKey(key);
        _aes = Aes.Create();
        _aes.Mode = CipherMode.ECB;
        _aes.Padding = PaddingMode.PKCS7;
        _aes.Key = _key;
    }

    private static byte[] GetSha1PrngKey(string key)
    {
        using (SHA1 sha1 = new SHA1CryptoServiceProvider())
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key);
            byte[] hash = sha1.ComputeHash(keyBytes);
            hash = sha1.ComputeHash(hash);
            byte[] finalKey = new byte[16];
            Array.Copy(hash, 0, finalKey, 0, 16);
            return finalKey;
        }
    }

    public string Encrypt(string originalData)
    {
        using (ICryptoTransform encryptor = _aes.CreateEncryptor())
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(originalData);
            byte[] result = encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
            return Convert.ToBase64String(result);
        }
    }

    public string Decrypt(string encryptedData)
    {
        using (ICryptoTransform decryptor = _aes.CreateDecryptor())
        {
            byte[] encryptedBytes = Convert.FromBase64String(encryptedData);
            byte[] result = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
            return Encoding.UTF8.GetString(result).TrimEnd('\0');
        }
    }
}

public class Program
{
    public static void Main()
    {
        string secret = "asdfasdasdfsdfasdf23434tgsdfhxcvau4IKf";
        EncryptUtil eg = new EncryptUtil(secret);
        string data = "14464614210中文的001";
        string encryptData = eg.Encrypt(data);
        string decryptData = "fH+Z38VD9uLdGLqpbm6InWxpDIYNyVnlzZHkfo9vK2k=";

        Console.WriteLine("Original value: " + data);
        Console.WriteLine("Encrypted value: " + encryptData);
        Console.WriteLine("Decrypted value: " + eg.Decrypt(decryptData));
    }
}

C#代码运行结果输出:

original value: 14464614210中文的001
encrypted value: fH+Z38VD9uLdGLqpbm6InWxpDIYNyVnlzZHkfo9vK2k=
decrypted value: 14464614210中文的001
  • 参考资料
返回顶部 示例中心 常见问题 智能客服 公众号
二维码