有没有可能限制输出openssl_encrypt()
函数的最大符号长度,同时节省解密的机会?如果没有,有什么方法加密输出长度只有3-8个符号的字符串?
发布于 2020-11-25 17:43:45
您可以在ECB模式下使用老式的DES算法,但是、DES算法和ECB模式都是不安全的。
DES的块长度为8字节,因此输出为8字节的块-这将由于内部填充到长度为7的明文而起作用-具有8字节长的明文会导致算法附加多一个(填充)数据块,而您最终将获得16字节的输出。
另一种方法是在CTR模式下使用AES -您将需要预定义用于加密的密钥和初始化向量(iv)。使用固定的iv使得这种加密也不安全。
这是示例程序的输出(我更喜欢“原始输出格式”,因为否则您会得到一个(最小)长度为12个字符的base64编码密文):
### Security warning - the code is UNSECURE
DES encryption example
des encryption with plaintext: 123
ciphertext len: 8 data: N��K=���
decryptedtext: 123
des encryption with plaintext: 1234567
ciphertext len: 8 data: �;[��,q
decryptedtext: 1234567
des encryption with plaintext: 12345678
ciphertext len: 16 data: �V�@�Ա���qhJc�
decryptedtext: 12345678
代码:
<?php
echo '### Security warning - the code is UNSECURE' . PHP_EOL;
echo PHP_EOL . 'DES encryption example' .PHP_EOL;
$key = '12348765'; // des-key = 8 bytes ### don't hardcode a key in code !!
$plaintext = '123';
echo PHP_EOL . 'des encryption with plaintext: ' . $plaintext . PHP_EOL;
$ciphertext = openssl_encrypt($plaintext, 'des-ecb', $key, OPENSSL_RAW_DATA);
echo 'ciphertext len: ' . strlen($ciphertext) . ' data: ' . $ciphertext . PHP_EOL;
$decryptedtext = openssl_decrypt($ciphertext, 'des-ecb', $key, OPENSSL_RAW_DATA);
echo 'decryptedtext: ' . $decryptedtext . PHP_EOL;
$plaintext = '1234567';
echo PHP_EOL . 'des encryption with plaintext: ' . $plaintext . PHP_EOL;
$ciphertext = openssl_encrypt($plaintext, 'des-ecb', $key, OPENSSL_RAW_DATA);
echo 'ciphertext len: ' . strlen($ciphertext) . ' data: ' . $ciphertext . PHP_EOL;
$decryptedtext = openssl_decrypt($ciphertext, 'des-ecb', $key, OPENSSL_RAW_DATA);
echo 'decryptedtext: ' . $decryptedtext . PHP_EOL;
$plaintext = '12345678';
echo PHP_EOL . 'des encryption with plaintext: ' . $plaintext . PHP_EOL;
$ciphertext = openssl_encrypt($plaintext, 'des-ecb', $key, OPENSSL_RAW_DATA);
echo 'ciphertext len: ' . strlen($ciphertext) . ' data: ' . $ciphertext . PHP_EOL;
$decryptedtext = openssl_decrypt($ciphertext, 'des-ecb', $key, OPENSSL_RAW_DATA);
echo 'decryptedtext: ' . $decryptedtext . PHP_EOL;
?>
https://stackoverflow.com/questions/64998428
复制相似问题