笔记:des加解密,php和.net版的实现
php5.x版本,要添加php扩展php_mcrypt。
1 class STD3Des 2 { 3 private $key = ""; 4 private $iv = ""; 5 6 /** 7 * 构造,传递二个已经进行base64_encode的KEY与IV 8 * 9 * @param string $key10 * @param string $iv11 */12 function __construct ($key, $iv)13 {14 if (empty($key) || empty($iv)) {15 echo 'key and iv is not valid';16 exit();17 }18 $this->key = $key;19 $this->iv = $iv;20 }21 22 /**23 *加密24 * @param <type> $value25 * @return <type>26 */27 public function encrypt ($value)28 {29 $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');30 $iv = base64_decode($this->iv);31 $value = $this->PaddingPKCS7($value);32 $key = base64_decode($this->key);33 mcrypt_generic_init($td, $key, $iv);34 $ret = base64_encode(mcrypt_generic($td, $value));35 mcrypt_generic_deinit($td);36 mcrypt_module_close($td);37 return $ret;38 }39 40 /**41 *解密42 * @param <type> $value43 * @return <type>44 */45 public function decrypt ($value)46 {47 $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');48 $iv = base64_decode($this->iv);49 $key = base64_decode($this->key);50 mcrypt_generic_init($td, $key, $iv);51 $ret = trim(mdecrypt_generic($td, base64_decode($value)));52 $ret = $this->UnPaddingPKCS7($ret);53 mcrypt_generic_deinit($td);54 mcrypt_module_close($td);55 return $ret;56 }57 58 private function PaddingPKCS7 ($data)59 {60 $block_size = mcrypt_get_block_size('tripledes', 'cbc');61 $padding_char = $block_size - (strlen($data) % $block_size);62 $data .= str_repeat(chr($padding_char), $padding_char);63 return $data;64 }65 66 private function UnPaddingPKCS7($text)67 {68 $pad = ord($text{strlen($text) - 1});69 if ($pad > strlen($text)) {70 return false;71 }72 if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {73 return false;74 }75 return substr($text, 0, - 1 * $pad);76 }77 }78 79 80 //使用81 include('STD3Des.class.php');82 $key='abcdefgh';83 $iv='abcdefgh';84 $msg='test string';85 $des=new STD3Des(base64_encode($key),base64_encode($iv));86 $rs1=$des->encrypt($msg);87 echo $rs1.'<br />';88 $rs2=$des->decrypt($rs1);89 echo $rs2;
.net版本
1 sealed public class CryptoHelper 2 { 3 /// <summary> 4 /// Encrypts the specified input. 5 /// </summary> 6 /// <param name="input">The input.</param> 7 /// <param name="key">key</param> 8 /// <param name="iv">iv</param> 9 /// <returns></returns> 10 public static string EncryptDes(string input, byte[] key, byte[] iv) 11 { 12 if (input == null || input.Length == 0) 13 return String.Empty; 14 15 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 16 MemoryStream ms = null; 17 CryptoStream encStream = null; 18 StreamWriter sw = null; 19 string result = String.Empty; 20 21 try 22 { 23 ms = new MemoryStream(); 24 25 // Create a CryptoStream using the memory stream and the 26 // CSP DES key. 27 //des.Mode = CipherMode.CBC; 28 //des.Padding = PaddingMode.PKCS7; 29 encStream = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write); 30 31 // Create a StreamWriter to write a string 32 // to the stream. 33 sw = new StreamWriter(encStream); 34 35 // Write the plaintext to the stream. 36 sw.Write(input); 37 38 sw.Flush(); 39 encStream.FlushFinalBlock(); 40 ms.Flush(); 41 42 43 result = Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length, CultureInfo.InvariantCulture)); 44 } 45 finally 46 { 47 //close objects 48 if (sw != null) 49 sw.Close(); 50 if (encStream != null) 51 encStream.Close(); 52 if (ms != null) 53 ms.Close(); 54 } 55 56 // Return the encrypted string 57 return result; 58 } 59 /// <summary> 60 /// Decrypts the specified input. 61 /// </summary> 62 /// <param name="input">the input.</param> 63 /// <param name="key">key</param> 64 /// <param name="iv">iv</param> 65 /// <returns></returns> 66 public static string DecryptDes(string input, byte[] key, byte[] iv) 67 { 68 byte[] buffer; 69 try { buffer = Convert.FromBase64String(input); } 70 catch (System.ArgumentNullException) { return String.Empty; } 71 // length is zero, or not an even multiple of four (plus a few other cases) 72 catch (System.FormatException) { return String.Empty; } 73 74 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 75 MemoryStream ms = null; 76 CryptoStream encStream = null; 77 StreamReader sr = null; 78 string result = String.Empty; 79 80 try 81 { 82 ms = new MemoryStream(buffer); 83 84 // Create a CryptoStream using the memory stream and the 85 // CSP DES key. 86 encStream = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read); 87 88 // Create a StreamReader for reading the stream. 89 sr = new StreamReader(encStream); 90 91 // Read the stream as a string. 92 result = sr.ReadToEnd(); 93 } 94 finally 95 { 96 //close objects 97 if (sr != null) 98 sr.Close(); 99 if (encStream != null)100 encStream.Close();101 if (ms != null)102 ms.Close();103 }104 105 return result;106 }107 }108 109 110 //调用111 112 string key = "abcdefgh";113 string iv = "abcdefgh";114 string msg="test string";115 string rs1 = CryptoHelper.EncryptDes(msg, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));116 string rs2 = CryptoHelper.DecryptDes(rs1, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> 'Hello World', 'github.com'=> [ 'foo'=> 'bar'], 'forge.laravel.com'=>

Alipay PHP ...

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

이 기사에서는 프레임 워크에 사용자 정의 기능 추가, 아키텍처 이해, 확장 지점 식별 및 통합 및 디버깅을위한 모범 사례에 중점을 둡니다.

기사는 입력 유효성 검사, 인증 및 정기 업데이트를 포함한 취약점을 방지하기 위해 프레임 워크의 필수 보안 기능을 논의합니다.
