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

自定义加密算法的实现

本帖最后由 feiniaoflyer 于 2014-05-01 13:16:02 编辑 由于要传一个需要保密的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)





------解决方案--------------------

------解决方案--------------------
学习了,厉害。
------解决方案--------------------
这个够乱的了吧
$id = 1234;<br />$key = 'aaa';<br />for($i=1; $i<100; $i++) {<br />  printf("%-10d %s %s\n", $id, $s = encrypt($id++, $key), decrypt( $s, $key));<br />}<br /><br />function encrypt($id, $key) {<br />  $dict = array('1','2','3','4','5','6','7','8','9',<br />    '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',<br />    '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',<br />    '-','=','*'<br />  );<br />  $n = rand(0, 15);<br />  srand($n);<br />  $key = current(unpack('L', substr(sha1($key, 1), $n)));<br />  $id ^= $key;<br />  $t = str_split(sprintf('%04b%032b', $n, $id), 6);<br />  foreach($t as $i=>&$v) {<br />    $v = $dict[bindec($v)];<br />    if($i == 0) shuffle($dict);<br />  }<br />  return join($t);<br />}<br /><br />function decrypt($s, $key) {<br />  $dict = array('1','2','3','4','5','6','7','8','9',<br />    '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',<br />    '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',<br />    '-','=','*'<br />  );<br />  $m = array_search($s{0}, $dict);<br />  $n = $m >> 2;<br />  srand($n);<br />  shuffle($dict);<br />  $dict = array_flip($dict);<br />  foreach(str_split($s) as $i=>$c) {<br />    $r[] = sprintf('%06b', $i==0 ? $m&0x03 : $dict[$c]);<br />  }    <br />  $id = bindec(join($r));<br />  $key = current(unpack('L', substr(sha1($key, 1), $n)));<br />  return $id ^ $key;<br />}<br />
1234       4rHK4B 1234<br>1235       oD2LN* 1235<br>1236       wqkf8u 1236<br>1237       6k=GVU 1237<br>1238       bxeCr* 1238<br>1239       =W-AOi 1239<br>1240       IiQ3e1 1240<br>1241       z6uMMA 1241<br>1242       WLcnd8 1242<br>1243       Rizj*M 1243<br>1244       4rHK47 1244<br>1245       oD2LNT 1245<br>1246       wqkf8Z 1246<br>1247       6k=GVJ 1247<br>1248       bxeCrE 1248<br>1249       =W-AOP 1249<br>1250       IiQ3et 1250<br>1251       z6uMMP 1251<br>1252       WLcndU 1252<br>1253       Rizj*p 1253<br>1254       4rHK4s 1254<br>1255       oD2LNs 1255<br>1256       wqkf84 1256<br>1257       6k=GVn 1257<br>1258       bxeCrL 1258<br>1259       =W-AOT 1259<br>1260       IiQ3ex 1260<br>1261       z6uMM1 1261<br>1262       WLcndD 1262<br>1263       Rizj*s 1263<br>1264       4rHK4h 1264<br>1265       oD2LNq 1265<br>1266       wqkf83 1266<div class="clear">
                 
              
              
        
            </div>
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools