


Sample code sharing on how to consistently implement DES encryption and decryption in php+c#
The following editor will bring you an example of DES encryption and decryption in PHP that is consistent with C#. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
PHP implements DES encryption and decryption consistent with c#. You can search a lot of them from the Internet, but after testing, you find that they are all unusable. The following correct code was found by me after a lot of hard work. I hope you can use it during system integration.
Note: The length of key is within 8 bits.
//C# 版DES 加解密算法 using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Security.Cryptography; using System.IO; using System.Text; public class Des{ //加解密密钥 private static string skey = "12345678"; //初始化向量 private static byte[] DESIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; #region DESEnCode DES加密 public static string DESEnCode(string pToEncrypt, string sKey) { pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt); //建立加密对象的密钥和偏移量 //原文使用ASCIIEncoding.ASCII方法的GetBytes方法 //使得输入密码必须输入英文文本 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); } #endregion /// <summary> /// /// </summary> /// <param name="pToDecrypt"> 待解密的字符串</param> /// <param name="sKey"> 解密密钥,要求为8字节,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> #region DESDeCode DES解密 public static string DESDeCode(string pToDecrypt, string sKey) { // HttpContext.Current.Response.Write(pToDecrypt + "<br>" + sKey); // HttpContext.Current.Response.End(); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; for (int x = 0; x < pToDecrypt.Length / 2; x++) { int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); return HttpContext.Current.Server.UrlDecode(System.Text.Encoding.Default.GetString(ms.ToArray())); } #endregion }
<?php class DES { var $key; var $iv; //偏移量 function DES( $key, $iv=0 ) { //key长度8例如:1234abcd $this->key = $key; if( $iv == 0 ) { $this->iv = $key; //默认以$key 作为 iv } else { $this->iv = $iv; //mcrypt_create_iv ( mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM ); } } function encrypt($str) { //加密,返回大写十六进制字符串 $size = mcrypt_get_block_size ( MCRYPT_DES, MCRYPT_MODE_CBC ); $str = $this->pkcs5Pad ( $str, $size ); return strtoupper( bin2hex( mcrypt_cbc(MCRYPT_DES, $this->key, $str, MCRYPT_ENCRYPT, $this->iv ) ) ); } function decrypt($str) { //解密 $strBin = $this->hex2bin( strtolower( $str ) ); $str = mcrypt_cbc( MCRYPT_DES, $this->key, $strBin, MCRYPT_DECRYPT, $this->iv ); $str = $this->pkcs5Unpad( $str ); return $str; } function hex2bin($hexData) { $binData = ""; for($i = 0; $i < strlen ( $hexData ); $i += 2) { $binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) ); } return $binData; } function pkcs5Pad($text, $blocksize) { $pad = $blocksize - (strlen ( $text ) % $blocksize); return $text . str_repeat ( chr ( $pad ), $pad ); } 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 ); } } ?>
The above is the detailed content of Sample code sharing on how to consistently implement DES encryption and decryption in php+c#. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article is a tutorial on how to encrypt and decrypt files without using third-party encryption and decryption tools. A tutorial on adding encryption and decryption methods to the right-click menu of Win11. Since the registry needs to be modified, you must make a backup before proceeding. operate. 1. First, press the [Win+R] key combination on the keyboard to open Run, then enter the [regedit] command and press [OK or Enter] to open the Registry Editor; 2. In the User Account Control window, you need to allow Does this app make changes to your device? Click [Yes]; 3. Registry Editor window, expand to the following path: HKEY_CURRENT_USER\Software\Microsoft\Windows\Curr

Encrypting and decrypting sensitive data using Yii framework middleware Introduction: In modern Internet applications, privacy and data security are very important issues. To ensure that users' sensitive data is not accessible to unauthorized visitors, we need to encrypt this data. The Yii framework provides us with a simple and effective way to implement the functions of encrypting and decrypting sensitive data. In this article, we’ll cover how to achieve this using the Yii framework’s middleware. Introduction to Yii framework Yii framework is a high-performance PHP framework.

As WeChat mini programs become more popular in the mobile application market, their development has also received more and more attention. In small programs, PHP, as a commonly used back-end language, is often used to handle the encryption and decryption of sensitive data. This article will introduce how to use PHP to implement encryption and decryption in WeChat applet. 1. What are encryption and decryption? Encryption is the conversion of sensitive data into an unreadable form to ensure that the data is not stolen or tampered with during transmission. Decryption is the restoration of encrypted data to original data. In small programs, encryption and decryption usually include

Title: Data Encryption and Decryption Using ReactQuery and Database Introduction: This article will introduce how to use ReactQuery and database for data encryption and decryption. We will use ReactQuery as the data management library and combine it with the database to perform data encryption and decryption operations. By combining these two technologies, we can securely store and transmit sensitive data, and perform encryption and decryption operations when needed to ensure data security. Text: 1. ReactQue

PHP mailbox development: realizing email encryption and decryption functions. With the increasing development of information transmission, email has become one of the important communication methods for people. However, the ensuing security issues have gradually attracted people's attention. In order to protect the security of emails, encryption and decryption have become important aspects of sending and receiving emails. This article will introduce how to use PHP to develop email encryption and decryption functions to improve email security. 1. Principle and function of encryption Email encryption is to convert the email content using a specific algorithm so that in addition to the recipient

Examples of data encryption and decryption in PHP Tencent Cloud Server API interface docking With the widespread application of cloud servers, more and more developers have begun to deploy their applications to cloud servers. In the process of connecting with the Tencent Cloud server API interface, data encryption and decryption is an important link. This article will introduce an example of data encryption and decryption in PHP. When connecting to the Tencent Cloud server API interface, we usually need to encrypt some sensitive data to ensure data security. At the same time, it is also necessary to pick up

Introduction to data encryption and decryption examples in the process of docking with the API interface of Tencent Cloud Server using PHP: In the process of docking with the API interface of Tencent Cloud Server, the security of data is very important. In order to ensure the security of data during transmission and storage, we need to encrypt sensitive information. This article will introduce how to use PHP to encrypt and decrypt data to improve data confidentiality and integrity. Data encryption: When making API requests, we need to encrypt sensitive information to ensure data security. common

In-depth study of network communication encryption and decryption of swoole development functions. With the rapid development of the Internet, network security issues have become increasingly prominent, and encryption and decryption have become an indispensable part of network communication. As a high-performance PHP network communication framework, Swoole provides a wealth of functions, including network communication encryption and decryption. Network communication encryption and decryption play an important role in ensuring the security and integrity of data transmission. In development, we often need to encrypt sensitive information and user data to prevent hackers and theft.
