?? encryptbean.java
字號(hào):
//實(shí)現(xiàn)加密,解密功能
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;
//加密函數(shù)
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);
}
//解密函數(shù)
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..........");
}
};
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -