key的生成
# 生成私钥
openssl genrsa -out rsa_private_key.pem 1024
# 将生成的私钥转换成pkcs8格式
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out pkcs8_rsa_private_key.pem
# 生成公钥
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
使用php进行rsa加密与解密
$pi_key = openssl_pkey_get_private(file_get_contents($priv_key_file));//这个函数可用来判断私钥是否是可用的,可用返回资源id Resource id
$pu_key = openssl_pkey_get_public(file_get_contents($pub_key_file));//这个函数可用来判断公钥是否是可用的
$data = "aassssasssddd";//原始数据
$encrypted = "";
$decrypted = "";
# 一般用公钥进行加密
openssl_public_encrypt($data,$encrypted,$pu_key);//公钥加密
$encrypted = base64_encode($encrypted);//加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的
echo $encrypted,"\n";
# 用私钥进行解密
openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key);
echo $decrypted,"\n";
rsa加密的长度限制
rsa加密对于明文有长度限制,一般来说1024的密钥,每次可以加密的明文长度是117字节,可解密的密文长度是128字节,所以对于长文本的加密可以使用以下方法
function rsa_enc($data) {
$pub_key = openssl_pkey_get_public(file_get_contents($pub_key_file));
$crypt_res = '';
$sec = '';
for ($i = 0; $i < ((strlen($data) - strlen($data) % 117) / 117 + 1); $i++) {
$sec = '';
openssl_public_encrypt(substr($data, $i * 117, 117), $sec, $pub_key);
$crypt_res = $crypt_res . $sec;
}
return $crypt_res;
}
public function rsa_dec($data) {
if (empty($data)) {
return '';
}
$priv_key = openssl_pkey_get_private(file_get_contents($priv_key_file));
$decrypt_res = '';
$sec = '';
for ($i = 0; $i < ((strlen($data) - strlen($data) % 128) / 128 + 1); $i++) {
$slip = '';
openssl_private_decrypt(substr($data, $i * 128, 128), $sec, $priv_key);
$decrypt_res = $decrypt_res . $sec;
}
return $decrypt_res;
}