C#/JAVA/PHP 互通DES加解密算法(ECB模式支持8位)

C#代码:

using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Diagnostics;
 
namespace ConsoleAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            //密钥8位,不足8位则用数字0补齐
            string key = "12345678";
 
            //待加密字符串
            string s1 = "1";
 
            //加密
            string s2 = DesEncrypt(s1, key);
 
            //解密
            string s3 = DesDecrypt("g6AtgJul6q0=", key);
 
            //加密、解密输出
            Debug.WriteLine("加密前:" + s1);
            Debug.WriteLine("加密后:" + s2);
            Debug.WriteLine("解密后:" + s3);
        }
 
        /// 
        /// 加密字符串
        /// 
        /// 明文
        /// 密钥
        /// 
   
   
        static string DesEncrypt(string strText, string encryptKey)
        {
            string outString = "";
            byte[] byKey = null;
            byte[] IV = Encoding.Default.GetBytes(encryptKey);
            try
            {
                byKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, encryptKey.Length));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.ECB;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                outString = Convert.ToBase64String(ms.ToArray());
            }
            catch (System.Exception)
            {
                outString = "";
            }
            return outString;
        }
 
        /// 
        /// 解密字符串
        /// 
        /// 密文
        /// 密钥
        /// 
   
   
        static string DesDecrypt(string strText, string decryptKey)
        {
            string outString = "";
            byte[] byKey = null;
            byte[] IV = Encoding.Default.GetBytes(decryptKey);
            byte[] inputByteArray = new Byte[strText.Length];
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(0, decryptKey.Length));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                des.Mode = CipherMode.ECB;
                inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = new System.Text.UTF8Encoding();
                outString = encoding.GetString(ms.ToArray());
            }
            catch (System.Exception)
            {
                outString = "";
            }
            return outString;
        }
    }
}

Java代码:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
 
public class Encrypt {
    /**
     * @param args
     */
    public static void main(String[] args) {
         
        //待加密内容
        String str = "1";
        //密码8位,不足8位则用数字0补齐
        String password = "12345678";
         
        //DES加密
        byte[] result = Encrypt.desCrypto(str.getBytes(),password);
        System.out.println("DES加密后内容为:"+new String(result));
        //Base64加密
        byte[] b = Base64.encodeBase64(result, true);
        System.out.println("Base64加密后内容为:"+new String(b));
         
        //Base64解密
        byte[] bb = Base64.decodeBase64(b);
        System.out.println("Base64解密后内容为:"+new String(bb));
        //DES解密
        try {
            byte[] decryResult = Encrypt.decrypt(bb, password);
            System.out.println("DES解密后内容为:"+new String(decryResult));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
     
    public static String encrypt(String srcMsg, String key){
        //DES加密
        byte[] result = Encrypt.desCrypto(srcMsg.getBytes(), key);
        //Base64编码
        byte[] resultBase = Base64.encodeBase64(result, true);
         
        return new String(resultBase);
    }
    private static byte[] desCrypto(byte[] datasource, String password) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            // 现在,获取数据并加密
            // 正式执行加密操作
            return cipher.doFinal(datasource);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
    private static byte[] decrypt(byte[] src, String password) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        return cipher.doFinal(src);
    }
}

Php代码:


   
   pkcs5Pad ( $str, $size );
    $s = mcrypt_encrypt(MCRYPT_DES,$key,$str,MCRYPT_MODE_ECB,$iv);
    return base64_encode($s);
  }
   
  /**
   * 解密
   * @param  string $str 待解密的字符串
   * @param  string $key 密码
   * @return string
   */
  public function decode($str, $key) {
    $iv = $key;
    $str = base64_decode($str);
    $str = mcrypt_decrypt( MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB, $iv );
    $str = $this->pkcs5Unpad( $str );
    return $str;
  }
   
  public function pkcs5Pad($text, $blocksize) {
    $pad = $blocksize - (strlen ( $text ) % $blocksize);
    return $text . str_repeat ( chr ( $pad ), $pad );
  }
   
  public 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 );
  }
}
 
/* 测试加密和解密 */
$encrypt = new encrypt();
echo $encrypt->encode('1', '12345678');
echo '
   
   
'; echo $encrypt->decode('g6AtgJul6q0=', '12345678');



  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#Java 中,可以使用相应的内置类库来实现 AES 加密。 在 C# 中,可以使用 System.Security.Cryptography 命名空间下的 Aes 类来实现 AES 加密。以下是一个简单的加密示例: ```csharp using System; using System.IO; using System.Security.Cryptography; class AesExample { static void Main() { // 加密的密钥和 IV byte[] key = new byte[32]; byte[] iv = new byte[16]; // 随机生成密钥和 IV using (Aes aes = Aes.Create()) { aes.GenerateKey(); aes.GenerateIV(); key = aes.Key; iv = aes.IV; } string plaintext = "Hello, world!"; // 加密 byte[] ciphertext; using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv; ICryptoTransform encryptor = aes.CreateEncryptor(); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { using (StreamWriter sw = new StreamWriter(cs)) { sw.Write(plaintext); } ciphertext = ms.ToArray(); } } } Console.WriteLine(Convert.ToBase64String(ciphertext)); } } ``` 在 Java 中,可以使用 javax.crypto 包下的 Cipher 类来实现 AES 加密。以下是一个简单的加密示例: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AesExample { public static void main(String[] args) throws Exception { // 加密的密钥和 IV byte[] key = new byte[32]; byte[] iv = new byte[16]; // 随机生成密钥和 IV SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); String plaintext = "Hello, world!"; // 加密 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); System.out.println(Base64.getEncoder().encodeToString(ciphertext)); } } ``` 需要注意的是,在实际使用中,需要使用安全的随机数生成器来生成密钥和 IV。此外,还需要考虑密钥管理和密钥交换等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值