DES对称加密算法的简单实现

网上看到的都是用了第三方包的,我这里写了个纯java无依赖的

环境

  1. JDK11
  2. Windows7
  3. VS Code

代码

源代码都发布在Gitee上了star

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;

/**
 * DES算法实现
 */
public class DES {
 
    /**
     * iv向量
     */
    private static final byte[] DESIV = { (byte) 0xCE, (byte) 0x35, (byte) 0x5,
        (byte) 0xD, (byte) 0x98, (byte) 0x91, (byte) 0x8, (byte) 0xA };
 
    /**
     * AlgorithmParameterSpec
     */
    private static AlgorithmParameterSpec IV = null;
 
    /**
     * 加密模式
     */
    private static final int ENCRYPT_MODE = 1;
 
    /**
     * 解密模式
     */
    private static final int DECRYPT_MODE = 2;
 
    /**
     * 密钥
     */
    private Key key;
 
    public DES(String str) {
        getKey(str);
    }
 
    public Key getKey() {
        return key;
    }
 
    public void setKey(Key key) {
        this.key = key;
    }
 
    /**
     * 通过密钥获得key
     * @param secretKey 密钥
     */
    public void getKey(String secretKey) {
        try {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(secretKey.getBytes());
            KeyGenerator generator = null;
            try {
                generator = KeyGenerator.getInstance("DES");
            } catch (NoSuchAlgorithmException e) {
            }
            generator.init(secureRandom);
            IV = new IvParameterSpec(DESIV);
            this.key = generator.generateKey();
            generator = null;
 
        } catch (Exception e) {
            throw new RuntimeException("Error in getKey(String secretKey), Cause: " + e);
        }
    }
 
    /**
     * 字符串des加密
     * @param data 需要加密的字符串
     * @return 加密结果
     * @throws Exception 异常
     */
    public byte[] encrypt(byte[] data) throws Exception {
        Cipher cipher = getPattern(ENCRYPT_MODE);
        return cipher.doFinal(data);
    }
 
    /**
     * 字符串des解密
     * @param data 需要解密的字符串
     * @return 解密结果
     * @throws Exception 异常
     */
    public byte[] decrypt(byte[] data) throws Exception {
        Cipher cipher = getPattern(DECRYPT_MODE);
        return cipher.doFinal(data);
    }
 
    /**
     * 初始化cipher
     * @param cipherMode cipher工作模式 1:加密; 2:解密
     * @return cipher
     * @throws Exception 异常
     */
    private Cipher getPattern(int cipherMode) throws Exception {
        Cipher cipher;
        cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(cipherMode, key, IV);
        return cipher;
    }
 
    public static void main(String[] args) throws Exception {
        String testString = "I am YiMi";
        DES des = new DES("blockchain");   // 秘钥
        String stringMi = Base64.getEncoder().encodeToString(des.encrypt(testString.getBytes()));
        System.out.println("密文:" + stringMi);
        byte[] stringMing = des.decrypt(Base64.getDecoder().decode(stringMi));
        System.out.println("明文:" + new String(stringMing));
    }
 
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DES对称分组密码系统 import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; class DES01 { private String strkey; private SecretKey skey=null; private String[] algo= {"DES/ECB/PKCS5Padding","DES/ECB/NoPadding","DES"}; public DES01(String key) { strkey=key; } public void keyGenerating() throws Exception { byte[] bkey=strkey.getBytes(); KeySpec ks = new DESKeySpec(bkey); SecretKeyFactory kf = SecretKeyFactory.getInstance("DES"); skey = kf.generateSecret(ks); } public static void main(String[] a) { DES01 des = new DES01("IAMASTUDENT"); des.test02("STUDENTWANGFENGLIMING"); } public byte[] Encripting(String plaintext,int i) throws Exception { byte[] bpt=plaintext.getBytes(); Cipher cf = Cipher.getInstance(algo[i]); if(skey==null)this.keyGenerating(); cf.init(Cipher.ENCRYPT_MODE,skey); byte[] bct = cf.doFinal(bpt); return bct; } public byte[] decripting(byte[] bct,int i) throws Exception { Cipher cf = Cipher.getInstance(algo[i]); if(skey==null)this.keyGenerating(); cf.init(Cipher.DECRYPT_MODE,skey); byte[] bpt = cf.doFinal(bct); return bpt; } public void test01(String mess) { try{ byte[] ct=this.Encripting(mess,0); byte[] pt=this.Decripting(ct,0); String ptt=new String(pt); System.out.println(ptt); }catch(Exception ex) { return; } } public void test02(String mess) { try{ //Encripting print("Plaintext to be encripted:"); print(mess); byte[] ct=this.Encripting(mess,0); //Exploiting the results print("Byte array of cipher:"); for(int i=0;i<ct.length;i++) System.out.print(ct[i]+" "); print(""); for(int i=0;i<ct.length;i++) ct[i]=(byte)(ct[i]&0xFF); String ciphertxt=new String(ct); print("Cipher Text :"+ciphertxt); byte[] ctcode = ciphertxt.getBytes(); //Decripting byte[] pt=this.decripting(ctcode,0); String ptt=new String(pt); print("Plaintext after decripting:"); print(ptt); }catch(Exception ex) { return; } } public static byte[] hex2Bytes(String str) { if (str==null) { return null; } else if (str.length() < 2) { return null; } else { int len = str.length() / 2; byte[] buffer = new byte[len]; for (int i=0; i<len; i++) { buffer[i] = (byte) Integer.parseInt( str.substring(i*2,i*2+2),16); } return buffer; } } public static String bytes2Hex(byte[] data) { if (data==null) { return null; } else { int len = data.length; String str = ""; for (int i=0; i<len; i++) { if ((data[i]&0xFF)<16) str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF); else str = str + java.lang.Integer.toHexString(data[i]&0xFF); } return str.toUpperCase(); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值