java很多时候要对秘要进行持久化加密,此时的加密采用md5。采用对称加密的时候就采用DES方法了,那么java证书的加密与解密代码是什么呢?下面跟本站小编一起来学习一下吧!
以下两个类可以很方便的完成字符串的加密和解密:
加密: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) {