PHPSeclib使用心得:RSA加密和AES加密
阿新 • • 發佈:2019-01-11
1.RSA
新建金鑰對:
$rsa = new RSA();
$result = $rsa->createKey();
echo $result["privatekey"] //私鑰
$result["publickey"] //公鑰
加密:
$rsa = new RSA(); $rsa->loadKey($key); $rsa->setEncryptionMode(RSA::ENCRYPTION_NONE); //選擇加密的模式,可選模式參考官方文件 echo base64_encode($rsa->encrypt($msg)); //需要對結果進行base64轉碼,否則為亂碼
解密:
$rsa = new RSA();
$rsa->loadKey($key);
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
echo $rsa->decrypt(base64_decode($msg)); //同理,解碼時,需要先進行base64解碼
目前筆者測試能和PHPSeclib的 RSA配合的javascript包為: https://github.com/rzcoder/node-rsa
2.AES
加密:
$aes = new AES(MCRYPT_MODE_ECB); $aes->setKey(self::KEY); $aes->setIV(self::VECTOR); echo base64_encode($aes->encrypt($msg));
解密:
$aes = new AES(MCRYPT_MODE_ECB);
$aes->setKey(self::KEY);
$aes->setIV(self::VECTOR);
echo $aes->decrypt(base64_decode($msg));