⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 encryptbean.java

📁 “JSP数据库项目案例导航”一书从第一章到第十一章各章实例的源程序文件以及数据库文件。 注意: 1. 本书中的案例提供的数据库环境不同
💻 JAVA
字号:
//实现加密,解密功能
package my;

import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
import sun.misc.*;

// PBEWithMD5AndDES , PBEWithSHAAndBlowfish , PBEWithSHAAnd128BitRC4 , PBEWithSHAAndIDEA-CBC , PBEWithSHAAnd3-KeyTripleDES-CBC , PBEWithSHAAndTwofish-CBC
//import com.isnetworks.base64.*;

public class PBEBean extends Object
{
	private static int ITERATIONS = 1000;
	//加密函数
	private static String encrypt(char[] password,String plaintext) throws Exception
	{
		byte[] salt= new byte[8];
		Random random = new Random();
		random.nextBytes(salt);

		PBEKeySpec keySpec = new PBEKeySpec(password);

		SecretKeyFactory  keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

		SecretKey key = keyFactory.generateSecret(keySpec);

		PBEParameterSpec paramSpec = new PBEParameterSpec(salt,ITERATIONS);

		Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
		cipher.init(Cipher.ENCRYPT_MODE,key,paramSpec);

		byte[] ciphertext = cipher.doFinal(plaintext.getBytes());

		BASE64Encoder encoder = new BASE64Encoder();
		String saltString = encoder.encode(salt);
		String ciphertextString = encoder.encode(ciphertext);
		return saltString+ciphertextString;
	}

	public String setPass(String plaintext) throws Exception
	{
		String strpasswd = "hg_oa_kjb";
		char [] cpasswd = strpasswd.toCharArray();
		return encrypt(cpasswd,plaintext);
	}

	//解密函数
	private static String decrypt(char[] password,String text) throws Exception
	{
		String salt = text.substring(0,12);
		String ciphertext = text.substring(12,text.length());
	
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] saltArray = decoder.decodeBuffer(salt);
		byte[] ciphertextArray = decoder.decodeBuffer(ciphertext);

		PBEKeySpec keySpec = new PBEKeySpec(password);
		SecretKeyFactory  keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
		SecretKey key = keyFactory.generateSecret(keySpec);
		PBEParameterSpec paramSpec = new PBEParameterSpec(saltArray,ITERATIONS);

		Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
		cipher.init(Cipher.DECRYPT_MODE,key,paramSpec);

		byte[] plaintextArray = cipher.doFinal(ciphertextArray);
		return new String(plaintextArray);
	}
	
	public String getPass(String text) throws Exception
	{
		String strpasswd = "hg_oa_kjb";
		char [] cpasswd = strpasswd.toCharArray();
		return decrypt(cpasswd,text);
	}

	public static void main(String args[]) throws Exception
	{
		System.out.println("Starting..........");

		PBEBean pbean = new PBEBean();
		System.out.println(pbean.setPass("word_text"));
		System.out.println(pbean.getPass(pbean.setPass("word_text")));

		System.out.println("Ending..........");
	}
};

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -