可變在這里含義很簡單 就是最終的加密結(jié)果是可變的 而非必需按標(biāo)準(zhǔn)MD 加密實現(xiàn) Java類庫security中的MessageDigest類就提供了MD 加密的支持 實現(xiàn)起來非常方便 為了實現(xiàn)更多效果 我們可以如下設(shè)計MD 工具類
稱多網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),稱多網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為稱多成百上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢,請找那個售后服務(wù)好的稱多做網(wǎng)站的公司定做!
Java代碼
package ** ** util;
import java security MessageDigest;
/**
* 標(biāo)準(zhǔn)MD 加密方法 使用java類庫的security包的MessageDigest類處理
* @author Sarin
*/
public class MD {
/**
* 獲得MD 加密密碼的方法
*/
public static String getMD ofStr(String origString) {
String origMD = null;
try {
MessageDigest md = MessageDigest getInstance( MD );
byte[] result = md digest(origString getBytes());
origMD = byteArray HexStr(result);
} catch (Exception e) {
e printStackTrace();
}
return origMD ;
}
/**
* 處理字節(jié)數(shù)組得到MD 密碼的方法
*/
private static String byteArray HexStr(byte[] bs) {
StringBuffer *** = new StringBuffer();
for (byte b : bs) {
*** append(byte HexStr(b));
}
return *** toString();
}
/**
* 字節(jié)標(biāo)準(zhǔn)移位轉(zhuǎn)十六進制方法
*/
private static String byte HexStr(byte b) {
String hexStr = null;
int n = b;
if (n ) {
//若需要自定義加密 請修改這個移位算法即可
n = b x F + ;
}
hexStr = Integer toHexString(n / ) + Integer toHexString(n % );
return hexStr toUpperCase();
}
/**
* 提供一個MD 多次加密方法
*/
public static String getMD ofStr(String origString int times) {
String md = getMD ofStr(origString);
for (int i = ; i times ; i++) {
md = getMD ofStr(md );
}
return getMD ofStr(md );
}
/**
* 密碼驗證方法
*/
public static boolean verifyPassword(String inputStr String MD Code) {
return getMD ofStr(inputStr) equals(MD Code);
}
/**
* 重載一個多次加密時的密碼驗證方法
*/
public static boolean verifyPassword(String inputStr String MD Code int times) {
return getMD ofStr(inputStr times) equals(MD Code);
}
/**
* 提供一個測試的主函數(shù)
*/
public static void main(String[] args) {
System out println( : + getMD ofStr( ));
System out println( : + getMD ofStr( ));
System out println( sarin: + getMD ofStr( sarin ));
System out println( : + getMD ofStr( ));
}
}
可以看出實現(xiàn)的過程非常簡單 因為由java類庫提供了處理支持 但是要清楚的是這種方式產(chǎn)生的密碼不是標(biāo)準(zhǔn)的MD 碼 它需要進行移位處理才能得到標(biāo)準(zhǔn)MD 碼 這個程序的關(guān)鍵之處也在這了 怎么可變?調(diào)整移位算法不就可變了么!不進行移位 也能夠得到 位的密碼 這就不是標(biāo)準(zhǔn)加密了 只要加密和驗證過程使用相同的算法就可以了
MD 加密還是很安全的 像CMD 那些窮舉破解的只是針對標(biāo)準(zhǔn)MD 加密的結(jié)果進行的 如果自定義移位算法后 它還有效么?可以說是無解的了 所以MD 非常安全可靠
為了更可變 還提供了多次加密的方法 可以在MD 基礎(chǔ)之上繼續(xù)MD 就是對 位的第一次加密結(jié)果再MD 恩 這樣去破解?沒有任何意義
這樣在MIS系統(tǒng)中使用 安全可靠 歡迎交流 希望對使用者有用
我們最后看看由MD 加密算法實現(xiàn)的類 那是非常龐大的
Java代碼
import java lang reflect *;
/**
* **********************************************
* md 類實現(xiàn)了RSA Data Security Inc 在提交給IETF
* 的RFC 中的MD message digest 算法
* ***********************************************
*/
public class MD {
/* 下面這些S S 實際上是一個 * 的矩陣 在原始的C實現(xiàn)中是用#define 實現(xiàn)的
這里把它們實現(xiàn)成為static final是表示了只讀 切能在同一個進程空間內(nèi)的多個
Instance間共享*/
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final int S = ;
static final byte[] PADDING = {
};
/* 下面的三個成員是MD 計算過程中用到的 個核心數(shù)據(jù) 在原始的C實現(xiàn)中
被定義到MD _CTX結(jié)構(gòu)中
*/
private long[] state = new long[ ]; // state (ABCD)
private long[] count = new long[ ]; // number of bits modulo ^ (l *** first)
private byte[] buffer = new byte[ ]; // input buffer
/* digestHexStr是MD 的唯一一個公共成員 是最新一次計算結(jié)果的
進制ASCII表示
*/
public String digestHexStr;
/* digest 是最新一次計算結(jié)果的 進制內(nèi)部表示 表示 bit的MD 值
*/
private byte[] digest = new byte[ ];
/*
getMD ofStr是類MD 最主要的公共方法 入口參數(shù)是你想要進行MD 變換的字符串
返回的是變換完的結(jié)果 這個結(jié)果是從公共成員digestHexStr取得的.
*/
public String getMD ofStr(String inbuf) {
md Init();
md Update(inbuf getBytes() inbuf length());
md Final();
digestHexStr = ;
for (int i = ; i ; i++) {
digestHexStr += byteHEX(digest[i]);
}
return digestHexStr;
}
// 這是MD 這個類的標(biāo)準(zhǔn)構(gòu)造函數(shù) JavaBean要求有一個public的并且沒有參數(shù)的構(gòu)造函數(shù)
public MD () {
md Init();
return;
}
/* md Init是一個初始化函數(shù) 初始化核心變量 裝入標(biāo)準(zhǔn)的幻數(shù) */
private void md Init() {
count[ ] = L;
count[ ] = L;
///* Load magic initialization constants
state[ ] = x L;
state[ ] = xefcdab L;
state[ ] = x badcfeL;
state[ ] = x L;
return;
}
/* F G H I 是 個基本的MD 函數(shù) 在原始的MD 的C實現(xiàn)中 由于它們是
簡單的位運算 可能出于效率的考慮把它們實現(xiàn)成了宏 在java中 我們把它們
實現(xiàn)成了private方法 名字保持了原來C中的 */
private long F(long x long y long z) {
return (x y) | ((~x) z);
}
private long G(long x long y long z) {
return (x z) | (y (~z));
}
private long H(long x long y long z) {
return x ^ y ^ z;
}
private long I(long x long y long z) {
return y ^ (x | (~z));
}
/*
FF GG HH和II將調(diào)用F G H I進行近一步變換
FF GG HH and II transformations for rounds and
Rotation is separate from addition to prevent reputation
*/
private long FF(long a long b long c long d long x long s long ac) {
a += F(b c d) + x + ac;
a = ((int) a s) | ((int) a ( s));
a += b;
return a;
}
private long GG(long a long b long c long d long x long s long ac) {
a += G(b c d) + x + ac;
a = ((int) a s) | ((int) a ( s));
a += b;
return a;
}
private long HH(long a long b long c long d long x long s long ac) {
a += H(b c d) + x + ac;
a = ((int) a s) | ((int) a ( s));
a += b;
return a;
}
private long II(long a long b long c long d long x long s long ac) {
a += I(b c d) + x + ac;
a = ((int) a s) | ((int) a ( s));
a += b;
return a;
}
/*
md Update是MD 的主計算過程 inbuf是要變換的字節(jié)串 inputlen是長度 這個
函數(shù)由getMD ofStr調(diào)用 調(diào)用之前需要調(diào)用md init 因此把它設(shè)計成private的
*/
private void md Update(byte[] inbuf int inputLen) {
int i index partLen;
byte[] block = new byte[ ];
index = (int) (count[ ] ) x F;
// /* Update number of bits */
if ((count[ ] += (inputLen )) (inputLen ))
count[ ]++;
count[ ] += (inputLen );
partLen = index;
// Transform as many times as possible
if (inputLen = partLen) {
md Memcpy(buffer inbuf index partLen);
md Transform(buffer);
for (i = partLen; i + inputLen; i += ) {
md Memcpy(block inbuf i );
md Transform(block);
}
index = ;
} else
i = ;
///* Buffer remaining input */
md Memcpy(buffer inbuf index i inputLen i);
}
/*
md Final整理和填寫輸出結(jié)果
*/
private void md Final() {
byte[] bits = new byte[ ];
int index padLen;
///* Save number of bits */
Encode(bits count );
///* Pad out to mod
index = (int) (count[ ] ) x f;
padLen = (index ) ? ( index) : ( index);
md Update(PADDING padLen);
///* Append length (before padding) */
md Update(bits );
///* Store state in digest */
Encode(digest state );
}
/* md Memcpy是一個內(nèi)部使用的byte數(shù)組的塊拷貝函數(shù) 從input的inpos開始把len長度的
字節(jié)拷貝到output的outpos位置開始
*/
private void md Memcpy(byte[] output byte[] input int outpos int inpos int len) {
int i;
for (i = ; i len; i++)
output[outpos + i] = input[inpos + i];
}
/*
md Transform是MD 核心變換程序 有md Update調(diào)用 block是分塊的原始字節(jié)
*/
private void md Transform(byte block[]) {
long a = state[ ] b = state[ ] c = state[ ] d = state[ ];
long[] x = new long[ ];
Decode(x block );
/* Round */
a = FF(a b c d x[ ] S xd aa L); /* */
d = FF(d a b c x[ ] S xe c b L); /* */
c = FF(c d a b x[ ] S x dbL); /* */
b = FF(b c d a x[ ] S xc bdceeeL); /* */
a = FF(a b c d x[ ] S xf c fafL); /* */
d = FF(d a b c x[ ] S x c aL); /* */
c = FF(c d a b x[ ] S xa L); /* */
b = FF(b c d a x[ ] S xfd L); /* */
a = FF(a b c d x[ ] S x d L); /* */
d = FF(d a b c x[ ] S x b f afL); /* */
c = FF(c d a b x[ ] S xffff bb L); /* */
b = FF(b c d a x[ ] S x cd beL); /* */
a = FF(a b c d x[ ] S x b L); /* */
d = FF(d a b c x[ ] S xfd L); /* */
c = FF(c d a b x[ ] S xa eL); /* */
b = FF(b c d a x[ ] S x b L); /* */
/* Round */
a = GG(a b c d x[ ] S xf e L); /* */
d = GG(d a b c x[ ] S xc b L); /* */
c = GG(c d a b x[ ] S x e a L); /* */
b = GG(b c d a x[ ] S xe b c aaL); /* */
a = GG(a b c d x[ ] S xd f dL); /* */
d = GG(d a b c x[ ] S x L); /* */
c = GG(c d a b x[ ] S xd a e L); /* */
b = GG(b c d a x[ ] S xe d fbc L); /* */
a = GG(a b c d x[ ] S x e cde L); /* */
d = GG(d a b c x[ ] S xc d L); /* */
c = GG(c d a b x[ ] S xf d d L); /* */
b = GG(b c d a x[ ] S x a edL); /* */
a = GG(a b c d x[ ] S xa e e L); /* */
d = GG(d a b c x[ ] S xfcefa f L); /* */
c = GG(c d a b x[ ] S x f d L); /* */
b = GG(b c d a x[ ] S x d a c aL); /* */
/* Round */
a = HH(a b c d x[ ] S xfffa L); /* */
d = HH(d a b c x[ ] S x f L); /* */
c = HH(c d a b x[ ] S x d d L); /* */
b = HH(b c d a x[ ] S xfde cL); /* */
a = HH(a b c d x[ ] S xa beea L); /* */
d = HH(d a b c x[ ] S x bdecfa L); /* */
c = HH(c d a b x[ ] S xf bb b L); /* */
b = HH(b c d a x[ ] S xbebfbc L); /* */
a = HH(a b c d x[ ] S x b ec L); /* */
d = HH(d a b c x[ ] S xeaa faL); /* */
c = HH(c d a b x[ ] S xd ef L); /* */
b = HH(b c d a x[ ] S x d L); /* */
a = HH(a b c d x[ ] S xd d d L); /* */
d = HH(d a b c x[ ] S xe db e L); /* */
c = HH(c d a b x[ ] S x fa cf L); /* */
b = HH(b c d a x[ ] S xc ac L); /* */
/* Round */
a = II(a b c d x[ ] S xf L); /* */
d = II(d a b c x[ ] S x aff L); /* */
c = II(c d a b x[ ] S xab a L); /* */
b = II(b c d a x[ ] S xfc a L); /* */
a = II(a b c d x[ ] S x b c L); /* */
d = II(d a b c x[ ] S x f ccc L); /* */
c = II(c d a b x[ ] S xffeff dL); /* */
b = II(b c d a x[ ] S x dd L); /* */
a = II(a b c d x[ ] S x fa e fL); /* */
d = II(d a b c x[ ] S xfe ce e L); /* */
c = II(c d a b x[ ] S xa L); /* */
b = II(b c d a x[ ] S x e a L); /* */
a = II(a b c d x[ ] S xf e L); /* */
d = II(d a b c x[ ] S xbd af L); /* */
c = II(c d a b x[ ] S x ad d bbL); /* */
b = II(b c d a x[ ] S xeb d L); /* */
state[ ] += a;
state[ ] += b;
state[ ] += c;
state[ ] += d;
}
/*Encode把long數(shù)組按順序拆成byte數(shù)組 因為java的long類型是 bit的
只拆低 bit 以適應(yīng)原始C實現(xiàn)的用途
*/
private void Encode(byte[] output long[] input int len) {
int i j;
for (i = j = ; j len; i++ j += ) {
output[j] = (byte) (input[i] xffL);
output[j + ] = (byte) ((input[i] ) xffL);
output[j + ] = (byte) ((input[i] ) xffL);
output[j + ] = (byte) ((input[i] ) xffL);
}
}
/*Decode把byte數(shù)組按順序合成成long數(shù)組 因為java的long類型是 bit的
只合成低 bit 高 bit清零 以適應(yīng)原始C實現(xiàn)的用途
*/
private void Decode(long[] output byte[] input int len) {
int i j;
for (i = j = ; j len; i++ j += )
output[i] = b iu(input[j]) | (b iu(input[j + ]) ) | (b iu(input[j + ]) )
| (b iu(input[j + ]) );
return;
}
/*
b iu是我寫的一個把byte按照不考慮正負(fù)號的原則的"升位"程序 因為java沒有unsigned運算
*/
public static long b iu(byte b) {
return b ? b x F + : b;
}
/*byteHEX() 用來把一個byte類型的數(shù)轉(zhuǎn)換成十六進制的ASCII表示
因為java中的byte的toString無法實現(xiàn)這一點 我們又沒有C語言中的
sprintf(outbuf % X ib)
*/
public static String byteHEX(byte ib) {
char[] Digit = { A B C D E F };
char[] ob = new char[ ];
ob[ ] = Digit[(ib ) X F];
ob[ ] = Digit[ib X F];
String s = new String(ob);
return s;
}
public static void main(String args[]) {
MD m = new MD ();
if (Array getLength(args) == ) { //如果沒有參數(shù) 執(zhí)行標(biāo)準(zhǔn)的Test Suite
System out println( MD Test suite: );
System out println( MD (\ \ ): + m getMD ofStr( ));
System out println( MD (\ a\ ): + m getMD ofStr( a ));
System out println( MD (\ abc\ ): + m getMD ofStr( abc ));
System out println( MD (\ \ ): + m getMD ofStr( ));
System out println( MD (\ \ ): + m getMD ofStr( ));
System out println( MD (\ message digest\ ): + m getMD ofStr( message digest ));
System out println( MD (\ abcdefghijklmnopqrstuvwxyz\ ): + m getMD ofStr( abcdefghijklmnopqrstuvwxyz ));
System out println( MD (\ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz \ ):
+ m getMD ofStr( ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ));
} else
System out println( MD ( + args[ ] + )= + m getMD ofStr(args[ ]));
}
lishixinzhi/Article/program/Java/hx/201311/26604
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
/**
文件名:FileEncrypter.java
JDK:1.40以上
說明:文件加密
加密方法:三重DES加密
加密過程:對選中的文件加密后在同文件夾下生成一個增加了".tdes"
擴展名的加密文件
解密過程:對選中的加密文件(必須有".tdes"擴展名)進行解密
*/
public class FileEncrypter extends JFrame{
public static final int WIDTH = 550;
public static final int HEIGHT = 200;
public static void main(String args[]) {
FileEncrypter fe = new FileEncrypter();
fe.show();
}
FileEncrypter(){
this.setSize(WIDTH,HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
this.setLocation((screenSize.width - WIDTH)/2,
(screenSize.height - HEIGHT)/2);
this.setTitle("文件加密器(TriDES)");
Container c = this.getContentPane();
c.setLayout( new FlowLayout());
final FilePanel fp = new FilePanel("文件選擇");
c.add(fp);
final KeyPanel pp = new KeyPanel("密碼");
c.add(pp);
JButton jbE = new JButton("加密");
c.add(jbE);
jbE.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
File file = new File(fp.getFileName());
if (file.exists())
encrypt(file.getAbsoluteFile(),pp.getKey());
else
JOptionPane.showMessageDialog(
null,"請選擇文件!","提示",JOptionPane.OK_OPTION);
}
});
JButton jbD = new JButton("解密");
c.add(jbD);
jbD.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
File file = new File(fp.getFileName());
if (file.exists())
decrypt(file.getAbsoluteFile(),pp.getKey());
else
JOptionPane.showMessageDialog(
null,"請選擇文件!","提示",JOptionPane.OK_OPTION);
}
});
}
/**
加密函數(shù)
輸入:
要加密的文件,密碼(由0-F組成,共48個字符,表示3個8位的密碼)如:
AD67EA2F3BE6E5ADD368DFE03120B5DF92A8FD8FEC2F0746
其中:
AD67EA2F3BE6E5AD DES密碼一
D368DFE03120B5DF DES密碼二
92A8FD8FEC2F0746 DES密碼三
輸出:
對輸入的文件加密后,保存到同一文件夾下增加了".tdes"擴展名的文件中。
*/
private void encrypt(File fileIn,String sKey){
try{
if(sKey.length() == 48){
byte[] bytK1 = getKeyByStr(sKey.substring(0,16));
byte[] bytK2 = getKeyByStr(sKey.substring(16,32));
byte[] bytK3 = getKeyByStr(sKey.substring(32,48));
FileInputStream fis = new FileInputStream(fileIn);
byte[] bytIn = new byte[(int)fileIn.length()];
for(int i = 0;iFILEIN.LENGTH();I++){
bytIn[i] = (byte)fis.read();
}
//加密
byte[] bytOut = encryptByDES(encryptByDES(
encryptByDES(bytIn,bytK1),bytK2),bytK3);
String fileOut = fileIn.getPath() + ".tdes";
FileOutputStream fos = new FileOutputStream(fileOut);
for(int i = 0;iBYTOUT.LENGTH;I++){
fos.write((int)bytOut[i]);
}
fos.close();
JOptionPane.showMessageDialog(
this,"加密成功!","提示",JOptionPane.OK_OPTION);
}else
JOptionPane.showMessageDialog(
this,"密碼長度必須等于48!","錯誤信息",JOptionPane.ERROR_MESSAGE);
}catch(Exception e){
e.printStackTrace();
}
}
/**
解密函數(shù)
輸入:
要解密的文件,密碼(由0-F組成,共48個字符,表示3個8位的密碼)如:
AD67EA2F3BE6E5ADD368DFE03120B5DF92A8FD8FEC2F0746
其中:
AD67EA2F3BE6E5AD DES密碼一
D368DFE03120B5DF DES密碼二
92A8FD8FEC2F0746 DES密碼三
輸出:
對輸入的文件解密后,保存到用戶指定的文件中。
*/
private void decrypt(File fileIn,String sKey){
try{
if(sKey.length() == 48){
String strPath = fileIn.getPath();
if(strPath.substring(strPath.length()-5).toLowerCase().equals(".tdes"))
strPath = strPath.substring(0,strPath.length()-5);
else{
JOptionPane.showMessageDialog(
this,"不是合法的加密文件!","提示",JOptionPane.OK_OPTION);
return;
}
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setSelectedFile(new File(strPath));
//用戶指定要保存的文件
int ret = chooser.showSaveDialog(this);
if(ret==JFileChooser.APPROVE_OPTION){
byte[] bytK1 = getKeyByStr(sKey.substring(0,16));
byte[] bytK2 = getKeyByStr(sKey.substring(16,32));
byte[] bytK3 = getKeyByStr(sKey.substring(32,48));
FileInputStream fis = new FileInputStream(fileIn);
byte[] bytIn = new byte[(int)fileIn.length()];
for(int i = 0;iFILEIN.LENGTH();I++){
bytIn[i] = (byte)fis.read();
}
//解密
byte[] bytOut = decryptByDES(decryptByDES(
decryptByDES(bytIn,bytK3),bytK2),bytK1);
File fileOut = chooser.getSelectedFile();
fileOut.createNewFile();
FileOutputStream fos = new FileOutputStream(fileOut);
for(int i = 0;iBYTOUT.LENGTH;I++){
fos.write((int)bytOut[i]);
}
fos.close();
JOptionPane.showMessageDialog(
this,"解密成功!","提示",JOptionPane.OK_OPTION);
}
}else
JOptionPane.showMessageDialog(
this,"密碼長度必須等于48!","錯誤信息",JOptionPane.ERROR_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(
this,"解密失敗,請核對密碼!","提示",JOptionPane.OK_OPTION);
}
}
/**
用DES方法加密輸入的字節(jié)
bytKey需為8字節(jié)長,是加密的密碼
*/
private byte[] encryptByDES(byte[] bytP,byte[] bytKey) throws Exception{
DESKeySpec desKS = new DESKeySpec(bytKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES");
cip.init(Cipher.ENCRYPT_MODE,sk);
return cip.doFinal(bytP);
}
/**
用DES方法解密輸入的字節(jié)
bytKey需為8字節(jié)長,是解密的密碼
*/
private byte[] decryptByDES(byte[] bytE,byte[] bytKey) throws Exception{
DESKeySpec desKS = new DESKeySpec(bytKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES");
cip.init(Cipher.DECRYPT_MODE,sk);
return cip.doFinal(bytE);
}
/**
輸入密碼的字符形式,返回字節(jié)數(shù)組形式。
如輸入字符串:AD67EA2F3BE6E5AD
返回字節(jié)數(shù)組:{173,103,234,47,59,230,229,173}
*/
private byte[] getKeyByStr(String str){
byte[] bRet = new byte[str.length()/2];
for(int i=0;iSTR.LENGTH()
Integer itg =
new Integer(16*getChrInt(str.charAt(2*i)) + getChrInt(str.charAt(2*i+1)));
bRet[i] = itg.byteValue();
}
return bRet;
}
/**
計算一個16進制字符的10進制值
輸入:0-F
*/
private int getChrInt(char chr){
int iRet=0;
if(chr=="0".charAt(0)) iRet = 0;
if(chr=="1".charAt(0)) iRet = 1;
if(chr=="2".charAt(0)) iRet = 2;
if(chr=="3".charAt(0)) iRet = 3;
if(chr=="4".charAt(0)) iRet = 4;
if(chr=="5".charAt(0)) iRet = 5;
if(chr=="6".charAt(0)) iRet = 6;
if(chr=="7".charAt(0)) iRet = 7;
if(chr=="8".charAt(0)) iRet = 8;
if(chr=="9".charAt(0)) iRet = 9;
if(chr=="A".charAt(0)) iRet = 10;
if(chr=="B".charAt(0)) iRet = 11;
if(chr=="C".charAt(0)) iRet = 12;
if(chr=="D".charAt(0)) iRet = 13;
if(chr=="E".charAt(0)) iRet = 14;
if(chr=="F".charAt(0)) iRet = 15;
return iRet;
}
}
/**
文件選擇組件。
*/
class FilePanel extends JPanel{
FilePanel(String str){
JLabel label = new JLabel(str);
JTextField fileText = new JTextField(35);
JButton chooseButton = new JButton("瀏覽...");
this.add(label);
this.add(fileText);
this.add(chooseButton);
clickAction ca = new clickAction(this);
chooseButton.addActionListener(ca);
}
public String getFileName(){
JTextField jtf = (JTextField)this.getComponent(1);
return jtf.getText();
}
private class clickAction implements ActionListener{
clickAction(Component c){
cmpt = c;
}
public void actionPerformed(ActionEvent event){
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
int ret = chooser.showOpenDialog(cmpt);
if(ret==JFileChooser.APPROVE_OPTION){
JPanel jp = (JPanel)cmpt;
JTextField jtf = (JTextField)jp.getComponent(1);
jtf.setText(chooser.getSelectedFile().getPath());
}
}
private Component cmpt;
}
}
/**
密碼生成組件。
*/
class KeyPanel extends JPanel{
KeyPanel(String str){
JLabel label = new JLabel(str);
JTextField fileText = new JTextField(35);
JButton chooseButton = new JButton("隨機產(chǎn)生");
this.add(label);
this.add(fileText);
this.add(chooseButton);
clickAction ca = new clickAction(this);
chooseButton.addActionListener(ca);
}
//返回生成的密碼(48個字符長度)
public String getKey(){
JTextField jtf = (JTextField)this.getComponent(1);
return jtf.getText();
}
private class clickAction implements ActionListener{
clickAction(Component c){
cmpt = c;
}
public void actionPerformed(ActionEvent event){
try{
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56);
Key ke = kg.generateKey();
byte[] bytK1 = ke.getEncoded();
ke = kg.generateKey();
byte[] bytK2 = ke.getEncoded();
ke = kg.generateKey();
byte[] bytK3 = ke.getEncoded();
JPanel jp = (JPanel)cmpt;
JTextField jtf = (JTextField)jp.getComponent(1);
jtf.setText(getByteStr(bytK1)+getByteStr(bytK2)+getByteStr(bytK3));
}catch(Exception e){
e.printStackTrace();
}
}
private String getByteStr(byte[] byt){
String strRet = "";
for(int i=0;iBYT.LENGTH;I++){
//System.out.println(byt[i]);
strRet += getHexValue((byt[i]240)/16);
strRet += getHexValue(byt[i]15);
}
return strRet;
}
private String getHexValue(int s){
String sRet=null;
switch (s){
case 0: sRet = "0";break;
case 1: sRet = "1";break;
case 2: sRet = "2";break;
case 3: sRet = "3";break;
case 4: sRet = "4";break;
case 5: sRet = "5";break;
case 6: sRet = "6";break;
case 7: sRet = "7";break;
case 8: sRet = "8";break;
case 9: sRet = "9";break;
case 10: sRet = "A";break;
case 11: sRet = "B";break;
case 12: sRet = "C";break;
case 13: sRet = "D";break;
case 14: sRet = "E";break;
case 15: sRet = "F";
}
return sRet;
}
private Component cmpt;
}
}
以下兩個類可以很方便的完成字符串的加密和解密
加密 CryptHelper encrypt(password)
解密 CrypHelper decrypt(password)
代碼如下
CryptUtils java
[java]
package gdie lab crypt;
import java io IOException;
import javax crypto Cipher;
import javax crypto KeyGenerator;
import javax crypto SecretKey;
import apache xerces internal impl dv util Base ;
public class CryptUtils {
private static String Algorithm = DES ;
private static byte[] DEFAULT_KEY=new byte[] { };
private static String VALUE_ENCODING= UTF ;
/**
* 生成密鑰
*
* @return byte[] 返回生成的密鑰
* @throws exception
*???????????? 扔出異常
*/
public static byte[] getSecretKey() throws Exception {
KeyGenerator keygen = KeyGenerator getInstance(Algorithm)
SecretKey deskey = keygen generateKey()
// if (debug ) System out println ( 生成密鑰 +byte hex (deskey getEncoded
// ()))
return deskey getEncoded()
}
/**
* 將指定的數(shù)據(jù)根據(jù)提供的密鑰進行加密
*
* @param input
*??????????? 需要加密的數(shù)據(jù)
* @param key
*??????????? 密鑰
* @return byte[] 加密后的數(shù)據(jù)
* @throws Exception
*/
public static byte[] encryptData(byte[] input byte[] key) throws Exception {
SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)
// if (debug )
// {
// System out println ( 加密前的二進串 +byte hex (input ))
// System out println ( 加密前的字符串 +new String (input ))
//
// }
Cipher c = Cipher getInstance(Algorithm)
c init(Cipher ENCRYPT_MODE deskey)
byte[] cipherByte = c doFinal(input)
// if (debug ) System out println ( 加密后的二進串 +byte hex (cipherByte ))
return cipherByte;
}
public static byte[] encryptData(byte[] input) throws Exception {
return encryptData(input DEFAULT_KEY)
}
/**
* 將給定的已加密的數(shù)據(jù)通過指定的密鑰進行解密
*
* @param input
*??????????? 待解密的數(shù)據(jù)
* @param key
*??????????? 密鑰
* @return byte[] 解密后的數(shù)據(jù)
* @throws Exception
*/
public static byte[] decryptData(byte[] input byte[] key) throws Exception {
SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)
// if (debug ) System out println ( 解密前的信息 +byte hex (input ))
Cipher c = Cipher getInstance(Algorithm)
c init(Cipher DECRYPT_MODE deskey)
byte[] clearByte = c doFinal(input)
// if (debug )
// {
// System out println ( 解密后的二進串 +byte hex (clearByte ))
// System out println ( 解密后的字符串 +(new String (clearByte )))
//
// }
return clearByte;
}
public static byte[] decryptData(byte[] input) throws Exception {
return decryptData(input DEFAULT_KEY)
}
/**
* 字節(jié)碼轉(zhuǎn)換成 進制字符串
*
* @param byte[] b 輸入要轉(zhuǎn)換的字節(jié)碼
* @return String 返回轉(zhuǎn)換后的 進制字符串
*/
public static String byte hex(byte[] bytes) {
StringBuilder hs = new StringBuilder()
for(byte b : bytes)
hs append(String format( % $ X b))
return hs toString()
}
public static byte[] hex byte(String content) {
int l=content length()》 ;
byte[] result=new byte[l];
for(int i= ;il;i++) {
int j=i《 ;
String s=content substring(j j+ )
result[i]=Integer valueOf(s ) byteValue()
}
return result;
}
/**
* 將字節(jié)數(shù)組轉(zhuǎn)換為base 編碼字符串
* @param buffer
* @return
*/
public static String bytesToBase (byte[] buffer) {
//BASE Encoder en=new BASE Encoder()
return Base encode(buffer)
//????? return encoder encode(buffer)
}
/**
* 將base 編碼的字符串解碼為字節(jié)數(shù)組
* @param value
* @return
* @throws IOException
*/
public static byte[] base ToBytes(String value) throws IOException {
//return Base decodeToByteArray(value)
//????? System out println(decoder decodeBuffer(value))
//????? return decoder decodeBuffer(value)
return Base decode(value)
}
/**
* 加密給定的字符串
* @param value
* @return 加密后的base 字符串
*/
public static String encryptString(String value) {
return encryptString(value DEFAULT_KEY)
}
/**
* 根據(jù)給定的密鑰加密字符串
* @param value 待加密的字符串
* @param key 以BASE 形式存在的密鑰
* @return 加密后的base 字符串
* @throws IOException
*/
public static String encryptString(String value String key) throws IOException {
return encryptString(value base ToBytes(key))
}
/**
* 根據(jù)給定的密鑰加密字符串
* @param value 待加密的字符串
* @param key 字節(jié)數(shù)組形式的密鑰
* @return 加密后的base 字符串
*/
public static String encryptString(String value byte[] key) {
try {
byte[] data=value getBytes(VALUE_ENCODING)
data=CryptUtils encryptData(data key)
return bytesToBase (data)
} catch (Exception e) {
// TODO Auto generated catch block
e printStackTrace()
return null;
}
}
/**
* 解密字符串
* @param value base 形式存在的密文
* @return 明文
*/
public static String decryptString(String value) {
return decryptString(value DEFAULT_KEY)
}
/**
* 解密字符串
* @param value base 形式存在的密文
* @param key base 形式存在的密鑰
* @return 明文
* @throws IOException
*/
public static String decryptString(String value String key) throws IOException {
String s=decryptString(value base ToBytes(key))
return s;
}
/**
* 解密字符串
* @param value base 形式存在的密文
* @param key 字節(jié)數(shù)據(jù)形式存在的密鑰
* @return 明文
*/
public static String decryptString(String value byte[] key) {
try {
byte[] data=base ToBytes(value)
data=CryptUtils decryptData(data key)
return new String(data VALUE_ENCODING)
}catch(Exception e) {
e printStackTrace()
return null;
}
}
}
package gdie lab crypt;
import java io IOException;
import javax crypto Cipher;
import javax crypto KeyGenerator;
import javax crypto SecretKey;
import apache xerces internal impl dv util Base ;
public class CryptUtils {
private static String Algorithm = DES ;
private static byte[] DEFAULT_KEY=new byte[] { };
private static String VALUE_ENCODING= UTF ;
/**
* 生成密鑰
*
* @return byte[] 返回生成的密鑰
* @throws exception
*???????????? 扔出異常
*/
public static byte[] getSecretKey() throws Exception {
KeyGenerator keygen = KeyGenerator getInstance(Algorithm)
SecretKey deskey = keygen generateKey()
// if (debug ) System out println ( 生成密鑰 +byte hex (deskey getEncoded
// ()))
return deskey getEncoded()
}
/**
* 將指定的數(shù)據(jù)根據(jù)提供的密鑰進行加密
*
* @param input
*??????????? 需要加密的數(shù)據(jù)
* @param key
*??????????? 密鑰
* @return byte[] 加密后的數(shù)據(jù)
* @throws Exception
*/
public static byte[] encryptData(byte[] input byte[] key) throws Exception {
SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)
// if (debug )
// {
// System out println ( 加密前的二進串 +byte hex (input ))
// System out println ( 加密前的字符串 +new String (input ))
//
// }
Cipher c = Cipher getInstance(Algorithm)
c init(Cipher ENCRYPT_MODE deskey)
byte[] cipherByte = c doFinal(input)
// if (debug ) System out println ( 加密后的二進串 +byte hex (cipherByte ))
return cipherByte;
}
public static byte[] encryptData(byte[] input) throws Exception {
return encryptData(input DEFAULT_KEY)
}
/**
* 將給定的已加密的數(shù)據(jù)通過指定的密鑰進行解密
*
* @param input
*??????????? 待解密的數(shù)據(jù)
* @param key
*??????????? 密鑰
* @return byte[] 解密后的數(shù)據(jù)
* @throws Exception
*/
public static byte[] decryptData(byte[] input byte[] key) throws Exception {
SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)
// if (debug ) System out println ( 解密前的信息 +byte hex (input ))
Cipher c = Cipher getInstance(Algorithm)
c init(Cipher DECRYPT_MODE deskey)
byte[] clearByte = c doFinal(input)
// if (debug )
// {
// System out println ( 解密后的二進串 +byte hex (clearByte ))
// System out println ( 解密后的字符串 +(new String (clearByte )))
//
// }
return clearByte;
}
public static byte[] decryptData(byte[] input) throws Exception {
return decryptData(input DEFAULT_KEY)
}
/**
* 字節(jié)碼轉(zhuǎn)換成 進制字符串
*
* @param byte[] b 輸入要轉(zhuǎn)換的字節(jié)碼
* @return String 返回轉(zhuǎn)換后的 進制字符串
*/
public static String byte hex(byte[] bytes) {
StringBuilder hs = new StringBuilder()
for(byte b : bytes)
hs append(String format( % $ X b))
return hs toString()
}
public static byte[] hex byte(String content) {
int l=content length()》 ;
byte[] result=new byte[l];
for(int i= ;il;i++) {
int j=i《 ;
String s=content substring(j j+ )
result[i]=Integer valueOf(s ) byteValue()
}
return result;
}
/**
* 將字節(jié)數(shù)組轉(zhuǎn)換為base 編碼字符串
* @param buffer
* @return
*/
public static String bytesToBase (byte[] buffer) {
//BASE Encoder en=new BASE Encoder()
return Base encode(buffer)
//? return encoder encode(buffer)
}
/**
* 將base 編碼的字符串解碼為字節(jié)數(shù)組
* @param value
* @return
* @throws IOException
*/
public static byte[] base ToBytes(String value) throws IOException {
//return Base decodeToByteArray(value)
//? System out println(decoder decodeBuffer(value))
//? return decoder decodeBuffer(value)
return Base decode(value)
}
/**
* 加密給定的字符串
* @param value
* @return 加密后的base 字符串
*/
public static String encryptString(String value) {
return encryptString(value DEFAULT_KEY)
}
/**
* 根據(jù)給定的密鑰加密字符串
* @param value 待加密的字符串
* @param key 以BASE 形式存在的密鑰
* @return 加密后的base 字符串
* @throws IOException
*/
public static String encryptString(String value String key) throws IOException {
return encryptString(value base ToBytes(key))
}
/**
* 根據(jù)給定的密鑰加密字符串
* @param value 待加密的字符串
* @param key 字節(jié)數(shù)組形式的密鑰
* @return 加密后的base 字符串
*/
public static String encryptString(String value byte[] key) {
try {
byte[] data=value getBytes(VALUE_ENCODING)
data=CryptUtils encryptData(data key)
return bytesToBase (data)
} catch (Exception e) {
// TODO Auto generated catch block
e printStackTrace()
return null;
}
}
/**
* 解密字符串
* @param value base 形式存在的密文
* @return 明文
*/
public static String decryptString(String value) {
return decryptString(value DEFAULT_KEY)
}
/**
* 解密字符串
* @param value base 形式存在的密文
* @param key base 形式存在的密鑰
* @return 明文
* @throws IOException
*/
public static String decryptString(String value String key) throws IOException {
String s=decryptString(value base ToBytes(key))
return s;
}
/**
* 解密字符串
* @param value base 形式存在的密文
* @param key 字節(jié)數(shù)據(jù)形式存在的密鑰
* @return 明文
*/
public static String decryptString(String value byte[] key) {
try {
byte[] data=base ToBytes(value)
data=CryptUtils decryptData(data key)
return new String(data VALUE_ENCODING)
}catch(Exception e) {
e printStackTrace()
return null;
}
}
}
CryptHelper java
[java]
package gdie lab crypt;
import javax crypto Cipher;
import javax crypto SecretKey;
import javax crypto SecretKeyFactory;
import javax crypto spec DESKeySpec;
import javax crypto spec IvParameterSpec;
import springframework util DigestUtils;
public class CryptHelper{
private static String CRYPT_KEY = zhongqian ;
//加密
private static Cipher ecip;
//解密
private static Cipher dcip;
static {
try {
String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()
KEY = KEY substring( )
byte[] bytes = KEY getBytes()
DESKeySpec ks = new DESKeySpec(bytes)
SecretKeyFactory skf = SecretKeyFactory getInstance( DES )
SecretKey sk = skf generateSecret(ks)
IvParameterSpec iv = new IvParameterSpec(bytes)
ecip = Cipher getInstance( DES/CBC/PKCS Padding )
ecip init(Cipher ENCRYPT_MODE sk iv )
dcip = Cipher getInstance( DES/CBC/PKCS Padding )
dcip init(Cipher DECRYPT_MODE sk iv )
}catch(Exception ex) {
ex printStackTrace()
}
}
public static String encrypt(String content) throws Exception {
byte[] bytes = ecip doFinal(content getBytes( ascii ))
return CryptUtils byte hex(bytes)
}
public static String decrypt(String content) throws Exception {
byte[] bytes? = CryptUtils hex byte(content)
bytes = dcip doFinal(bytes)
return new String(bytes ascii )
}
//test
public static void main(String[] args) throws Exception {
String password = gly ;
String en = encrypt(password)
System out println(en)
System out println(decrypt(en))
}
}
package gdie lab crypt;
import javax crypto Cipher;
import javax crypto SecretKey;
import javax crypto SecretKeyFactory;
import javax crypto spec DESKeySpec;
import javax crypto spec IvParameterSpec;
import springframework util DigestUtils;
public class CryptHelper{
private static String CRYPT_KEY = zhongqian ;
//加密
private static Cipher ecip;
//解密
private static Cipher dcip;
static {
try {
String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()
KEY = KEY substring( )
byte[] bytes = KEY getBytes()
DESKeySpec ks = new DESKeySpec(bytes)
SecretKeyFactory skf = SecretKeyFactory getInstance( DES )
SecretKey sk = skf generateSecret(ks)
IvParameterSpec iv = new IvParameterSpec(bytes)
ecip = Cipher getInstance( DES/CBC/PKCS Padding )
ecip init(Cipher ENCRYPT_MODE sk iv )
dcip = Cipher getInstance( DES/CBC/PKCS Padding )
dcip init(Cipher DECRYPT_MODE sk iv )
}catch(Exception ex) {
ex printStackTrace()
}
}
public static String encrypt(String content) throws Exception {
byte[] bytes = ecip doFinal(content getBytes( ascii ))
return CryptUtils byte hex(bytes)
}
public static String decrypt(String content) throws Exception {
byte[] bytes? = CryptUtils hex byte(content)
bytes = dcip doFinal(bytes)
return new String(bytes ascii )
}
//test
public static void main(String[] args) throws Exception {
String password = gly ;
String en = encrypt(password)
System out println(en)
System out println(decrypt(en))
}
lishixinzhi/Article/program/Java/hx/201311/26449