PHP使用RSA私钥解密数据

时间:2014-08-09 20:44:20

标签: php cryptography rsa data-conversion phpseclib

我有一个使用c#rsa公钥加密密码的程序,该公钥输出一个字节数组。

为了让我轻松传输并维护数据,我将字节直接转换为十六进制字符串。现在这是我遇到问题的地方。我将发布数据发送到我的脚本,现在不确定将其转换为什么以及如何解密它。

我正在尝试使用http://phpseclib.sourceforge.net/,我在这篇文章中指出了RSA decryption using private key关于此问题的文档非常模糊,我不知道解密()应该采取什么样的数据/类型

<?php
include('Crypt/RSA.php');
if (isset($_POST['Password'])) 
    {

        $Password = $_POST['Password'];
        $crypttext = pack("H*",$Password);
        echo $cryptext;
        $rsa = new Crypt_RSA();
        $rsa->loadKey('key.priv'); 

        $decryptedText =$rsa->decrypt($cryptext);

        echo "Pass = >" . $decryptedText;
    }
?>

请注意,这不会出现错误,但$decryptedText为空。

编辑:添加更多信息。

这是我的c#encrypt方法。

public static string Encrypt(string data, string keyLocation, string keyName)
    {

        Console.WriteLine("-------------------------BEGIN Encrypt--------------------");
        // Variables
        CspParameters cspParams = null;
        RSACryptoServiceProvider rsaProvider = null;
        string publicKeyText = "";
        string result = "";
        byte[] plainBytes = null;
        byte[] encryptedBytes = null;

        try
        {
            // Select target CSP
            cspParams = new CspParameters();
            cspParams.ProviderType = 1; // PROV_RSA_FULL 

            rsaProvider = new RSACryptoServiceProvider(2048, cspParams);

            // Read public key from Server
            WebClient client = new WebClient();
            Stream stream = client.OpenRead(keyLocation + "/" + keyName);
            StreamReader reader = new StreamReader(stream);
            publicKeyText = reader.ReadToEnd();
            //
            //Console.WriteLine("Key Text : {0}",publicKeyText);

            // Import public key
            rsaProvider.FromXmlString(publicKeyText);


            // Encrypt plain text
            plainBytes = Convert.FromBase64String(data);
            Console.WriteLine("inputlength : {0}",plainBytes.Length);
            encryptedBytes = rsaProvider.Encrypt(plainBytes, false);




            result = ByteArrayToString(encryptedBytes);
            Console.WriteLine("Encrypted Hex string : {0}", result);


        }
        catch (Exception ex)
        {
            // Any errors? Show them
            Console.WriteLine("Exception encrypting file! More info:");
            Console.WriteLine(ex.Message);
        }

        rsaProvider.Dispose();
        Console.WriteLine("-------------------------END Encrypt--------------------");
        return result;
    } // Encrypt


public static byte[] StringToByteArray(String hex)
    {
        int NumberChars = hex.Length / 2;
        byte[] bytes = new byte[NumberChars];
        using (var sr = new StringReader(hex))
        {
            for (int i = 0; i < NumberChars; i++)
                bytes[i] =
                  Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
        }
        return bytes;
    }
    public static string ByteArrayToString(byte[] ba)
    {
        StringBuilder hex = new StringBuilder(ba.Length * 2);
        foreach (byte b in ba)
            hex.AppendFormat("{0:x2}", b);
        return hex.ToString();
    }

我将php修改为此

<?php
include('Crypt/RSA.php');
if (isset($_POST['Password'])) 
    {

        $Password = $_POST['Password'];
        $crypttext = pack("H*",$Password);
        echo $cryptext;
        $rsa = new Crypt_RSA();
        $rsa->loadKey(file_get_contents('key.priv')); // Added file_get_contents() which fixed the key loading
        $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); // Added this which is essential thank you guys/gals
        $decryptedText =$rsa->decrypt($cryptext);

        echo "Pass = >" . $decryptedText; // gives unsual data. This needs to be converted from binary data to base64string I think
        echo "Pass = >" . base64_encode($decryptedText); // gives no data.
        echo "Pass = >" . base64_decode($decryptedText); // gives no data.
    }
?>

我四处搜索并尝试了几个转换回文本的东西,我尝试了base64_encode()和base64_decode(),但我什么也没得到,否则我得到了gobbledey gook。

1 个答案:

答案 0 :(得分:0)

最终解决方案是使用imap_binary($ decryptedText)转换回来。

编辑:

此后我注意到,更好的方法是更换两件事

C#

plainBytes = Convert.FromBase64String(data);

已更改为

plainBytes = Encoding.UTF8.GetBytes(data);

和PHP

imap_binary($decryptedText)

已更改为

utf8_decode($decryptedText)