有时候为了数据安全,我们可以给数据进行RSA加密。私钥与公钥对可以通过工具生成。私钥为加密方保存用来加密数据,公钥给到解密方用来解密。示例中的秘钥对使用的2048强度。
public function rsa()
{
// 公钥,解密用
$publicKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsCcLc566TmAu8wgeZe3c
KSyJzK5rlOAKa8vBqu5csd3LK1M946mqw0q2J4TJOPdWoavDlSTA8UrNvPoRcWhy
9BC7Vu8+kmiwHXvk6swKHpml70nPIWyctQi9UtmR3Zsi+OyvD8r+HCYZqixrgsiE
BEOhn2Wx1Y+9D7OqK1pUNah5n7TBfKzswEzrKZNEpiHv9HMIngJpALEHRfz30gED
iS4ayQX9aq8f9jqTP3WU3ULwet572wKEcc1FuN5Dl10pRQUyaJESY6vyoQdEdt9n
gNUd38a4ircU9SEtKpcoEkc061rZoFTTDksjau7X64IXMU8eHMoYE+N9zhTyl86o
iwIDAQAB
-----END PUBLIC KEY-----';
// 私钥,加密用
$privateKey = '-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwJwtznrpOYC7z
CB5l7dwpLInMrmuU4Apry8Gq7lyx3csrUz3jqarDSrYnhMk491ahq8OVJMDxSs28
+hFxaHL0ELtW7z6SaLAde+TqzAoemaXvSc8hbJy1CL1S2ZHdmyL47K8Pyv4cJhmq
LGuCyIQEQ6GfZbHVj70Ps6orWlQ1qHmftMF8rOzATOspk0SmIe/0cwieAmkAsQdF
/PfSAQOJLhrJBf1qrx/2OpM/dZTdQvB63nvbAoRxzUW43kOXXSlFBTJokRJjq/Kh
B0R232eA1R3fxriKtxT1IS0qlygSRzTrWtmgVNMOSyNq7tfrghcxTx4cyhgT433O
FPKXzqiLAgMBAAECggEBAJzZN14tILE2/bcTLJYQFPBoow6o5Ew8rarMVFcSRWFv
H0Alr77uzYl1FfrcRpw9yFrOaal8f3ya4dT6SdvU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HAu5J15XlWINqTEBRWQ6NmLl1owwkYDeFbjO+2rp8b
e7854KfNTYTNH7eDmr7Aqnvo
-----END PRIVATE KEY-----';
// 待加密的字符串数据
$data = '我们测试一下RSA';
// 为避免乱码,我先进行base64 ecode
$data = base64_encode($data);
// 加密方用私钥加密
openssl_private_encrypt($data, $encrypted, $privateKey);
// 解密方用公钥解密
openssl_public_decrypt($encrypted, $decrypted, $publicKey);
// 进行base64 decode 得到原字符串
$originData = base64_decode($decrypted);
// 打印出的内容为:"我们测试一下RSA"
print_r( $originData );
}