zoukankan      html  css  js  c++  java
  • DES ECB 模式 JAVA PHP C# 实现 加密 解密 兼容

    版本一:

    JAVA:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    import javax.crypto.*;
    import javax.crypto.spec.DESKeySpec;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.security.spec.InvalidKeySpecException;
    
    /**
     * 该加密工具兼容PHP
     */
    public class DesEcbCompatiblePhpUtil {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(DesEcbCompatiblePhpUtil.class);
    
        /**
         * 密钥算法
         */
        private static final String ALGORITHM = "DES";
        /**
         * 加解密算法/工作模式/填充方式
         */
        private static final String ALGORITHM_STR = "DES/ECB/NoPadding";
    
        private static final String CHARSET = "UTF-8";
    
        /**
         * 填充内容
         */
        private static final String PAD_STR = "";
    
        public static void main(String[] args) throws Exception {
            String clearText = "123";
    
            String key = "123";
            System.out.println("明文:" + clearText + "
    密钥:" + key);
            String encryptText = encrypt(clearText, key);
            System.out.println("加密后:" + encryptText);
            String decryptText = decrypt(encryptText, key);
            System.out.println("解密后:"+decryptText);
    
            System.out.println(decryptText.trim().equals("123456"));
        }
    
        public static String encrypt(String souce, String key) {
            try {
                return encryptByDes(pkcs5Pad(souce), pkcs5Pad(key));
            } catch (Exception e) {
                LOGGER.error("加密数据: {}异常,原因:{},{}", souce, e.getMessage(), e);
            }
    
            return "";
        }
    
        public static String decrypt(final String souce, final String key) {
            try {
                return decryptByDes(souce, pkcs5Pad(key)).trim();
            } catch (Exception e) {
                LOGGER.error("解密数据: {}异常,原因:{},{}", souce, e.getMessage(), e);
            }
    
            return "";
        }
    
        private static String encryptByDes(final String souce, final String key) throws InvalidKeyException,
                NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
                IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            // 从原始密匙数据创建DESKeySpec对象
            DESKeySpec dks = new DESKeySpec(key.getBytes(CHARSET));
            // 创建一个密匙工厂,然后用它把DESKeySpec转换成 一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey key1 = keyFactory.generateSecret(dks);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, key1, sr);
            // 现在,获取数据并加密
            byte encryptedData[] = cipher.doFinal(souce.getBytes(CHARSET));
            // 通过BASE64位编码成字符创形式
            String base64Str = new BASE64Encoder().encode(encryptedData);
    
            return base64Str;
        }
    
        private static String decryptByDes(final String souce, final String key) throws InvalidKeyException,
                NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IOException,
                IllegalBlockSizeException, BadPaddingException {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            // 从原始密匙数据创建DESKeySpec对象
            DESKeySpec dks = new DESKeySpec(key.getBytes(CHARSET));
            // 创建一个密匙工厂,然后用它把DESKeySpec转换成 一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey key1 = keyFactory.generateSecret(dks);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, key1, sr);
            // 将加密报文用BASE64算法转化为字节数组
            byte[] encryptedData = new BASE64Decoder().decodeBuffer(souce);
            // 用DES算法解密报文
            byte decryptedData[] = cipher.doFinal(encryptedData);
            return new String(decryptedData, CHARSET);
        }
    
        private static String pkcs5Pad(final String souce) {
            //密文和密钥的长度必须是8的倍数
            if (0 == souce.length() % 8) {
                return souce;
            }
    
            StringBuffer tmp = new StringBuffer(souce);
    
            while (0 != tmp.length() % 8) {
                tmp.append(PAD_STR);
            }
            return tmp.toString();
        }
    }

    PHP:

    class DesUtil{
        
        public function ecbEncrypt($key = "", $encrypt) {
            $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB), MCRYPT_RAND);
            $decrypted = mcrypt_encrypt(MCRYPT_DES, $key, $encrypt, MCRYPT_MODE_ECB, $iv);
            $encode = base64_encode($decrypted);
            return $encode;
        }
    
        public function ecbDecrypt($key = "", $decrypt) {
            $decoded = base64_decode($decrypt);
            $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB), MCRYPT_RAND);
            $decrypted = mcrypt_decrypt(MCRYPT_DES, $key, $decoded, MCRYPT_MODE_ECB, $iv);
            return self::trimEnd($decrypted);
        }
    
        /*
         * 去掉填充的字符
         */
    
        private function trimEnd($text) {
            $len = strlen($text);
            $c = $text[$len - 1];
    
            if (ord($c) == 0) {
                return rtrim($text, $c);
            }
    
            if (ord($c) < $len) {
                for ($i = $len - ord($c); $i < $len; $i++) {
                    if ($text[$i] != $c) {
                        return $text;
                    }
                }
                return substr($text, 0, $len - ord($c));
            }
            return $text;
        }
    }

    版本二:

    JAVA:

    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.security.spec.InvalidKeySpecException;
    
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    
    public class SecretUtilTools {
        
        public static String encryptForDES(String souce, String key) throws InvalidKeyException,
                NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
                IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            // 从原始密匙数据创建DESKeySpec对象
            DESKeySpec dks = new DESKeySpec(key.getBytes("UTF-8"));
            // 创建一个密匙工厂,然后用它把DESKeySpec转换成 一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key1 = keyFactory.generateSecret(dks);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, key1, sr);
            // 现在,获取数据并加密
            byte encryptedData[] = cipher.doFinal(souce.getBytes("UTF-8"));
            // 通过BASE64位编码成字符创形式
            String base64Str = new BASE64Encoder().encode(encryptedData);
    
            return base64Str;
        }
    
        
        public static String decryptForDES(String souce, String key) throws InvalidKeyException,
                NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IOException,
                IllegalBlockSizeException, BadPaddingException {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            // 从原始密匙数据创建DESKeySpec对象
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            // 创建一个密匙工厂,然后用它把DESKeySpec转换成 一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key1 = keyFactory.generateSecret(dks);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, key1, sr);
            // 将加密报文用BASE64算法转化为字节数组
            byte[] encryptedData = new BASE64Decoder().decodeBuffer(souce);
            // 用DES算法解密报文
            byte decryptedData[] = cipher.doFinal(encryptedData);
            return new String(decryptedData,"UTF-8");
        }
    
    }

    PHP:

    <?php  
    class SecretUtilTools  
    {     
        //加密算法       
        function encryptForDES($input,$key)   
        {         
           $size = mcrypt_get_block_size('des','ecb');  
           $input = $this->pkcs5_pad($input, $size);  
           $td = mcrypt_module_open('des', '', 'ecb', '');  
           $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);  
           @mcrypt_generic_init($td, $key, $iv);  
           $data = mcrypt_generic($td, $input);  
           mcrypt_generic_deinit($td);  
           mcrypt_module_close($td);  
           $data = base64_encode($data);  
           return $data;  
        }   
        //解密算法      
        function decryptForDES($encrypted,$key)  
        {         
           $encrypted = base64_decode($encrypted);  
           $td = mcrypt_module_open('des','','ecb','');   
           //使用MCRYPT_DES算法,cbc模式  
           $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);  
           $ks = mcrypt_enc_get_key_size($td);  
           @mcrypt_generic_init($td, $key, $iv);  
           //初始处理                 
           $decrypted = mdecrypt_generic($td, $encrypted);  
           //解密  
           mcrypt_generic_deinit($td);  
           //结束               
           mcrypt_module_close($td);  
           $y=$this->pkcs5_unpad($decrypted);  
           return $y;     
        }
                 
        function pkcs5_pad ($text, $blocksize)   
        {         
           $pad = $blocksize - (strlen($text) % $blocksize);  
           return $text . str_repeat(chr($pad), $pad);  
        } 
            
        function pkcs5_unpad($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);  
        }  
    }

    C#:

    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading;
    
    public class SecretUtilTools  
    {
        public string encryptForDES(string message, string key)
        {
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(message);
                des.Key = UTF8Encoding.UTF8.GetBytes(key);
                des.IV = UTF8Encoding.UTF8.GetBytes(key);
                des.Mode = System.Security.Cryptography.CipherMode.ECB;
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return str;
            }
        }
    
    
        public string decryptForDES(string message, string key)
        {
            byte[] inputByteArray = Convert.FromBase64String(message);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = UTF8Encoding.UTF8.GetBytes(key);
                des.IV = UTF8Encoding.UTF8.GetBytes(key);
                des.Mode = System.Security.Cryptography.CipherMode.ECB;
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
       
    }
  • 相关阅读:
    PHP开发者必须养成的十大优良习惯
    Centos7下编译安装PHP
    linux 强制删除yum安装的php7.2
    php和go的web性通对比
    最好的编程语言及其它
    管理哲学新解
    继甲骨文裁员、Java服软Python后,国产原创IT技术已经成熟,让中国科技不再受制于人!
    雷军:我是个失败的创业者,因为我是劳模
    当95后进入大厂
    如何避免自high式分享
  • 原文地址:https://www.cnblogs.com/phpdragon/p/6008187.html
Copyright © 2011-2022 走看看