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

}

转载于:https://my.oschina.net/DCL0djYBw0/blog/651056

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值