标准DES加密解密类
程序员文章站
2022-03-12 18:57:33
...
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* 标准DES加密解密类
*/
public class Des3Utility {
private static final String ALGORITHM = "DESede";
private static final String ENCODING = "UTF-8";
private static final String HEX_SOURCE = "0123456789ABCDEF";
/**
* 字节码转十六进制字符串
* @param sources
* 字节码
* @return
*/
private static String byteToHex(byte[] sources) {
if(sources == null || sources.length == 0){
return null;
}
StringBuffer result = new StringBuffer();
for(byte source : sources){
String tmp = (Integer.toHexString(source & 0XFF));
if(tmp.length() == 1){
result.append("0" + tmp);
}else{
result.append(tmp);
}
}
return result.toString().toUpperCase();
}
/**
* 十六进制字符串转字节码
* @param source
* 十六进制字符串
* @return
* @throws Exception
*/
public static byte[] hexToByte(String source) throws Exception {
if(source.length() % 2 != 0){
throw new IllegalArgumentException("给定的十六进制字符串的长度不是偶数");
}
char[] sourceChars = source.toUpperCase().toCharArray();
int length = sourceChars.length/2;
byte buffer[] = new byte[length];
for(int index = 0;index < length;index++) {
buffer[index] = (byte) (HEX_SOURCE.indexOf(sourceChars[index*2]) << 4 | HEX_SOURCE.indexOf(sourceChars[index*2 + 1]));
}
return buffer;
}
/**
* 根据字符串生成**字节数组
* @param key
* **字符串
* @return
* @throws Exception
*/
private static byte[] buildDesKey(String key) throws Exception {
byte[] keyByte = new byte[24];
byte[] temp = key.getBytes(ENCODING);
if (keyByte.length > temp.length) {
//如果temp不够24位,则拷贝temp数组整个长度的内容到key数组中
System.arraycopy(temp, 0, keyByte, 0, temp.length);
} else {
//如果temp大于24位,则拷贝temp数组24个长度的内容到key数组中
System.arraycopy(temp, 0, keyByte, 0, keyByte.length);
}
return keyByte;
}
/**
* 加密方法
* @param source
* 待加密串
* @param key
* 秘钥
* @return
* 加密后的字符串
* @throws Exception
*/
public static String encode(String source, String key) throws Exception {
byte[] text = source.getBytes(ENCODING);
Cipher cipher = Cipher.getInstance(ALGORITHM + "/CBC/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(buildDesKey(key), ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
byte[] cipherBytes = cipher.doFinal(text);
return byteToHex(cipherBytes);
}
/**
* DES解密方法
* @param source
* 待解密的字符串
* @param key
* 秘钥
* @return
* 解密后的字符串
* @throws Exception
*/
public static String decode(String source, String key) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM + "/CBC/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(buildDesKey(key), ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
return new String(cipher.doFinal(hexToByte(source)));
}
}
上一篇: No route to host
下一篇: 获取元素的偏移量offset实例详解