標籤:
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;}
php使用openssl進行Rsa長資料加密(117)解密(128) 和 DES 加密解密