我有c#代码用于加密。我需要在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代码:
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;
}
我使用过其他stackoverflow帖子中的parseCSBBlob
方法。但它不会工作。我从这段代码中获取加密,但它没有在C#中解密。我无法在PHP中获得ImportCspBlob
方法。加密应该在PHP中完成,解密在C#中完成。