Des加密

DESECB与CBC加密详解

des加密比较常见,使用频率比较高,

记录两种des加密方式:ECB和CBC

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

  /**
     * 加密数据
     * @param encryptString  注意:这里的数据长度只能为8的倍数
     * @param encryptKey
     * @return
     * @throws Exception
     */
    public static byte[] encryptDES(String encryptString, String encryptKey) throws Exception {
        byte[] encryptStringTemp=pading(encryptString);
        SecretKeySpec key = new SecretKeySpec(getKey(encryptKey), "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(encryptStringTemp);
        return encryptedData;
    }

   public static byte[] encryptDES_CBC(String encryptString, String encryptKey,String iv1) throws Exception {
        IvParameterSpec iv = new IvParameterSpec(getIv(iv1));
        byte[] encryptStringTemp=pading(encryptString);
        SecretKeySpec key = new SecretKeySpec(getKey(encryptKey), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,key, iv);
        byte[] encryptedData = cipher.doFinal(encryptStringTemp);
        return encryptedData;
    }


    public static byte[] getIv(String iv) throws DecoderException {
      return   Hex.decodeHex(iv.toCharArray());
    }




  private static byte[] pading(String str){
        byte[] strBs=str.getBytes();
        return pading(strBs);


    }


  private static byte[] pading(byte[] strBs){
       if (strBs.length % 8 !=0) {
           int n=strBs.length/8;
           byte[] pading=new byte[8*(n+1)];
           System.arraycopy(strBs, 0, pading, 0, strBs.length);
           //不足8位的进行补足
           for(int i=strBs.length;i<pading.length;i++){
               pading[i]=(byte)0;
           }
           return pading;
       } else {
            return strBs;
       }


  }


 /**
     * 自定义一个key
     * @param
     */
    public static byte[] getKey(String keyRule) {
        Key key = null;
        byte[] keyByte = keyRule.getBytes();
        // 创建一个空的八位数组,默认情况下为0
        byte[] byteTemp = new byte[8];
        // 将用户指定的规则转换成八位数组
        for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
            byteTemp[i] = keyByte[i];
        }
        key = new SecretKeySpec(byteTemp, "DES");
        return key.getEncoded();
    }

 /***
     * 解密数据
     * @param decryptString
     * @param decryptKey
     * @return
     * @throws Exception
     */
    public static String decryptDES(String decryptString, String decryptKey) throws Exception {
        byte[] b = ConvertUtil.hexStringToByte(decryptString);
        b = pading(b);
        SecretKeySpec key = new SecretKeySpec(getKey(decryptKey), "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte decryptedData[] = cipher.doFinal(b);
        return new String(decryptedData,"UTF-8");
    }




### DES加密算法概述 DES(Data Encryption Standard)是一种对称加密算法,广泛应用于数据保护领域。它采用固定的64位分组大小和56位有效密钥长度进行加密处理[^1]。 以下是基于 Python 的 DES 加密实现示例代码: ```python from Crypto.Cipher import DES from Crypto.Util.Padding import pad, unpad import base64 def des_encrypt(plain_text, key): cipher = DES.new(key, DES.MODE_ECB) # 使用ECB模式初始化Cipher对象 padded_plain_text = pad(plain_text.encode('utf-8'), DES.block_size) # 填充明文到块大小的倍数 encrypted_data = cipher.encrypt(padded_plain_text) # 执行加密操作 return base64.b64encode(encrypted_data).decode('utf-8') # 将二进制加密结果编码为Base64字符串返回 def des_decrypt(cipher_text, key): cipher = DES.new(key, DES.MODE_ECB) # 使用相同的密钥和ECB模式创建解密器 decoded_cipher_text = base64.b64decode(cipher_text) # 解码Base64字符串回原始字节流 decrypted_padded_data = cipher.decrypt(decoded_cipher_text) # 进行解密操作 return unpad(decrypted_padded_data, DES.block_size).decode('utf-8') # 移除填充并还原成原文本 # 测试函数 key = b'abcdefgh' # 密钥必须是8字节长 message = "HelloWorld" encrypted_message = des_encrypt(message, key) print(f"Encrypted Message: {encrypted_message}") decrypted_message = des_decrypt(encrypted_message, key) print(f"Decrypted Message: {decrypted_message}") ``` 上述代码展示了如何利用 `pycryptodome` 库完成 DES 算法的基本加解密功能。需要注意的是,在实际应用中应选用更强的安全措施,比如使用更复杂的加密模式(如 CBC 或 CTR),以及妥善保管密钥。 关于 DES 的具体工作原理,其核心在于一系列复杂的置换、替换和移位运算。这些过程由 S 盒(Substitution Box)、P 盒(Permutation Box)等组件定义,并通过多轮迭代增强安全性。尽管如此,由于现代计算能力的增长,单独使用的 DES 已不再被认为是安全的选择[^2]。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值