search
HomeBackend DevelopmentPHP Tutorial自定义加密算法的实现

由于要传一个需要保密的ID,因此用到对称加密,但mcrypt_encrypt算法加密后字符串太长,因此想实现一个自定义加密算法,想法如下

首先先对key计算sha1,取结果的前32bit,然后跟要加密整数进行异或,得到一个加密后的32bit结果

对结果分组:2bit | 6bit | 6bit | 6bit | 6bit | 6bit

各个组分别取名为:a0、a1、a2、a3、a4、a5

另定义一个长度64的字典数组

$dict=array('1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'01','02','03');

将前面每个分组的值作为字典数组的下标,则加密结果为:$dict[a0].$dict[a1].$dict[a2].$dict[a3].$dict[a4].$dict[a5]

这样加密后的结果就是一个长度6-12的字符串,如果字典数组最后3个元素用其他单字符表示,那么结果就固定为6个字符的字符串。

由于初学php不久,对php的函数库不熟悉,求大侠帮忙实现下加密解密算法:

string encrypt(int id,string key)

int decrypt(string text,string key)





回复讨论(解决方案)

echo encrypt(1234, 'abc'), PHP_EOL;echo decrypt( '1TgGSY', 'abc');function encrypt($id, $key) {  $dict = array('1','2','3','4','5','6','7','8','9',    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',    '-','=','*'  );  $key = current(unpack('L', sha1($key, 1)));  $id ^= $key;  $t = str_split(sprintf('%036b', $id), 6);  foreach($t as &$v) $v = $dict[bindec($v)];  return join($t);}function decrypt($s, $key) {  $dict = array('1','2','3','4','5','6','7','8','9',    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',    '-','=','*'  );  $dict = array_flip($dict);  foreach(str_split($s) as $c) $r[] = sprintf('%06b', $dict[$c]);  $id = bindec(join($r));  $key = current(unpack('L', sha1($key, 1)));  return $id ^ $key;}
1TgGSY
1234



我自己也实现了加密过程,不过看起来就没那么优雅了,执行效率也低点,贴出来衬托下高手风范 

$key_string = 'abc';function keyToInt($key) {	$key_sha1 = sha1 ( $key );	$first_char = $key_sha1 [0];	if (ord ( $first_char ) > 55) {		return hexdec ( (hexdec ( $first_char ) & 7) . substr ( $key_sha1, 1, 7 ) ) | (- 2147483648);	} else {		return hexdec ( $key_sha1 );	}}function Encrypt($num){		$dict = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','*','!');	$r1 = $num ^ keyToInt ( $key_string );	$r2 = decbin ( $r1 );	$r3 = array (			bindec ( substr ( $r2, 0, 2 ) ),			bindec ( substr ( $r2, 2, 6 ) ),			bindec ( substr ( $r2, 8, 6 ) ),			bindec ( substr ( $r2, 14, 6 ) ),			bindec ( substr ( $r2, 20, 6 ) ),			bindec ( substr ( $r2, 26, 6 ) ) 	);	return $dict [$r3 [0]] . $dict [$r3 [1]] . $dict [$r3 [2]] . $dict [$r3 [3]] . $dict [$r3 [4]] . $dict [$r3 [5]];}


算法实现之后,发觉在设计算法时,有个缺陷没考虑到,

由于仅仅是id与key异或,加密后的结果存在一定规律性,

比如
1234->1TgGSY 
1235->1TgGSX

有没有什么好的办法打散下结果?

这个够乱的了吧

$id = 1234;$key = 'aaa';for($i=1; $i<100; $i++) {  printf("%-10d %s %s\n", $id, $s = encrypt($id++, $key), decrypt( $s, $key));}function encrypt($id, $key) {  $dict = array('1','2','3','4','5','6','7','8','9',    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',    '-','=','*'  );  $n = rand(0, 15);  srand($n);  $key = current(unpack('L', substr(sha1($key, 1), $n)));  $id ^= $key;  $t = str_split(sprintf('%04b%032b', $n, $id), 6);  foreach($t as $i=>&$v) {    $v = $dict[bindec($v)];    if($i == 0) shuffle($dict);  }  return join($t);}function decrypt($s, $key) {  $dict = array('1','2','3','4','5','6','7','8','9',    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',    '-','=','*'  );  $m = array_search($s{0}, $dict);  $n = $m >> 2;  srand($n);  shuffle($dict);  $dict = array_flip($dict);  foreach(str_split($s) as $i=>$c) {    $r[] = sprintf('%06b', $i==0 ? $m&0x03 : $dict[$c]);  }      $id = bindec(join($r));  $key = current(unpack('L', substr(sha1($key, 1), $n)));  return $id ^ $key;}
1234       4rHK4B 12341235       oD2LN* 12351236       wqkf8u 12361237       6k=GVU 12371238       bxeCr* 12381239       =W-AOi 12391240       IiQ3e1 12401241       z6uMMA 12411242       WLcnd8 12421243       Rizj*M 12431244       4rHK47 12441245       oD2LNT 12451246       wqkf8Z 12461247       6k=GVJ 12471248       bxeCrE 12481249       =W-AOP 12491250       IiQ3et 12501251       z6uMMP 12511252       WLcndU 12521253       Rizj*p 12531254       4rHK4s 12541255       oD2LNs 12551256       wqkf84 12561257       6k=GVn 12571258       bxeCrL 12581259       =W-AOT 12591260       IiQ3ex 12601261       z6uMM1 12611262       WLcndD 12621263       Rizj*s 12631264       4rHK4h 12641265       oD2LNq 12651266       wqkf83 12661267       6k=GVg 12671268       bxeCr5 12681269       =W-AOH 12691270       IiQ3eP 12701271       z6uMMc 12711272       WLcndE 12721273       Rizj*6 12731274       4rHK4I 12741275       oD2LN= 12751276       wqkf8U 12761277       6k=GVI 12771278       bxeCr9 12781279       =W-AOl 12791280       IiQ3bI 12801281       z6uMhG 12811282       WLcnaY 12821283       Rizj6d 12831284       4rHK3Z 12841285       oD2L*n 12851286       wqkfbP 12861287       6k=Gzj 12871288       bxeC=o 12881289       =W-AEd 12891290       IiQ3bY 12901291       z6uMh* 12911292       WLcnag 12921293       Rizj6v 12931294       4rHK3F 12941295       oD2L*e 12951296       wqkfbJ 12961297       6k=Gzm 12971298       bxeC=N 12981299       =W-AEw 12991300       IiQ3bs 13001301       z6uMhl 13011302       WLcna4 13021303       Rizj6V 13031304       4rHK3u 13041305       oD2L*V 13051306       wqkfbm 13061307       6k=Gz* 13071308       bxeC=- 13081309       =W-AEa 13091310       IiQ3bm 13101311       z6uMhe 13111312       WLcnaS 13121313       Rizj6= 13131314       4rHK38 13141315       oD2L*l 13151316       wqkfbS 13161317       6k=Gz6 13171318       bxeC=q 13181319       =W-AEn 13191320       IiQ3bO 13201321       z6uMhV 13211322       WLcnau 13221323       Rizj61 13231324       4rHK3K 13241325       oD2L*p 13251326       wqkfbv 13261327       6k=Gzw 13271328       bxeC=h 13281329       =W-AE- 13291330       IiQ3bS 13301331       z6uMhj 13311332       WLcna9 1332

在你的设计中,第一节只有 2bit 有效位,所以可在其上再附加4bit信息
而0~15的随机数正好是4bit

算法中,这个随机数起到2个作用
1、调整 key
2、打乱字典

如果不怎么需要太强的保密性,位运算移位就足够了,省点CPU

楼主的解答超赞
加上随机数后,1个整数可对应16种结果,64^6种结果尽数用上,解密时也不用再判断是不是无效字符串了。

是楼主的解答超赞,打错啦

不打了

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use