You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于实现RC4加密输入输出仅含字母数字的技术问询

搞定RC4加密的两个需求:输入限字母数字+输出纯字母数字

嘿,我来帮你解决这两个问题!你现在看到的��Tb#这种特殊字符,是因为RC4加密直接输出了二进制字节流,这些字节对应的ASCII码大多是不可见字符。你的核心需求有两个:一是加密时只能输入字母和数字,二是把加密输出改成纯字母数字格式,咱们一步步来:


1. 先搞定输入验证:只允许字母数字通过

在调用RC4加密之前,先给明文加个校验,用正则表达式检查是不是只有a-z、A-Z、0-9这些字符,不符合的话直接提示错误就行。

代码示例:

<?php
require_once( "rc4.php" );

$key = "password";
$plaintext = "hello";

// 输入校验:仅允许字母和数字
if (!preg_match('/^[a-zA-Z0-9]+$/', $plaintext)) {
    die("提示:输入只能包含字母和数字哦");
}

// 先获取RC4加密的二进制结果
$cipherBinary = rc4( $key, $plaintext );

2. 把加密输出转成纯字母数字格式

要把二进制的加密结果转成纯字母数字,有两个简单靠谱的方案:

方案一:转十六进制(最省心,绝对纯字母数字)

用PHP自带的bin2hex()函数把二进制加密结果转成十六进制字符串,十六进制只有0-9、a-f(小写)或者A-F(大写),完全符合你的要求。解密的时候再用hex2bin()转回去即可。

完整代码:

<?php
require_once( "rc4.php" );

$key = "password";
$plaintext = "hello";

// 输入校验
if (!preg_match('/^[a-zA-Z0-9]+$/', $plaintext)) {
    die("提示:输入只能包含字母和数字哦");
}

// RC4加密得到二进制数据
$cipherBinary = rc4( $key, $plaintext );
// 转成十六进制(纯字母数字输出)
$cipherText = bin2hex($cipherBinary);
echo "加密结果:" . $cipherText; // 示例输出:类似 "8d1a7f2b..."

// 解密流程
$decryptBinary = hex2bin($cipherText);
$decryptText = rc4( $key, $decryptBinary );
echo "解密结果:" . $decryptText; // 输出 hello

方案二:自定义Base64变种(更节省字符长度)

标准Base64里有+和/这两个非字母数字的字符,咱们可以把它们替换成字母(比如把+换成A,/换成B),解密的时候再换回去就行。这种方式比十六进制输出的字符更短,适合需要节省空间的场景。

代码示例:

<?php
require_once( "rc4.php" );

$key = "password";
$plaintext = "hello";

// 输入校验
if (!preg_match('/^[a-zA-Z0-9]+$/', $plaintext)) {
    die("提示:输入只能包含字母和数字哦");
}

// RC4加密
$cipherBinary = rc4( $key, $plaintext );
// 转Base64并替换特殊字符为字母
$cipherText = strtr(base64_encode($cipherBinary), '+/', 'AB');
echo "加密结果:" . $cipherText; // 示例输出:类似 "XyTbAB..."

// 解密流程
$decryptBinary = base64_decode(strtr($cipherText, 'AB', '+/'));
$decryptText = rc4( $key, $decryptBinary );
echo "解密结果:" . $decryptText; // 输出 hello

额外提醒

要是你不确定rc4.php里的RC4实现是不是标准的,记得确认它是按照RC4的标准流程来的:先初始化S盒,然后生成密钥流,最后把明文和密钥流做异或得到二进制结果。

内容的提问来源于stack exchange,提问作者user9644415

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:57:36