PHP和JAVA AES加解密问题

1.问题

        php加密的java不能正常机密,java加密的php不能正常解密

2.前置参数

        key 32位

        iv 16位

3.问题解决

        因为key是32位的,所以参数需要$method=AES-256-CBC,$options=1

 4.PHP代码

secret_key = isset($key) ? $key : 'morefun';

        $this->method = $method;

        $this->iv = $iv;

        $this->options = $options;
    }

    /**
     * 加密方法,对数据进行加密,返回加密后的数据
     *
     * @param string $data 要加密的数据
     *
     * @return string
     *
     */
    public function encrypt($data)
    {

        $result = openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
        $result = base64_encode($result);
        return $result;
    }

    /**
     * 解密方法,对数据进行解密,返回解密后的数据
     *
     * @param string $data 要解密的数据
     *
     * @return string
     *
     */
    public function decrypt($data)
    {

        return openssl_decrypt(base64_decode($data), $this->method, $this->secret_key, $this->options, $this->iv);
    }
}

5.java代码

package com.xxx.cn.utils;

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

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

public class Test {

    public static String encrypt(String secretKey, String iv, String strToEncrypt) {
        if (strToEncrypt == null || strToEncrypt.isEmpty()) {
            return strToEncrypt;
        }
        try {
            Cipher cipher = getCipher(secretKey, iv, Cipher.ENCRYPT_MODE);
            return
                    Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8
                    )));
        } catch (Exception exp) {
            exp.printStackTrace();
            return "";
        }
    }

    private static Cipher getCipher(String secretKey, String iv, int cipherMode)
            throws Exception {
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
        SecretKeySpec secretKeySpec = new
                SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(cipherMode, secretKeySpec, ivSpec);
        return cipher;
    }

    public static void main(String[] args) {
        String s = "xxxx";

        System.out.println(encrypt("95D03jGYjs1wTpg0PfKWgyvL2WfLXQ1y", "GETwRqKWgqtRO8Ew", s));
    }

}

你可能感兴趣的:(php,java,aes)