import
java.io.FileInputStream;
import
java.io.FileOutputStream;
import
java.io.ObjectInputStream;
import
java.io.ObjectOutputStream;
import
java.security.Key;
import
javax.crypto.Cipher;
import
javax.crypto.KeyGenerator;
import
javax.crypto.SecretKey;
/**
* DESEncryption實現了DES對稱加密
*
* @author PacoYang
*
*/
public
class
DESEncryption
{
/**
* 創建祕鑰函數,並將祕鑰保存在文件key.txt中
*
*/
public
static
void
setKey()
throws
Exception
{
//
設定加密類型爲三重DES加密,這裏可以改爲DES或AES加密,請大家看API文檔
KeyGenerator kg = KeyGenerator.getInstance(
"DESede"
);
// 設定祕鑰長度爲112,三重DES的祕鑰長度可選112或168
kg.init(
168
);
// 生成祕鑰
SecretKey k = kg.generateKey();
//
下面保存生成好的祕鑰
FileOutputStream f =
new
FileOutputStream(
"key.txt"
);
ObjectOutputStream ops =
new
ObjectOutputStream(f);
ops.writeObject(k);
}
/**
* 獲取祕鑰函數,根據URL路徑讀取文件中的祕鑰
* @param url 祕鑰路徑
* @return 返回祕鑰
*/
public
static
Key
getKey(String url)
throws
Exception
{
FileInputStream f =
new
FileInputStream(url);
ObjectInputStream ips =
new
ObjectInputStream(f);
Key k = (Key) ips.readObject();
return
k;
}
/**
* 加密函數
* @param k 祕鑰
* @param code 要加密的代碼
* @return 返回加密後的內容
*/
public
static
String
encrypt(Key k, String code)
throws
Exception
{
Cipher cp = Cipher.getInstance(
"DESede"
);
cp.init(Cipher.ENCRYPT_MODE, k);
byte
codebyte[]
= code.getBytes(
"UTF8"
);
byte
encode[]
= cp.doFinal(codebyte);
return
parseByte2HexStr(encode);
}
/**
* 解密函數
* @param k 祕鑰
* @param code 要解密的代碼
* @return 返回解密後的內容
*/
public
static
String
decrypt(Key k, String code)
throws
Exception
{
Cipher cp = Cipher.getInstance(
"DESede"
);
cp.init(Cipher.DECRYPT_MODE, k);
byte
codebyte[]
= parseHexStr2Byte(code);
byte
decode[]
= cp.doFinal(codebyte);
return
new
String(decode);
}
// main函數用於測試
public
static
void
main(String[]
args)
throws
Exception {
String s =
"abc123abc321"
;
DESEncryption.setKey();
Key k = DESEncryption.getKey(
"key.txt"
);
String encode = DESEncryption.encrypt(k,s);
System.out.println(encode);
String decode = DESEncryption.decrypt(k,encode);
System.out.println(decode);
}
/**
* 將二進制轉換成16進值制 ,防止byte[]數字轉換成string類型時造成的數據損失
* @param buf
* @return 返回16進制轉換成的string
*/
public
static
String
parseByte2HexStr(
byte
buf[]) {
StringBuffer sb =
new
StringBuffer();
for
(
int
i
=
0
; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] &
0xFF
);
if
(hex.length()
==
1
) {
hex =
'0'
+
hex;
}
sb.append(hex.toUpperCase());
}
return
sb.toString();
}
/**
* 將16進制轉換爲二進制
* @param hexStr 16進制的數組轉換成String類型再傳過來的參數
* @return 轉換回來的二進制數組
*/
public
static
byte
[]
parseHexStr2Byte(String hexStr) {
if
(hexStr.length()
<
1
)
return
null
;
byte
[]
result =
new
byte
[hexStr.length()
/
2
];
for
(
int
i
=
0
; i < hexStr.length() /
2
;
i++) {
int
high
= Integer.parseInt(hexStr.substring(i *
2
,
i *
2
+
1
),
16
);
int
low
= Integer.parseInt(hexStr.substring(i *
2
+
1
,
i *
2
+
2
),
16
);
result[i] = (
byte
)
(high *
16
+ low);
}
return
result;
}
}