DES加密实现类,具体的项目中可以引用

本文介绍了一个简单的DES加密类实现,包括加密和解密的方法。通过使用Java的Security和Crypto包,实现了基于字符串密钥的DES加密和解密过程。文章提供了完整的源代码示例。

自己测试写的一个DES加密类,分析一下,也为了自己以后使用方便。

getEncryptionStr方法获得加密的密文,getDesString方法获得密文解密的明文,两个方法都要传入秘钥,当然秘钥是双方都知道的,加密的意义在于在数据传输过程中,保护数据安全,一定程度上防止数据被截获分析。

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

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

public class DES_encryption {
 
 
 private static Key getKey(String strKey) {
  Key key=null;
  try {
   KeyGenerator _generator = KeyGenerator.getInstance("DES");
   _generator.init(new SecureRandom(strKey.getBytes()));
   key = _generator.generateKey();
   _generator = null;
   return key;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return key;
 }

 
 public static String getEncryptionStr(String strMing,String strKey) {
  BASE64Encoder base64en = new BASE64Encoder();
  try {
   byte[] byteMing = strMing.getBytes("UTF8");
   Key key=getKey(strKey);
   Cipher cipher;
   cipher = Cipher.getInstance("DES");
   cipher.init(Cipher.ENCRYPT_MODE, key);
   String strMiresult = base64en.encode(cipher.doFinal(byteMing));
   return strMiresult;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 
 public static String  getDesString(String strMi,String strKey) {
  BASE64Decoder base64De = new BASE64Decoder();
  try {
   Key key=getKey(strKey);
   byte[] byteMi = base64De.decodeBuffer(strMi);
   Cipher cipher;
   cipher = Cipher.getInstance("DES");
   cipher.init(Cipher.DECRYPT_MODE, key);
   String strDesResult = new String(cipher.doFinal(byteMi), "UTF8");
   return strDesResult;
  } catch (Exception e) {
   System.out.println("秘钥密文不匹配,解密失败!");
  }
  return null;
 }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值