php使用openssl进行Rsa长数据加密(117)解密(128) 和 DES 加密解密
PHP使用openssl进行Rsa加密,如果要加密的明文太长则会出错,解决方法:加密的时候117个字符加密一次,然后把所有的密文拼接成一个密文;解密的时候需要128个字符解密一下,然后拼接成数据。
加密:
/** * 加密 * @param $originalData * @return string|void */ /*function encrypt($originalData){ // if (openssl_private_encrypt($originalData, $encryptData, $this->rsaPrivateKey)) { if (openssl_public_encrypt($originalData, $encryptData, $this->rsaPublicKey)) { return base64_encode($encryptData); } else { return false; } }*/ function encrypt($originalData){ $crypto = ''; foreach (str_split($originalData, 117) as $chunk) { openssl_public_encrypt($chunk, $encryptData, $this->rsaPublicKey); $crypto .= $encryptData; } return base64_encode($crypto); }
解密:
/** * 私钥解密 * @param $encryptData */ /*function decrypt($encryptData){ // if (openssl_public_decrypt(base64_decode($encryptData), $decryptData, $this->rsaPublicKey)) { if (openssl_private_decrypt(base64_decode($encryptData), $decryptData, $this->rsaPrivateKey)) { return $decryptData; } else { return false; } }*/ function decrypt($encryptData){ $crypto = ''; foreach (str_split(base64_decode($encryptData), 128) as $chunk) { openssl_private_decrypt($chunk, $decryptData, $this->rsaPrivateKey); $crypto .= $decryptData; } return $crypto; }
DES 加密解密:
function encrypt($encrypt,$key){ $passcrypt = mcrypt_encrypt(MCRYPT_DES ,$key, $encrypt, MCRYPT_MODE_CBC, $key); $encode = base64_encode($passcrypt); return $encode; } function decrypt($decrypt,$key){ $decoded = base64_decode($decrypt); $decrypted = mcrypt_decrypt(MCRYPT_DES ,$key, $decoded, MCRYPT_MODE_ECB, $key); return $decrypted; }
AES 加密解密
//为 CBC 模式创建随机的初始向量 $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); function aesEncrypt($encrypt, $key, $iv){ $passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128 ,$key, $encrypt, MCRYPT_MODE_CBC, $iv); //将初始向量附加在密文之后,以供解密时使用 $passcrypt = $iv . $passcrypt; //对密文进行 base64 编码 $encode = base64_encode($passcrypt); return $encode; } function aesDecrypt($decrypt, $key, $iv_size){ $decoded = base64_decode($decrypt); //初始向量大小,可以通过 mcrypt_get_iv_size() 来获得 $iv_dec = substr($decoded, 0, $iv_size); //获取除初始向量外的密文 $decoded = substr($decoded, $iv_size); //可能需要从明文末尾移除 0 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128 , $key, $decoded, MCRYPT_MODE_ECB, $iv_dec); return $decrypted; }