DES加密与解密

本文介绍了一种使用DES算法进行数据加密和解密的方法。通过具体的Java代码实现了DES密钥的生成、加密过程及解密过程,并展示了如何利用BASE64进行编码与解码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

===================使用DES进行加密和解密============================

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.security.SecureRandom;

 

/**
  * 功能: DES加密
  */
 private String encrypt(String key, String source){
  String algorithm  = "DES";
  byte [] cipherByte   = null;
  
  try {
   DESKeySpec dks = new DESKeySpec(key.getBytes());
   SecureRandom sr = new SecureRandom();
   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
   SecretKey securekey = keyFactory.generateSecret(dks);
   Cipher c1 = Cipher.getInstance(algorithm);
   c1.init(Cipher.ENCRYPT_MODE, securekey, sr);
   cipherByte = c1.doFinal(source.getBytes());
  } catch (Exception e) {
   e.printStackTrace();
  }
  BASE64Encoder base64encoder = new BASE64Encoder();
  String encode=base64encoder.encode(cipherByte);
  return encode;
 }
 /**
  * 功能: DES解密
  * @param key
  * @param source
  * @return
  */
 private String decrypt(String key, String source){
  String algorithm  = "DES";
  SecureRandom sr  = new SecureRandom(); 
  String result   = null; 
  try {
   DESKeySpec dks  = new DESKeySpec(key.getBytes());   
         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);   
         SecretKey securekey = keyFactory.generateSecret(dks);   
         Cipher cipher  = Cipher.getInstance(algorithm);   
         cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
         BASE64Decoder base64decoder = new BASE64Decoder();
         byte[] encodeByte = base64decoder.decodeBuffer(source);
         byte[] cipherByte = cipher.doFinal(encodeByte);
         result = new String(cipherByte, "GBK");
  } catch (Exception e){
   e.printStackTrace();
  }
        return result;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值