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) {