package com.friday.custody.service.trustService.csc.utils;

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

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

public class BlowfishUtil {
	public static String encrypt(String src, String key) throws Exception {
		byte[] byteKey = key.getBytes(StandardCharsets.UTF_8);
		byte[] byteSrc = src.getBytes(StandardCharsets.UTF_8);
		String hex = "";
		byte[] encrypted = encrypt(byteSrc, byteKey);
		 for(int i = 0; i < encrypted.length; i++) {  
		        hex += Integer.toHexString(encrypted[i] & 0xFF);
		 }
		 System.out.println("jdk自带---------"+ hex);
		
		return Hex.encodeHexString(encrypted);

	}

	public static String decrypt(String encrypted, String key) throws Exception {
		byte[] bytes = Hex.decodeHex(encrypted.toCharArray());
		byte[] byteKey = key.getBytes(StandardCharsets.UTF_8);

		byte[] after = decrypt(bytes, byteKey);

		return new String(after, "UTF-8");

	}

	public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
		SecretKey secretKey = new SecretKeySpec(key, "Blowfish");

		Cipher cipher = Cipher.getInstance("Blowfish");

		cipher.init(Cipher.ENCRYPT_MODE, secretKey);

		return cipher.doFinal(src);

	}

	public static byte[] decrypt(byte[] encrypted, byte[] key) throws Exception {

		SecretKey secretKey = new SecretKeySpec(key, "Blowfish");

		Cipher cipher = Cipher.getInstance("Blowfish");

		cipher.init(Cipher.DECRYPT_MODE, secretKey);

		return cipher.doFinal(encrypted);

	}

}