PHP7 解决 java对应的 AES/ECB/PKCS5Padding 算法

先点击链接了解一下算法吧
在线生成AES加密

java

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class aes {
    //加密方法 str为传输的值 key取商户私钥字符串的前16位
    public static String aesEncrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
        return new BASE64Encoder().encode(bytes);
    }

    public static String aesDecrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = new BASE64Decoder().decodeBuffer(str);
        bytes = cipher.doFinal(bytes);
        return new String(bytes, "utf-8");
    }
}

php


/**
 * Created by PhpStorm.
 * User: Shinelon
 * Date: 2018/7/19
 * Time: 14:22
 */

class AES
{
   public static function encrypt($data, $key) {
       $data =  openssl_encrypt($data, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA);
       return base64_encode($data);
   }

    public static function decrypt($data, $key) {
        $encrypted = base64_decode($data);
        return openssl_decrypt($encrypted, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA);
    }
}

AES/ECB/PKCS5Padding说明

  • AES:加密算法
  • ECB:模式
  • PKCS5Padding:补码方式

你可能感兴趣的:(web,linux)