php與java對稱加密解密

 /**
     * 加密
     * @param $string
     * @param $key
     * @return false|string
     */
    public function _encrypt($string, $key='')
    {
        // 對接java,服務商做的AES加密通過SHA1PRNG算法(只要password一樣,每次生成的數組都是一樣的),Java的加密源碼翻譯php如下:
        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);

        // openssl_encrypt 加密不同Mcrypt,對祕鑰長度要求,超出16加密結果不變
        $data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);

        $data = strtolower(bin2hex($data));

        return $data;
    }
    /**
     * 解密
     * @param string $string 需要解密的字符串
     * @param string $key 密鑰
     * @return string
     */
    public function _decrypt($string, $key='')
    {

        // 對接java,服務商做的AES加密通過SHA1PRNG算法(只要password一樣,每次生成的數組都是一樣的),Java的加密源碼翻譯php如下:
        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);

        $decrypted = openssl_decrypt(hex2bin($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);

        return  json_decode($decrypted,true);
    }

```php

```java
package com.gdin.yhk.common.util;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * AES 加密 ECB 模式 PKCS7Padding 填充模式
 * 
 * @author
 *
 */
public class Demo {

	/**
	 * 加密/解密算法 / 工作模式 / 填充方式
	 * Java 6支持PKCS5Padding填充方式
	 * Bouncy Castle支持PKCS7Padding填充方式
	 */
	protected static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";
	
	protected static final String KEY_ALGORITHM = "AES";
	
	protected static final String ENCRYPT_CHARSET = "UTF-8";
	
	static {
		//如果是PKCS7Padding填充方式,則必須加上下面這行
		Security.addProvider(new BouncyCastleProvider());
	}
	
	protected static SecretKeySpec createKey(String password, Integer keysize) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
		
		// 第一種方法在solaris 或部分 linux上,每次調用會生成不同的KEY,所以改用第二種
//		SecureRandom secureRandom = new SecureRandom(password.getBytes(ENCRYPT_CHARSET));
//		kgen.init(128, secureRandom);
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(password.getBytes(ENCRYPT_CHARSET));
		kgen.init(keysize, secureRandom);
		
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_ALGORITHM);
		return key;
	}
	
	public static void main(String[] args) throws Exception {
		String content = "{\"paperNum\":\"440101200001011111\",\"phone\":\"13800000000\"}";
		
		String password = "0c23c0ae-dfe3-4cec-9b6e-83d7fd1f2485";
		try {
			System.out.println("原內容:\n"+content);
			String tempContent = encrypt(content,password);
			System.out.println("加密後:\n"+tempContent);
			tempContent = decrypt(tempContent, password);
			System.out.println("解密後:\n"+tempContent);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * AES加密
	 * 
	 * @param content  源字符串
	 * @param password 密鑰
	 * @return 加密後的密文
	 */
	public static String encrypt(String content, String password) {
		try {
			SecretKeySpec key = createKey(password, 128);
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");// 創建密碼器
			byte[] byteContent = content.getBytes(ENCRYPT_CHARSET);
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			if (result != null && result.length > 0) {
				return parseByte2HexStr(result);
			}
		} catch (Exception e) {
		}
		return "";
	}

	/**
	 * AES解密
	 * 
	 * @param content  加密後的密文
	 * @param password 密鑰
	 * @return 源字符串
	 */
	public static String decrypt(String content, String password) {
		try {
			byte[] newContent = parseHexStr2Byte(content);// 將16進制轉換爲二進制
			SecretKeySpec key = createKey(password, 128);
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");// 創建密碼器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(newContent);
			if (result != null && result.length > 0) {
				return new String(result, ENCRYPT_CHARSET);
			}
		} catch (Exception e) {
		}
		return "";
	}
	
	/**
	 * 將二進制轉換成16進制
	 * 
	 * @param buf
	 * @return
	 */
	protected static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		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
	 */
	protected 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;
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章