登录
原创

基于PHP和Java的AES加密

专栏聚合数据JUHE.CN
发布于 2020-09-30 阅读 2319
  • Java
  • PHP
原创

PHP

class AES7
{
    protected $aesKey = 'test';
 
    protected $iv = '';
 
    public function setIv($iv)
    {
        $this->iv = $iv;
    }
 
    public function setKey($key)
    {
        $this->aesKey = $key;
    }
 
    public function encrypt($data)
    {
        $encrypted = openssl_encrypt($data, 'aes-128-ecb', ($this->aesKey), OPENSSL_RAW_DATA, ($this->iv));
        return base64_encode($encrypted);
    }
 
    public function decrypt($data)
    {
        $encrypted = base64_decode($data);
        $decrypted = openssl_decrypt($encrypted, 'aes-128-ecb', ($this->aesKey), OPENSSL_RAW_DATA, ($this->iv));
        return $decrypted;
    }
}

Java

package com.jefferson.utils.test.crypt;
 
import org.apache.commons.codec.binary.base64;
 
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
 
import javax.crypto.Cipher;
 
import javax.crypto.spec.SecretKeySpec;
 
public class SecurityAESTool {
 
    /**
     * AES加密
     * 
     * @param str
     *            明文
     * @param key
     *            秘钥
     * @return
     */
    public static String encrypt(String str, String key) {
        byte[] crypted = null;
        try {
 
            SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
 
            String enStr = str;
            crypted = cipher.doFinal(enStr.getBytes("UTF-8"));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        String body = new String(base64.encodebase64(crypted));
        return body;
    }
 
    /**
     * AES解密
     * 
     * @param input
     * @param key
     * @return
     */
    public static String decrypt(String input, String key) {
        byte[] output = null;
        String body = null;
        if (input == null || key == null) {
            return null;
        }
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            byte[] b = base64.decodebase64(input);
            // 解密
            output = cipher.doFinal(b);
            body = new String(output, "UTF-8");
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return body;
    }
 
    public static void main(String[] args) throws UnsupportedEncodingException {
        String key = "1234567812345678";// 密钥
        String data = "12345678"; // 明文
 
        String enStr = SecurityAESTool.encrypt(data, key);
        System.out.println(URLEncoder.encode(enStr, "UTF-8"));
    }
}

评论区

DDwyane
20粉丝

我饿了,要睡觉了~

1

0

0

举报