PHP用RSA私钥解密数据 [英] PHP decrypting data with RSA Private Key

查看:128
本文介绍了PHP用RSA私钥解密数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我尝试使用 http://phpseclib.sourceforge。 net / ,我在此帖中指向使用私钥的RSA解密这方面的文档非常模糊,我不知道什么数据/类型decrypt()应该采取。

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

请注意,这不会产生错误,但 $ decryptedText 为空。

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

编辑:添加更多信息。

这是我的c#加密方法。 >

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

我将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

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.

推荐答案

最终的解决方案是使用imap_binary($ decryptptedText)

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

编辑:

自从我注意到一个更好的方法将替换2个

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

已更改为

plainBytes = Encoding.UTF8.GetBytes(data);

和PHP

imap_binary($decryptedText)

已更改为

utf8_decode($decryptedText)

这篇关于PHP用RSA私钥解密数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆