PHP decrypting data with RSA Private Key

2019-03-03 22:28发布

问题:

I have a program that encrypts passwords using a c# rsa public key which outputs a byte array.

In order for me to transport it easily and maintain data I am converting the bytes directly to a Hex string. Now this is where I am having issue. I send the post data to my script and am now unsure what to convert it to and how to decrypt it.

I am attempting to use http://phpseclib.sourceforge.net/ which I was pointed to by this post RSA decryption using private key The documentation on this is very vague and I don't know what data/type decrypt() should take.

<?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;
    }
?>

Note that this gives no errors but $decryptedText is empty.

EDIT: Adding more info.

This is my c# encrypt method.

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();
    }

I modified the php to this

<?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.
    }
?>

I searched around and tried several things to convert back to text and I have tried base64_encode() and base64_decode() but I get nothing and otherwise I get gobbledey gook.

回答1:

The final solution was to use imap_binary($decryptedText) to convert back.

Edit :

It has since been brought to my attention that a better way of doing this would be to replace 2 things

C#

plainBytes = Convert.FromBase64String(data);

Changed to

plainBytes = Encoding.UTF8.GetBytes(data);

and PHP

imap_binary($decryptedText)

Changed to

utf8_decode($decryptedText)