DES是一个分组加密算法,典型的DES以64位为分组对数据加密,加密和解密用的是同一个
算法。它的密钥长度64位,其中8位不参与加密计算,仅仅用做校验该密钥的有效性。所以
真正参与加密的密钥是56位。
DES对64位(bit)的明文分组M进行操作,M经过一个初式置换ip,置换成m0,将m0明文分
成左半部分和右半部分,各32位长
DES会根据我们的原始密钥生成16个64位长度的加密密钥,分别供每一轮运算中使用(每一轮就
是对左右部分进行运算)
package cn.hzh.demo.test;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class DESTest {
public static void main(String[] args) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
String cleartext = "嗨!This is just a test";
String oraginKey = "abcefsaasas";
String key = getKey(oraginKey);
String ciphertext = desEncript(cleartext, key);
System.out.println(ciphertext);
String text = desDecript(ciphertext, key);
System.out.println(text);
}
private static String desEncript(String cleartext,String oraginKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance("DES");
SecretKeySpec key = new SecretKeySpec(oraginKey.getBytes(),"DES");
cipher.init(Cipher.ENCRYPT_MODE,key);
byte[] doFinal = cipher.doFinal(cleartext.getBytes());
byte[] base64 = Base64.encodeBase64(doFinal);
return new String(base64);
}
private static String desDecript(String ciphertext,String oraginKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance("DES");
SecretKeySpec key = new SecretKeySpec(oraginKey.getBytes(),"DES");
cipher.init(Cipher.DECRYPT_MODE,key);
byte[] base64 = Base64.decodeBase64(ciphertext.getBytes());
byte[] cipherBytes = cipher.doFinal(base64);
return new String(cipherBytes);
}
private static String getKey(String oraginKey){
byte[] key = new byte[8];
byte[] oraginBytes = oraginKey.getBytes();
for (int i = 0; i< 8 && i < oraginBytes.length; i++) {
key[i] = oraginBytes[i];
}
return new String(key);
}
}