package symmetricEncryption;java
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;code
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;ip
import util.TypeUtil;ci
public class DES_TEST {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
String key=getKeyDES();//獲取密鑰
System.out.println(key);
SecretKey secretKey = loadKeyDES(key);//獲取密鑰
String originalMsg= "I am superMan super";
byte[] encryptbytes= encryptDES(originalMsg.getBytes(),secretKey);
System.out.println(TypeUtil.bytesToHexString(encryptbytes));
//d915dacf62df41405c545daed3056176
//2efea9a30ac1c4db4f8b74fb8464d25a32e57f7816a3bb0e
byte[] decryptbytes=decryptDES(encryptbytes,secretKey);
String finalMsg=new String(decryptbytes);
System.out.println(finalMsg);
System.out.println(originalMsg.equals(finalMsg));
}
public static String getKeyDES() throws NoSuchAlgorithmException{
KeyGenerator generator=KeyGenerator.getInstance("DES");
generator.init(56);
SecretKey key=generator.generateKey();
System.out.println(TypeUtil.bytesToHexString(key.getEncoded()));
return TypeUtil.bytesToHexString(key.getEncoded());
}
public static SecretKey loadKeyDES(String hexKey ){
byte[] bytes= TypeUtil.hexStringToBytes(hexKey);
SecretKey secretKey=new SecretKeySpec(bytes,"DES");
return secretKey;
}
public static byte[] encryptDES(byte[] source ,SecretKey secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher=Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bytes=cipher.doFinal(source);
return bytes;
}
public static byte[] decryptDES(byte[] source ,SecretKey secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher=Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] bytes=cipher.doFinal(source);
return bytes;
}get
}
generator