我正试图找出一种在php中使用RSA的方法。
我用
生成了公钥和私钥ssh-keygen -t rsa
现在我正在尝试使用我的PHP代码中的那些。这是我正在使用的代码:
<?php
$string=$_GET["i"];
//$fp=fopen ("public.pem","r");
$pub_key='ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAtTLDrnS+MyPb/MGHzgcS90DgaoPiDNattlL0Xo7keAjfqz5/yCXU0L8ilkAWIwME5DdXK04MskRtupYPwxPGB4Y7bG/4wvArx5FEgDSq6FUMNvQZ/Vqj13uvcjadLctC2ypAUPRo39qO1IGLEDEWNOS49UgLxzfnr1dZF/Ox5m5UjhOjsALcTiv4eR6ClGcCrAHE7Jp5nL2BwVu46nx3eFlpe7cljQVUOQDgUa5yWaRoJE6qcYgQu1TDo6b/pcAWU1WVu+HzJY4g0aoV2VqamCnl3oyWoPz7ykvxbJbHv7/qTbV+IBNzSx4R7KSppvnPKsrbeiWROvZ4JF84leX+Iw== root@ip-10-83-11-72';
//fclose($fp);
$PK="";
$PK=openssl_get_publickey($pub_key);
if (!$PK) {
echo "Cannot get public key";
echo $pub_key;
}
$finaltext="";
openssl_public_encrypt($string,$finaltext,$PK);
if (!empty($finaltext)) {
openssl_free_key($PK);
echo "Encryption OK!";
echo $finaltext;
echo "<br/><br/><br/>";
}else{
echo "Cannot Encrypt";
}
// STEP 2: Decription (Using Private Key)
//$fp=fopen ("private.pem","r");
$priv_key2='-----BEGIN RSA PRIVATE KEY-----
MIIEoAIBAAKCAQEAtTLDrnS+MyPb/MGHzgcS90DgaoPiDNattlL0Xo7keAjfqz5/
yCXU0L8ilkAWIwME5DdXK04MskRtupYPwxPGB4Y7bG/4wvArx5FEgDSq6FUMNvQZ
/Vqj13uvcjadLctC2ypAUPRo39qO1IGLEDEWNOS49UgLxzfnr1dZF/Ox5m5UjhOj
sALcTiv4eR6ClGcCrAHE7Jp5nL2BwVu46nx3eFlpe7cljQVUOQDgUa5yWaRoJE6q
cYgQu1TDo6b/pcAWU1WVu+HzJY4g0a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pleS
ShT+cXeG+yl6ijZeNmJB+LDYhC0bpwkfbE97AtQoPW5DnLRVQI9uanJiiix1PvHr
iQKBgBj/RiXsDHvVJ28xZPUffZntrAD/TWXMHZWVMFgfsf8Ti0O7ypXqY43+Aoph
nfDH6xJFqU9azsiv5xQVY7X1h4+DuOamqdawIV5LtYod+ip0dxduQMfrqLld/p0m
E+jAaxvC4b6zqomFnZ9MB9eAzUg9i8UQkc4H3cH/bO6MKPG3
-----END RSA PRIVATE KEY-----
';//fread ($fp,8192);
//fclose($fp);
$PK2=openssl_get_privatekey($priv_key2);
$Crypted=openssl_private_decrypt($Data,$Decrypted,$PK2);
if (!$Crypted) {
$MSG.="<p class='error'>Cannot Decrypt ($CCID).</p>";
}else{
echo "Decrypted Data: " . $Decrypted;
}
最后,应用程序崩溃了:
Cannot get public key
Warning: openssl_public_encrypt() [function.openssl-public-encrypt]: key parameter is not a valid public key in /home/menkaur/public_html/iathao.com/bookmarks/lcn.php on line 13
Cannot Encrypt
我做错了什么?
答案 0 :(得分:7)
openssl使用的密钥是PEM格式。要生成它,请使用以下代码:
openssl genrsa -des3 -out private.pem 1024
它将生成一个名为“private.pem”的文件。然后,您可以使用以下方法生成公钥:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
在PHP中,您可以按如下方式使用这些键:
<?php
$pub = file_get_contents('public.pem');
$pk = openssl_get_publickey($pub);
if(!$pk) ...
然后用你的逻辑做你想做的事。