PHP7和Java聯調AES CBC加解密

因爲對接不少第三方系統常常遇到aes的加解密,這裏作個簡單的記錄。php

Java代碼:html

package com.pft.api.util;

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

public class AESUtil {

	private static final String IV_STRING = "初始化向量";

	public static String encryptAES(String content, String key) {
		try {
			byte[] byteContent = content.getBytes("UTF-8");
			// 注意,爲了能與 iOS 統一
			// 這裏的 key 不能夠使用 KeyGenerator、SecureRandom、SecretKey 生成
			byte[] enCodeFormat = key.getBytes();
			SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
			byte[] initParam = IV_STRING.getBytes();
			IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
			// 指定加密的算法、工做模式和填充方式
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
			byte[] encryptedBytes = cipher.doFinal(byteContent);
			// 一樣對加密後數據進行 base64 編碼
			Base64.Encoder encoder = Base64.getEncoder();
			return encoder.encodeToString(encryptedBytes);
		} catch (Exception e) {
		}
		return null;
	}

	public static String decryptAES(String content, String key) {
		try {
			// base64 解碼
			Base64.Decoder decoder = Base64.getDecoder();
			byte[] encryptedBytes = decoder.decode(content);
			byte[] enCodeFormat = key.getBytes();
			SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
			byte[] initParam = IV_STRING.getBytes();
			IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
			byte[] result = cipher.doFinal(encryptedBytes);
			return new String(result, "UTF-8");
		} catch (Exception e) {
		}
		return null;
	}

	public static void main(String[] args) {
		String content = "{\"code\":\"1544496569178\",\"name\":\"test\",\"number\":\"123444\"}";
		String key = "asdfghjklzxcvbnm";
		String s = encryptAES(content, key);
		System.out.println(s);
	}

}

複製代碼

PHP代碼:java

class Aes {
    private $secretKey = '密鑰';
    private $iv        = '初始化向量';
    public function decode($secretData){
        return openssl_decrypt(base64_decode($secretData),'AES-128-CBC',$this->secretKey,OPENSSL_RAW_DATA,$this->iv);
    }

    public function encode($data){
        $data = base64_encode(openssl_encrypt($data, 'AES-128-CBC', $this->secretKey, OPENSSL_RAW_DATA, $this->iv));
        return $data;
    }
}
複製代碼

剛開始PHP端一直失敗的緣由是$iv對方沒有提供,本身也忽略了這個參數; 另外就是要注意填充方式:OPENSSL_RAW_DATAOPENSSL_ZERO_PADDING算法

擴展閱讀:關於mcrypt_encrypt和openssl_encrypt加密結果不一致的解決api

相關文章
相關標籤/搜索