关于DES加密啊的一些Java api

package symmetricEncryption;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

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;

import util.TypeUtil;


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;
 }

}

你可能感兴趣的:(关于DES加密啊的一些Java api)