关于TripleDES/CBC/PKCS5Padding 在php7.1之后的实现

安全 PHP · xingqi · 于 1年前 发布 · 920 次阅读

项目需求

对接JAVA TripleDES_CBC_Encrypt

技术背景

项目php7.2身份证认证接口java

实现原理

mcrypt_encrypt — 使用给定参数加密明文 (警告 本函数已自 PHP 7.1.0 起废弃。强烈建议不要使用本函数。) PHP7.1以后需要使用openssl_encrypt 本文针对PHP7.1以后实现加密,所以对mcrypt_encrypt不作多余解释

mcrypt_encrypt($cipher, $key, $data, $mode, $iv = null)

下面是openssl_encrypt加密方式

/**
 * Encrypts data
 * 以指定的方式和 key 加密数据,返回原始或 base64 编码后的字符串。
 * @link https://php.net/manual/en/function.openssl-encrypt.php
 * @param string $data
 * 待加密的明文信息数据
 * The data.
 *
 * @param string $cipher_algo
 * 密码学方式。openssl_get_cipher_methods() 可获取有效密码方式列表。
 * The cipher method. For a list of available cipher methods, use {@see openssl_get_cipher_methods()}.
 *
 * @param string $passphrase
 * 口令(passphrase)。 若 passphrase 比预期长度短,将静默用 NUL 填充; 若比预期长度更长,将静默截断。
 * The key.
 *
 * @param int $options [optional]
 * options 是以下标记的按位或: OPENSSL_RAW_DATA 、 OPENSSL_ZERO_PADDING。
 * options is a bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.
 *
 * @param string $iv [optional]
 * 非 NULL 的初始化向量
 * A non-NULL Initialization Vector.
 *
 * @param string &$tag [optional]
 * 使用 AEAD 密码模式(GCM 或 CCM)时传引用的验证标签。
 * The authentication tag passed by reference when using AEAD cipher mode (GCM or CCM).
 *
 * @param string $aad [optional]
 * 附加的验证数据。
 * Additional authentication data.
 *
 * @param int $tag_length [optional]
 * 验证 tag 的长度。GCM 模式时,它的范围是 4 到 16。
 * The length of the authentication tag. Its value can be between 4 and 16 for GCM mode.
 *
 * @return string|false the encrypted string on success or false on failure.
 * 成功时返回加密后的字符串, 或者在失败时返回 false。
 */
openssl_encrypt(
    string $data,
    string $cipher_algo,
    string $passphrase,
    int $options = 0,
    string $iv = "",
    string &$tag = null,
    string $aad = "",
    int $tag_length = 16
): string|false

实现的目标

php7.1以后可以进行TripleDES/CBC/PKCS5Padding加密

关键代码

openssl_encrypt($data, 'des-ede3-cbc', $passphrase, OPENSSL_RAW_DATA, $iv);
共收到 0 条回复
没有找到数据。
添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册