需求:采用 DES 对数据加密,DES 加密模式为ECB,数据补位的填充方式为PKCS5Padding
实现:代码如下(不用导入额外的jar包,jdk自带的即可,本案例使用jdk7)
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class testENC {
/***
* 加密数据
* @param encryptString 要加密的数据
* @param encryptKey 秘钥
* @return
* @throws Exception
*/
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(getKey(encryptKey), "DES"));
byte[] encryptedData = cipher.doFinal(encryptString.getBytes("GBK"));
return Base64.encodeBase64String(encryptedData);
}
/***
* 解密数据
* @param decryptString 要解密的数据
* @param decryptKey 秘钥
* @return
* @throws Exception
*/
public static String decryptDES(String decryptString, String decryptKey) throws Exception {
byte[] sourceBytes = Base64.decodeBase64(decryptString);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(getKey(decryptKey), "DES"));
byte[] decoded = cipher.doFinal(sourceBytes);
return new String(decoded, "GBK");
}
/**
* key 不足8位补位
* @param string
*/
public static byte[] getKey(String keyRule) {
Key key = null;
byte[] keyByte = keyRule.getBytes();
// 创建一个空的八位数组,默认情况下为0
byte[] byteTemp = new byte[8];
// 将用户指定的规则转换成八位数组
for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
byteTemp[i] = keyByte[i];
}
key = new SecretKeySpec(byteTemp, "DES");
return key.getEncoded();
}
/**
* 测试类
*
*/
public static void main(String[] args) throws Exception {
String clearText = "|01|03|01|817777777||0|2017116371|";
String key = "12345678";//密钥
System.out.println("明文:"+clearText+"\n密钥:"+key);
String encryptText = encryptDES(clearText, key);
System.out.println("加密后:"+encryptText);
String decryptText = decryptDES(encryptText, key);
System.out.println("解密后:"+decryptText);
}
}
参考:java中DES加密(DES/ECB/pkcs5padding)的代码分享_ssylml的博客-CSDN博客_des/ecb/pkcs5padding