java des 加密/解密

时间:2023-03-09 22:38:45
java des 加密/解密
 JAVA实现
加密
注意:DES加密和解密过程中,密钥长度都必须是8的倍数
public byte[] desCrypto(byte[] datasource, String password) {
try{

9 DESKeySpec desKey = new DESKeySpec(password.getBytes());
//创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
         //Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
// 偏移量
IvParameterSpec iv = new IvParameterSpec(password.getBytes());
//用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);
//现在,获取数据并加密
//正式执行加密操作
return cipher.doFinal(datasource);
}catch(Throwable e){
e.printStackTrace();
}
return null;
} 解密
private byte[] decrypt(byte[] src, String password) throws Exception { // 创建一个DESKeySpec对象
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 将DESKeySpec对象转换成SecretKey对象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
           // 偏移量
IvParameterSpec iv = new IvParameterSpec(password.getBytes());
         // 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
// 真正开始解密操作
return cipher.doFinal(src);
}

测试场景
例如,我们可以利用如上函数对字符串进行加密解密,也可以对文件进行加密解密,如:
[java] view plaincopy
//待加密内容
String str = "测试内容";
//密码,长度要是8的倍数
String password = "12345678";
byte[] result = DESCrypto.desCrypto(str.getBytes(),password);
System.out.println("加密后内容为:"+new String(result)); //直接将如上内容解密
try {
byte[] decryResult = des.decrypt(result, password);
System.out.println("加密后内容为:"+new String(decryResult)); //加密后内容为:测试内容
 } catch (Exception e1) {   e1.printStackTrace();  }


计算机中的数据都是二进制的,不管是字符串还是文件,而加密后的也是二进制的,
由于加密后输出的为byte[],而byte[]对我们显示是不友好的(乱码),所以需要将byte[]转换为其他编码,一般都是转换为base64编码,
1 /**
* 将byte[]转为各种进制的字符串
* @param bytes byte[]
* @param radix 可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制
* @return 转换后的字符串
*/
public static String binary(byte[] bytes, int radix){
return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
} /**
* base 64 encode
* @param bytes 待编码的byte[]
* @return 编码后的base 64 code
*/
public static String base64Encode(byte[] bytes){
return new BASE64Encoder().encode(bytes);
} /**
* base 64 decode
* @param base64Code 待解码的base 64 code
* @return 解码后的byte[]
* @throws Exception
*/
public static byte[] base64Decode(String base64Code) throws Exception{
return QStringUtil.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
}
     /**
* 把二进制转化为大写的十六进制
*
* @param bytes
* @return
*/
private static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
return sign.toString();
}