【JAVA】加密解密(轉http://www.wangchao.net.cn/bbsdetail_1742.html)

iteye_15380發表於2012-03-05
package com.duduli.li;

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

public class Eryptogram {
private static String Algorithm = "DES";
// 定義 加密演算法,可用 DES,DESede,Blowfish
static boolean debug = false;

/**
* 構造子註解.
*/
public Eryptogram() {

}

/**
* 生成金鑰
*
* @return byte[] 返回生成的金鑰
* @throws exception
* 扔出異常.
*/
public static byte[] getSecretKey() throws Exception {
KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
SecretKey deskey = keygen.generateKey();
if (debug)
System.out.println("生成金鑰:" + byte2hex(deskey.getEncoded()));
return deskey.getEncoded();

}

/**
* 將指定的資料根據提供的金鑰進行加密
*
* @param input
* 需要加密的資料
* @param key
* 金鑰
* @return byte[] 加密後的資料
* @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("加密前的二進串:" + byte2hex(input));
System.out.println("加密前的字串:" + new String(input));
}
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
byte[] cipherByte = c1.doFinal(input);
if (debug)
System.out.println("加密後的二進串:" + byte2hex(cipherByte));
return cipherByte;

}

/**
* 將給定的已加密的資料通過指定的金鑰進行解密
*
* @param input
* 待解密的資料
* @param key
* 金鑰
* @return byte[] 解密後的資料
* @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("解密前的資訊:" + byte2hex(input));
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
byte[] clearByte = c1.doFinal(input);
if (debug) {
System.out.println("解密後的二進串:" + byte2hex(clearByte));
System.out.println("解密後的字串:" + (new String(clearByte)));

}
return clearByte;

}

/**
* 位元組碼轉換成16進位制字串
*
* @param byte[] b 輸入要轉換的位元組碼
* @return String 返回轉換後的16進位制字串
*/
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
if (n < b.length - 1)
hs = hs + ":";

}
return hs.toUpperCase();

}

public static void main(String[] args) {
try {
debug = false;
Eryptogram etg = new Eryptogram();
byte[] key = etg.getSecretKey();
System.out.println("key = " + key);
String aa = "你要加密的資訊。";
byte[] data = aa.getBytes();
System.out.println(data);
byte[] en = etg.encryptData(data, key);
System.out.println("encryptData = " + new String(en));
byte[] de = etg.decryptData(en, key);
System.out.println("decryptData = " + new String(de));

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

}
}
}

相關文章