java很多時候要對祕要進行持久化加密,此時的加密採用md5。採用對稱加密的時候就採用DES方法了,那麼java證書的加密與解密程式碼是什麼呢?下面跟yjbys小編一起來學習一下吧!
以下兩個類可以很方便的完成字串的加密和解密:
加密:ypt(password)
解密:ypt(password)
程式碼如下:
[java]
package t;
import ception;
import er;
import enerator;
import etKey;
import 64;
public class CryptUtils {
private static String Algorithm = "DES";
private static byte[] DEFAULT_KEY=new byte[] {-53, 122, -42, -88, -110, -123, -60, -74};
private static String VALUE_ENCODING="UTF-8";
/**
* 生成金鑰
*
* @return byte[] 返回生成的金鑰
* @throws exception
* 扔出異常.
*/
public static byte[] getSecretKey() throws Exception {
KeyGenerator keygen = nstance(Algorithm);
SecretKey deskey = rateKey();
// if (debug ) tln ("生成金鑰:"+byte2hex (ncoded
// ()));
return ncoded();
}
/**
* 將指定的資料根據提供的金鑰進行加密
*
* @param input
* 需要加密的資料
* @param key
* 金鑰
* @return byte[] 加密後的資料
* @throws Exception
*/
public static byte[] encryptData(byte[] input, byte[] key) throws Exception {
SecretKey deskey = new etKeySpec(key, Algorithm);
// if (debug )
// {
// tln ("加密前的二進串:"+byte2hex (input ));
// tln ("加密前的字串:"+new String (input ));
//
// }
Cipher c1 = nstance(Algorithm);
(YPT_MODE, deskey);
byte[] cipherByte = nal(input);
// if (debug ) tln ("加密後的二進串:"+byte2hex (cipherByte ));
return cipherByte;
}
public static byte[] encryptData(byte[] input) throws Exception {
return encryptData(input, DEFAULT_KEY);
}
/**
* 將給定的已加密的資料通過指定的金鑰進行解密
*
* @param input
* 待解密的資料
* @param key
* 金鑰
* @return byte[] 解密後的資料
* @throws Exception
*/
public static byte[] decryptData(byte[] input, byte[] key) throws Exception {
SecretKey deskey = new etKeySpec(key, Algorithm);
// if (debug ) tln ("解密前的資訊:"+byte2hex (input ));
Cipher c1 = nstance(Algorithm);
(YPT_MODE, deskey);
byte[] clearByte = nal(input);
// if (debug )
// {
// tln ("解密後的二進串:"+byte2hex (clearByte ));
// tln ("解密後的字串:"+(new String (clearByte )));
//
// }
return clearByte;
}
public static byte[] decryptData(byte[] input) throws Exception {
return decryptData(input, DEFAULT_KEY);
}
/**
* 位元組碼轉換成16進位制字串
*
* @param byte[] b 輸入要轉換的位元組碼
* @return String 返回轉換後的16進位制字串
*/
public static String byte2hex(byte[] bytes) {
StringBuilder hs = new StringBuilder();
for(byte b : bytes)
nd(at("%1$02X", b));
return ring();
}
public static byte[] hex2byte(String content) {
int l=th()>>1;
byte[] result=new byte[l];
for(int i=0;i
int j=i<<1;
String s=tring(j, j+2);
result[i]=eOf(s, 16)Value();
}
return result;
}
/**
* 將位元組陣列轉換為base64編碼字串
* @param buffer
* @return
*/
public static String bytesToBase64(byte[] buffer) {