0

I have c# code for encryption. And I need to convert it with same logic in PHP.

// Public key to be used for encryption
    String publicKey="yxnxuhj2322i23k232sasas123121";
    // Sample data to be encrypted
    String data="test";
    //Encryption logic
    CspParameters cspParams = new CspParameters { ProviderType = 1 };
    RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
    rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey));
    byte[] plainBytes = Encoding.UTF8.GetBytes(data);
    byte[] encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
    string encryptedString = Convert.ToBase64String(encryptedBytes);

PHP Code:

include('Crypt/RSA.php');
$a = 'yxnxuhj2322i23k232sasas123121';
$a = base64_decode($a);

$rsa= parseCSBBlob($a);

$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
define('CRYPT_RSA_PKCS15_COMPAT', true);

$user=utf8_encode("test");
$enc_user= $rsa->encrypt($user);
$enc_user=base64_encode($enc_user);

function parseCSBBlob($str) {
    // from https://msdn.microsoft.com/en-us/library/windows/desktop/aa387453(v=vs.85).aspx
    extract(unpack('atype/aversion/vreserved/Valgo', $str));
    if (ord($type) != 6) { // 6 == PUBLICKEYBLOB
        return false;
    }
    //https://msdn.microsoft.com/en-us/library/windows/desktop/aa375549(v=vs.85).aspx
    if ($algo != 0x0000a400) { // 0x0000a400 == CALG_RSA_KEYX
        return false;
    }
    $str = substr($str, 8); // aavV
    extract(unpack('Vmagic/Vbitlen/Vpubexp', $str));
    if ($magic != 0x31415352) { // RSA1
        return false;
    }
    $str = substr($str, 12); // VVV
    if (strlen($str) != $bitlen / 8) {
        return false;
    }
    $str = strrev($str);

    $rsa = new Crypt_RSA();
    $rsa->loadKey(array(
        'e' => new Math_BigInteger($pubexp, 256),
        'n' => new Math_BigInteger($str, 256)
    ));
    return $rsa;
}

I have used the parseCSBBlob method from other stackoverflow post. But it wont work. I am getting encryption from this code but it is not get decrypted in C#. I could not get the ImportCspBlob method in PHP. Encryption should be done in PHP and decryption is done in C#.

0 Answers0