2011-09-20 135 views
3

我需要加密和解密一個字符串。我不能使用散列,因爲解密的字符串必須是可讀的。我知道mcrypt,但我正在尋找一些使用證書文件進行加密和解密的東西。加密/解密字符串(PHP)

謝謝。

回答

4

您可以使用公鑰/私鑰通過OpenSSL和很簡單,一旦你使用過一次或兩次

function encryptString($clearText) 
{ 
    $keyFile=fopen("public.pem","r"); 
    $publicKey=fread($keyFile,8192); 
    fclose($keyFile); 

    openssl_get_publickey($publicKey); 
    openssl_public_encrypt($clearText,$cryptText,$publicKey); 
    return(base64_encode($cryptText)); 
} 

function decryptString($cryptText) 
{ 
    $keyFile=fopen("private.pem","r"); 
    $privateKey=fread($keyFile,8192); 
    fclose($keyFile); 

    openssl_get_privatekey($privateKey); 
    $binText = base64_decode($cryptText); 
    openssl_private_decrypt($binText,$clearText,$privateKey); 
    return($clearText); 
} 

要生成一個密鑰,一個簡短的指南是http://en.wikibooks.org/wiki/Transwiki:Generate_a_keypair_using_OpenSSL

總之

openssl rsa -pubout -in private.pem -out public.pem 

更新

@keepwalking問如何從命令行執行此操作,@vstm回覆了一個很棒的鏈接http://www.devco.net/archives/2006/02/13/public_-_private_key_encryption_using_openssl.php

總之那個頁面,一旦你有鑰匙創建的,您可以通過使用下面的命令進行加密的文本文件file.txt的並輸出給file.ssl

openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl 

要解密file.ssl到另一個文件decrypt.txt,您可以使用下面的命令。

openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt 
+0

哦,謝謝。它看起來很容易:)你可以在命令行函數中翻譯php函數(openssl ....)嗎? – keepwalking

+1

@keepwalking:check out [openssl rsautl](http://www.devco.net/archives/2006/02/13/public_-_private_key_encryption_using_openssl.php)。還可以查看'openssl rsautl -help'獲取像padding-scheme之類的選項。 – vstm

+0

@keepwalking:你的意思是使用命令行函數來加密和解密一個字符串?如果是這樣,請看看vtsm的鏈接。 – Kirk

1

那麼,如果你想使用非對稱加密你要麼必須使用openssl_* -functions或phpseclib如果OpenSSL是不可用在你的PHP。

另一件事是你不能使用證書像對稱密鑰。如果你有一個使用公鑰加密的密文(一個證書包含公鑰),那麼你必須使用私鑰解密,並且如果密文使用私鑰加密,那麼你必須使用公鑰解密,否則它會贏得'工作。