DES 加密算法

优质
小牛编辑
127浏览
2023-12-01

说明:DES加密/解密类仅供参考思路,需要接入方具体实现细节及调通

php版DES加密/解密类:

<?php
/**
 * Created by PhpStorm.
 * User: didi
 * Date: 2017/9/27
 * Time: 16:11
 */
namespace Library;

class DESHelper
{
    //私钥,固定字节长度为8位
    private $key;
    //偏移量,固定字节长度为8位
    private $iv;
    private $cipher;
    public function __construct($key)
    {
        if(strlen($key) > 8)
        {
            $this->key = substr($key, 0, 8);
        }
        else
        {
            $this->key = $key;
        }

        $this->iv = $this->key;

        $this->cipher = mcrypt_module_open(MCRYPT_DES,'',MCRYPT_MODE_CBC,'');
        //var_dump(mcrypt_enc_get_iv_size($this->cipher),mcrypt_enc_get_key_size($this->cipher),mcrypt_enc_get_block_size($this->cipher));exit;
    }
    //加密
    public function encrypt($str)
    {
        $size = mcrypt_enc_get_block_size($this->cipher);
        $str  = $this->pkcs5Pad($str, $size);
        mcrypt_generic_init($this->cipher, $this->key, $this->iv);
        $data = mcrypt_generic($this->cipher,$str);
        mcrypt_generic_deinit($this->cipher);
        return base64_encode($data);
    }
    //解密
    public  function decrypt($str)
    {
        $str = base64_decode($str);
        mcrypt_generic_init($this->cipher, $this->key, $this->iv);
        $data = mdecrypt_generic($this->cipher,$str);
        $data = rtrim($data,"\0");
        mcrypt_generic_deinit($this->cipher);
        $data = $this->pkcs5Unpad( $data );
        return $data;
    }
    private function pkcs5Pad($text, $blocksize)
    {
        $pad = $blocksize - (strlen ( $text ) % $blocksize);
        return $text . str_repeat ( chr ( $pad ), $pad );
    }
    private function pkcs5Unpad($text)
    {
        $pad = ord ( $text {strlen ( $text ) - 1} );
        if ($pad > strlen ( $text ))
            return false;
        if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad)
            return false;
        return substr ( $text, 0, - 1 * $pad );
    }
    public function __destruct()
    {
        mcrypt_module_close($this->cipher);
    }
}

java版DES加密/解密类:

package amigo.endecrypt;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.codec.binary.Base64;
public class DESUtil {
    //算法名称
    public static final String KEY_ALGORITHM = "DES";
    //算法名称/加密模式/填充方式
    //DES共有四种工作模式-->>ECB:电子密码本模式、CBC:加密分组链接模式、CFB:加密反馈模式、OFB:输出反馈模式
    public static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
    /**
     *
     * 生成密钥key对象
     * @param KeyStr 密钥字符串
     * @return 密钥对象
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws Exception
     */
    private static SecretKey keyGenerator(String keyStr) throws Exception {
        DESKeySpec desKey = new DESKeySpec(keyStr.getBytes("UTF-8"));
        //创建一个密匙工厂,然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        return securekey;
    }
    /**
     * 加密数据
     * @param data 待加密数据
     * @param key 密钥
     * @return 加密后的数据
     */
    public static String encrypt(String data, String key) throws Exception {
        Key deskey = keyGenerator(key);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        // 实例化Cipher对象,它用于完成实际的加密操作
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化Cipher对象,设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, deskey, iv);
        byte[] results = cipher.doFinal(data.getBytes("UTF-8"));
        // 执行加密操作。加密后的结果通常都会用Base64编码进行传输
        return Base64.encodeBase64String(results);
    }
    /**
     * 解密数据
     * @param data 待解密数据
     * @param key 密钥
     * @return 解密后的数据
     */
    public static String decrypt(String data, String key) throws Exception {
        Key deskey = keyGenerator(key);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        //初始化Cipher对象,设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, deskey, iv);
        // 执行解密操作
        return new String(cipher.doFinal(Base64.decodeBase64(data)));
    }
    public static void main(String[] args) throws Exception {
        String source = "amigoxie";
        System.out.println("原文: " + source);
        String key = "A1B2C3D4";
        String encryptData = encrypt(source, key);
        System.out.println("加密后: " + encryptData);
        String decryptData = decrypt(encryptData, key);
        System.out.println("解密后: " + decryptData);
    }
}