I'm trying to decrypt a cipher, which has been encrypted in PHP, using RSA in C#. Here is my C# code:
public byte[] Decrypt(byte[] dataToDecrypt)
{
byte[] plain;
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
rsa.ImportParameters(PrivateKey);
plain = rsa.Decrypt(dataToDecrypt, false);
}
return plain;
}
And the PHP code is:
public static function encrypt($dataToEncrypt, $userPublicKey) {
if (openssl_public_encrypt($dataToEncrypt, $encrypted, $userPublicKey, OPENSSL_PKCS1_PADDING)) {
return $encrypted;
} else {
throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');
}
}
I get no exceptions or errors in C#. The problem is that if I convert the byte array output of the Decrypt function to a string (i.e. using System.Text.UTF8Encoding.GetString()) the decrypted string is very different from the original plain text passed to 'encrypt' function in PHP.
Any idea why they are different? What am I missing?
p.s. I'd like to add that I have code to encrypt data in C# and decrypt it back in PHP, in a very similar fashion with no problems. I cannot just get it to work the other way around, as I explained above. Thanks
=== UPDATE ===
The input data - i.e. $dataToEncrypt is:
$sessionKey = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
The public and private keys are:
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAzMzT6e4CVC11E1w9bXhnIVgZIAfs5McBeewW3bZtS8NBelHs
HyxiZjkHgMZp6BGSsux0gl0e+DkeISHe5dOQEX7WJBaARxiGJxTzhEo556rrmSXz
7h5TSht/ivTWPZTYfAaYwLC71C/IKWfRPGSVuqHTlflVc0JSUF3M6dgWPqLRF7G3
qqYFdx3+2CoVyCQkNogvkICZNbGGtx7RlGHJ1LCeCyEdC+6AIyNItBbXGtBOf/IZ
bdL+QioWCV/VzQAhm01QVn8g6CHiCMvAIMMj2RXUg/1tL2vw0QNS2ZJgfsM3x67s
M47T1zHj/OTaX6lAp77FHkof1tKmTwlV1RSj7wIDAQABAoIBAGHMbmYHgpUwH/he
0/ayyIzjxRvGrRmS7uGKHGFD/G1xkJMZC+jXCSZHlY2pMmnf+m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JyxY1jHqa0X64W/5nZqH/uv58+Hf6uv47l3n3n0T
58WFfKgXY5AaLCbi1UERdeHKPXNXDFkTKuuOb190M+RNbGgzwN9fcQ==
-----END RSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA498EWxuZK/KsUgIEusEt
QOJulgTHwb8C4avtzJnzhosTeKooXvyGFPpex6HcQGSRqrWpNr2yhw1BvJvH2UyE
Jisl5BJA5Za+ofmbGifCFwCllZ37U1YpOmqpB2Yt+yYElGh5dp+lqs5Q3u3nPknd
nLS3bxH7qlZBvR9YPWj9x7IuSXJyopAmdJato8xeNHzmBxWD8FgQKICFpLtGsPXq
XRwT0imTs6/EcMqq6fdlp0OyBKyZjw6t47gMeqiuSYz6k41Nf/SbtIC4snUyoUgI
TvnHjWe1cY7js4kY62A9ZpHX0NpG7JXctxVb+aZOv1rS36bUjcP+bug1W3ZKrTG6
hwIDAQAB
-----END PUBLIC KEY-----
So for example if the input ($dataToEncrypt) in base64 string is :
VPA13tGd8HMlaB3yKxlFBb8/dAXlCjX5Rr1SzE4L6TY=
I get this output (plain) in base64 string is:
UTgfMQfl82FV4D4HfHPiwmo7jOygBmtXBap0Hn+fAoT4zZcGmLXiY1rGIhmEr90tNxzTGHhknx6PhgJ5eZDK2c9aWi/gD3FJz8MksRjbOkX09GMabcdekdwcyvu9JEWJZi2wOSaRLTRkf90uOArq7pG1g8CPwPLkghj39nUF+XYdGyAB4SXmKkPHshg+dk1acEaXhj9mnAF2fluDEJnfQEU=
Related
I've got a private key stored on my PHP server. A message is encrypted using the private key on the PHP server. My C# code is meant to receive the ciphertext from PHP's response and decrypt it with the public key. However, I keep running into errors such as
Cryptography.CryptoThrowHelper.WindowsCryptographicException: 'Key does not exist.'
My PHP code is as follows:
$pkey = openssl_pkey_get_private("file://pkey");
openssl_private_encrypt($text, $ciphertext, $pkey, OPENSSL_PKCS1_PADDING);
echo base64_encode($ciphertext);
My C# code includes an implementation of the function mentioned in this thread, where the answer has a comment linking to Github. A snippet is below:
string pubkey = "M...Q==";
RSA rsa = CreateRsaProviderFromPublicKey(pubkey);
byte[] bytes = Convert.FromBase64String(dataEncrypted);
byte[] decryptedBytes = rsa.Decrypt(bytes, RSAEncryptionPadding.Pkcs1);
return Encoding.UTF8.GetString(decryptedBytes);
The error occurs on the line where rsa.Decrypt is being called. I obtained the public key from the PHP function openssl_pkey_get_details, where I then stripped the ----BEGIN PUBLIC KEY----- header and footer and removed all spaces.
Edit 1: Perhaps I should post the code I used to make the private key, since that could be problematic:
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
Edit 2: I tried using sha256 with 2048 bytes for a new key, it made no difference.
Let me please explain the complete workflow for RSA encryption with 3 small, simple programs. I'm running all programs in Online compiler so you can easily run the codes directly. The key pair is a 4096 bit long RSA one, the online generation will take some seconds and the encryption padding is OAEP for security reasons.
Security warning: all programs run without any exception handling and are for educational purpose only.
Step 1: Key generation
As the encryption is done with the public key of the recipient of the message the recipient has to generate the RSA key pair. As per your definition the PHP-side is the sender and the C#-side is the recipient let's generate the key pair in C#.
The first code will generate a 4096 bit long RSA key pair in XML-encoding - that's the default output encoding of C#:
privateKeyXML: <RSAKeyValue><Modulus>u0pkuoAjII9KQ9OgEILB6MnGBAedO/Ho+O69W5USpQc+pDGxQbqcC9PKKQk4dymGnS70HVswHVUkdiLcEIMCjU8jdXFnOfh5SPKfR9bgmRQ3HhEaY5ejcCerCW96J5leNEcfkMpWjXy+hvzt0Whnv21Xckbkzo17HZrN+G9C5D1KEeQkdKdg8WVR+3XfhiFLj/S6ANmNjCNbcrR8GKY1GjZahDUyddEza76RuJ3Wqyle0BmNT0RoSHGvjBP+LlY3aOqzsU2sqnzGnItRzr2HnQwVV10MMFo3fbuWopzXqzVjQbnxJM9G79l20Np2eFLDVp4zpiYrGHWSFOnfIDqmy5ke57W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k+csbaPCsILQ0ZCzTnCcoh9svw9AIvlHn5YyAa8Gl5o6Ub8lsJXOSftGVtcCsWRiLbD1pg1CTQmoKPPxUFsaU9iPXrfb48+5hFFOVe6+22S8YShFl/HaRq8TMESXmCiRgbgzBV7zmABkJFtH6WUBkXqBTSlUoEsYUHIV61vptroHHui/aVxnynvtkJqTTfto2ukq5ZzpDmQeDE075kM/rOyUuUiJBQ7eszrXKTDKW2xqc6q/OQMfjEiPdtl1Rc44obdRGaTmJhi9h5a/SqH6KPDVoaR+hwLXggnLERroyogElyjbzrkfD5nCE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
Step 2: RSA encryption on PHP-side with public key
As we are using the PHP-built-in OpenSSL-engine we need to convert the XML-encoded public key to a PEM encoding first. As it is the public key I'm using an
online service for this task - there are many other options but for the sake of demonstration it's okay. Go to https://superdry.apphb.com/tools/online-rsa-key-converter and copy/paste the publicKeyXML to the first inputbox and press the button "Convert". In the outputbox below you will find this Public key:
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAu0pkuoAjII9KQ9OgEILB
6MnGBAedO/Ho+O69W5USpQc+pDGxQbqcC9PKKQk4dymGnS70HVswHVUkdiLcEIMC
jU8jdXFnOfh5SPKfR9bgmRQ3HhEaY5ejcCerCW96J5leNEcfkMpWjXy+hvzt0Whn
v21Xckbkzo17HZrN+G9C5D1KEeQkdKdg8WVR+3XfhiFLj/S6ANmNjCNbcrR8GKY1
GjZahDUyddEza76RuJ3Wqyle0BmNT0RoSHGvjBP+LlY3aOqzsU2sqnzGnItRzr2H
nQwVV10MMFo3fbuWopzXqzVjQbnxJM9G79l20Np2eFLDVp4zpiYrGHWSFOnfIDqm
y5ke57WnISJwnPz6A+ByhYVJfaxohkk+csbaPCsILQ0ZCzTnCcoh9svw9AIvlHn5
YyAa8Gl5o6Ub8lsJXOSftGVtcCsWRiLbD1pg1CTQmoKPPxUFsaU9iPXrfb48+5hF
FOVe6+22S8YShFl/HaRq8TMESXmCiRgbgzBV7zmABkJFtH6WUBkXqBTSlUoEsYUH
IV61vptroHHui/aVxnynvtkJqTTfto2ukq5ZzpDmQeDE075kM/rOyUuUiJBQ7esz
rXKTDKW2xqc6q/OQMfjEiPdtl1Rc44obdRGaTmJhi9h5a/SqH6KPDVoaR+hwLXgg
nLERroyogElyjbzrkfD5nCECAwEAAQ==
-----END PUBLIC KEY-----
Copy and paste your public key in the second program (function loadRsaPublicKeyPem), let it run and encrypt the data, giving this Base64 encoded output:
RSA 2048 encryption OAEP-padding string
plaintext: The quick brown fox jumps over the lazy dog
* * * encrypt the plaintext with the RSA public key * * *
ciphertextBase64: Rot82ugHFtc3b/JNC+uUYMUSQgdHl4bwcdpLIpY7EJzrI7xwMdzKMoastjc4IFiAcXExC7YmpVkVXsHYVGDbMb+o/IKAp/LyH5SrlQqAJq65ZG7Fe54UgKatdqAIBMQIawiv+3g2YmrstdA2KIjW1+93FeH1vUgqSYxydSvIkngjqE//1Dwa/DY+bFrDfG9B1HtDEDFvAOOZE7qC4I2XYvD3LQVwp4zBzFXSzeJP9/BkksC6CN6caKDRdaQa+/oyRjZXJiFIx4YAhok4aBwg54er+2jEeKHcUM01eZBTCFtrIZF4Yg9GQRkCA89XsZkGypqPVL/HLZXx6yHF3kR3XVvCuKwzX/IyostUNbPeWWAWieUFbBWhdPSrENC//7M8nmE7dvcBbRHpoX4LWmD+kWYAFV3M+5n9SJhzwayI0rvQY9DQ4U5IiaP32TDjqyPyK2gzimpuYRe7KWYCBgCG503XThdWe4vpcDNYOKp0KO5TwHMNMTg/FLbwuQcvcpiT9lQLbr5Pz84swe1olhle0rTlBXOS6ONn5LWfrKYjfwluBYsxF/XtJcg+HytBZbCqMNHTeeS4a40r0XLxH/Gjdvw1zs7APrA9AN2SObthMeIXJlryLSshmoKsgBDCi3JzZ80kO4729SVtH1SbwElkZtJNqD6IilY2c1M6CV94tHg=
Step 3: RSA decryption on C#-side with Private key
Copy and paste your private key in the third program (function loadRsaPrivateKeyXml), copy and paste the ciphertextBase64 and run the program, you
will get this output:
RSA 2048 decryption OAEP-padding string
* * * decrypt the ciphertext with the RSA private key * * *
ciphertextReceivedBase64: Rot82ugHFtc3b/JNC+uUYMUSQgdHl4bwcdpLIpY7EJzrI7xwMdzKMoastjc4IFiAcXExC7YmpVkVXsHYVGDbMb+o/IKAp/LyH5SrlQqAJq65ZG7Fe54UgKatdqAIBMQIawiv+3g2YmrstdA2KIjW1+93FeH1vUgqSYxydSvIkngjqE//1Dwa/DY+bFrDfG9B1HtDEDFvAOOZE7qC4I2XYvD3LQVwp4zBzFXSzeJP9/BkksC6CN6caKDRdaQa+/oyRjZXJiFIx4YAhok4aBwg54er+2jEeKHcUM01eZBTCFtrIZF4Yg9GQRkCA89XsZkGypqPVL/HLZXx6yHF3kR3XVvCuKwzX/IyostUNbPeWWAWieUFbBWhdPSrENC//7M8nmE7dvcBbRHpoX4LWmD+kWYAFV3M+5n9SJhzwayI0rvQY9DQ4U5IiaP32TDjqyPyK2gzimpuYRe7KWYCBgCG503XThdWe4vpcDNYOKp0KO5TwHMNMTg/FLbwuQcvcpiT9lQLbr5Pz84swe1olhle0rTlBXOS6ONn5LWfrKYjfwluBYsxF/XtJcg+HytBZbCqMNHTeeS4a40r0XLxH/Gjdvw1zs7APrA9AN2SObthMeIXJlryLSshmoKsgBDCi3JzZ80kO4729SVtH1SbwElkZtJNqD6IilY2c1M6CV94tHg=
decryptedData: The quick brown fox jumps over the lazy dog
And voila - we receive the original plaintext from PHP-side here on C#. Here are the online-ressources:
program 1 - generate RSA keys on C#-side: https://repl.it/#javacrypto/CsharpGenerateRsaKeypair#main.cs
program 2 - encrypt on PHP-side: https://repl.it/#javacrypto/PhpRsaOaepPaddingEncryption#main.php
program 3 - decrypt on C#-side: https://repl.it/#javacrypto/CsharpRsaOaepPaddingDecryption#main.cs
code program 1:
using System;
using System.Security.Cryptography;
using System.Text;
class RSACSPSample
{
static void Main()
{
// Create a new instance of RSACryptoServiceProvider to generate
// public and private key data.
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096);
rsa.PersistKeyInCsp = false;
string privateKeyXML = rsa.ToXmlString(true);
string publicKeyXML = rsa.ToXmlString(false);
Console.WriteLine("privateKeyXML: " + privateKeyXML);
Console.WriteLine("publicKeyXML: " + publicKeyXML);
Console.WriteLine();
}
}
code program 2:
<?php
function rsaEncryptionOaepSha1($publicKey, $plaintext) {
openssl_public_encrypt($plaintext, $ciphertext, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
return $ciphertext;
}
function base64Encoding($input) {return base64_encode($input);}
function loadRsaPublicKeyPem() {
// this is a sample key - don't worry !
return '
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAu0pkuoAjII9KQ9OgEILB
6MnGBAedO/Ho+O69W5USpQc+pDGxQbqcC9PKKQk4dymGnS70HVswHVUkdiLcEIMC
jU8jdXFnOfh5SPKfR9bgmRQ3HhEaY5ejcCerCW96J5leNEcfkMpWjXy+hvzt0Whn
v21Xckbkzo17HZrN+G9C5D1KEeQkdKdg8WVR+3XfhiFLj/S6ANmNjCNbcrR8GKY1
GjZahDUyddEza76RuJ3Wqyle0BmNT0RoSHGvjBP+LlY3aOqzsU2sqnzGnItRzr2H
nQwVV10MMFo3fbuWopzXqzVjQbnxJM9G79l20Np2eFLDVp4zpiYrGHWSFOnfIDqm
y5ke57WnISJwnPz6A+ByhYVJfaxohkk+csbaPCsILQ0ZCzTnCcoh9svw9AIvlHn5
YyAa8Gl5o6Ub8lsJXOSftGVtcCsWRiLbD1pg1CTQmoKPPxUFsaU9iPXrfb48+5hF
FOVe6+22S8YShFl/HaRq8TMESXmCiRgbgzBV7zmABkJFtH6WUBkXqBTSlUoEsYUH
IV61vptroHHui/aVxnynvtkJqTTfto2ukq5ZzpDmQeDE075kM/rOyUuUiJBQ7esz
rXKTDKW2xqc6q/OQMfjEiPdtl1Rc44obdRGaTmJhi9h5a/SqH6KPDVoaR+hwLXgg
nLERroyogElyjbzrkfD5nCECAwEAAQ==
-----END PUBLIC KEY-----
';
}
echo 'RSA 2048 encryption OAEP-padding string' . PHP_EOL;
$dataToEncryptString = "The quick brown fox jumps over the lazy dog";
echo 'plaintext: ' . $dataToEncryptString . PHP_EOL;
// encryption
echo PHP_EOL . '* * * encrypt the plaintext with the RSA public key * * *' .PHP_EOL;
$publicKeyLoad = openssl_pkey_get_public(loadRsaPublicKeyPem());
$ciphertextBase64 = base64Encoding(rsaEncryptionOaepSha1($publicKeyLoad, $dataToEncryptString));
echo 'ciphertextBase64: ' . $ciphertextBase64 . PHP_EOL;
// transport the encrypted data to recipient
?>
code program 3:
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
class RsaDecryptionOaepPadding {
static void Main() {
Console.WriteLine("RSA 2048 decryption OAEP-padding string");
string ciphertextBase64 = "Rot82ugHFtc3b/JNC+uUYMUSQgdHl4bwcdpLIpY7EJzrI7xwMdzKMoastjc4IFiAcXExC7YmpVkVXsHYVGDbMb+o/IKAp/LyH5SrlQqAJq65ZG7Fe54UgKatdqAIBMQIawiv+3g2YmrstdA2KIjW1+93FeH1vUgqSYxydSvIkngjqE//1Dwa/DY+bFrDfG9B1HtDEDFvAOOZE7qC4I2XYvD3LQVwp4zBzFXSzeJP9/BkksC6CN6caKDRdaQa+/oyRjZXJiFIx4YAhok4aBwg54er+2jEeKHcUM01eZBTCFtrIZF4Yg9GQRkCA89XsZkGypqPVL/HLZXx6yHF3kR3XVvCuKwzX/IyostUNbPeWWAWieUFbBWhdPSrENC//7M8nmE7dvcBbRHpoX4LWmD+kWYAFV3M+5n9SJhzwayI0rvQY9DQ4U5IiaP32TDjqyPyK2gzimpuYRe7KWYCBgCG503XThdWe4vpcDNYOKp0KO5TwHMNMTg/FLbwuQcvcpiT9lQLbr5Pz84swe1olhle0rTlBXOS6ONn5LWfrKYjfwluBYsxF/XtJcg+HytBZbCqMNHTeeS4a40r0XLxH/Gjdvw1zs7APrA9AN2SObthMeIXJlryLSshmoKsgBDCi3JzZ80kO4729SVtH1SbwElkZtJNqD6IilY2c1M6CV94tHg=";
try {
// receiving the encrypted data, decryption
Console.WriteLine("\n* * * decrypt the ciphertext with the RSA private key * * *");
string ciphertextReceivedBase64 = ciphertextBase64;
Console.WriteLine("ciphertextReceivedBase64: " + ciphertextReceivedBase64);
string privateKeyLoad = loadRsaPrivateKeyXml();
byte[] ciphertextReceived = Base64Decoding(ciphertextReceivedBase64);
byte[] decryptedtextByte = rsaDecryptionOaep(privateKeyLoad, ciphertextReceived);
Console.WriteLine("decryptedData: " + Encoding.UTF8.GetString(decryptedtextByte, 0, decryptedtextByte.Length));
}
catch(ArgumentNullException) {
Console.WriteLine("The data was not RSA encrypted");
}
}
public static byte[] rsaDecryptionOaep(string privateKeyXml, byte[] ciphertext) {
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(2048);
RSAalg.PersistKeyInCsp = false;
RSAalg.FromXmlString(privateKeyXml);
return RSAalg.Decrypt(ciphertext, true);
}
static byte[] Base64Decoding(String input) {
return Convert.FromBase64String(input);
}
public static string loadRsaPrivateKeyXml() {
return "<RSAKeyValue><Modulus>u0pkuoAjII9KQ9OgEILB6MnGBAedO/Ho+O69W5USpQc+pDGxQbqcC9PKKQk4dymGnS70HVswHVUkdiLcEIMCjU8jdXFnOfh5SPKfR9bgmRQ3HhEaY5ejcCerCW96J5leNEcfkMpWjXy+hvzt0Whnv21Xckbkzo17HZrN+G9C5D1KEeQkdKdg8WVR+3XfhiFLj/S6ANmNjCNbcrR8GKY1GjZahDUyddEza76RuJ3Wqyle0BmNT0RoSHGvjBP+LlY3aOqzsU2sqnzGnItRzr2HnQwVV10MMFo3fbuWopzXqzVjQbnxJM9G79l20Np2eFLDVp4zpiYrGHWSFOnfIDqmy5ke57WnISJwnPz6A+ByhYVJfaxohkk+csbaPCsILQ0ZCzTnCcoh9svw9AIvlHn5YyAa8Gl5o6Ub8lsJXOSftGVtcCsWRiLbD1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hyyN4xyJH1P5EPPSoVj7L4s2kDlaMhtoX9oNuLojnKIosauGhvs/esXmSd/1udqqEcdWdJIaKeR6f0KZ3wvY/L7UoOna7VW3MKrDrm1EKYQVAWu+1ujfglnBohFkGaDGuapxkRhcXtCqrQSVbT8zWqa6yFL+TbzR6JSu7euwI0/43Cpd6Rg0vm5Z64KK1hNPMP2+ablLCRm3GzeAXZ/F7MG6n/KZ7sYam3Ez56q5eDzO66UL2Ksi81FLTtq/NNegWnELZ79bJy9D1i2R6GmtDG/Lm6BWYHz4m7e7+DMmBJcQbE3cky6iKVyhYVgJ74cREetbXER6Ifriuv9RqumcE1+dN/9yBkinJqa9jFblIGwJMAK9u5fC/Y7Ddba1DS43TYGvnGuYO26QBZPwlyd78t3utHW+Fn38uN/XfYlxMcxlxUHo6eC//zWxRMga+U7AWAZZWLDgHZ+Jp+7cfYypBsIryDiZMUQSkH3o87SMVE9lhT7tO/waJ8mjcdwfAXmCXLhKkFU9CorsU5bIpGkQgGIXNswAGOh8hDvvW1GHLSruGMhoOM9TqHsoO66Ow77E=</D></RSAKeyValue>";
}
}
Credit to Michael Fehr from the comments.
Apparently C# cannot decrypt using a public key, at least with the libraries I'm using. So the solution is to give the C# code the private key and decrypt all messages from the PHP server with the public key.
It's my understanding that this won't be a security issue, despite the fact that the "private" key is being sent into the wild, because both keys are designed for this exact purpose.
I have this code in .net:
RSACryptoServiceProvider cipher = new RSACryptoServiceProvider();
cipher.FromXmlString(publicKey);
byte[] data = Encoding.UTF8.GetBytes(input);
byte[] cipherText = cipher.Encrypt(data, false);
result = Convert.ToBase64String(cipherText);
and this code in python:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64encode
key = open(public_key_loc, "r").read()
rsakey = RSA.importKey(key)
encrypted_data = rsakey.encrypt(input, 32)[0]
result = b64encode(encrypted_data)
When I run this codes with a public key, I get different answers on the same input!
I've searched and found out that both Crypto (python) and RSACryptoServiceProvider (.net) are using the RSA algorithm.
EDIT:
The public key used in .net is created by removing -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- from the key and converting it to XML.
Example:
PublicKey:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCETtzC9pZ+dnQ0z0pXL6pNrkn4vGdbLTf3fhH5
MsVYsFIPuuaUSC9EnbTa8G9p1AIKNsjQaBbzfkvgdu5Tz8qEXZfYQV2bnSCtl/87M7Xn0raAmGTr
jSliTdsxMyJHObzAPkamjHemAxHd9VkwXfZOPAh00ueag+buTAkbzL1MlQIDAQAB
-----END PUBLIC KEY-----
Input:
"6000306"
.net output: SpDXp/KCea8DlIuhow6k8+uyfGFe93r9+w39ROoSRAggF9dBU3boK5zRareOQo2//7LyMZZVVklvDCFPo/irJtgbxjn6c0C7gHrL7ubKRG7iVaa9iSF1u13gdRZvLGy/MKOxiz9G+FKLZfJYtkiOSLkJHXXMWTGSNedQsdraJZc=
Python output:
Q3H0NTJYZzymWhWDtMCSzcqZ0D/Nvumq3VqvFCvQRlib82pth48DbVcKwjrmSjT0F/ipi7mnSq8M7BLX/7wo4tQFqul9+avyI/eAW5LKbuFZiiD8eP0GMwEZZyHGurFKhxu+1Qa0dftCIeiIMVJsVaHcUD254BSkYQC04Fflvfc=
What is the problem? Am I missing something?
For the python code, you have neglected to use the PKCS1_v1_5 module you imported. As a result, you're getting plain vanilla RSA encryption with no padding. This is not what you want. If instead your code is:
key = open(public_key_loc, "r").read()
rsakey = RSA.importKey(key)
cipher = PKCS1_v1_5.new(rsakey)
encrypted_data = cipher.encrypt(input)
result = b64encode(encrypted_data)
Then you'll see that the cipher changes every time, even with the same input, just like the C# side does. PKCS1 version 1.5 type 2 padding includes a random component, so the output should never be the same.
The PKCS1_OAEP module is the more modern choice, and is supported by .NET simply by change the false to true in the RSACryptoServiceProvider.Encrypt() method.
I need to encrypt a password and add it as a http header to make a rest call from a python client. I am trying to implement the following C# code listed below in Python, but the rest POST request seems to be failing with Python as the encrypted password string generated from python does not seem to be matching the encrypted password from C# . The C# code generates the correct encrypted password
modulus: "w1jcEfmxCTz5aB9wGg1Vl5K45VUm8Aj7+05sBarmrwbvC9BNjAqSySPmC2ajWSQGdmBs4xylKZjHKaXg5rxuNw=="
exponent:
"AQAB"
password to encrypt:'tricky'
encrypted password from C#(keeps changing each time it is generated): '%14%1d%0a%bb%a0X%24H%ad%ce%9aG%f6a%dau%d8%01%ec%d5)+%d3%11%8e%3ew%c8K%dce%ec%84K%e6%1d%ea%81%3e%d14%87%80s%8eo%a6%bc%fd%1b%8f%a1V8%c8%96%b1%ec%1f%d7qd%bbz'
encrypted password from Python:'%21%F6%7E.i%F4%F4%5E%E5%A9v%03E%8C%1C%3E%F1%D7%DBT%A2%03z%BF%E2%E8%8FJh%E3%85%AA%24%25%C2%C9Hg%18z%22a%F8g%0B%81%3C%DC%FEr%F8C%98s%B5%DA1%F6%60%23%BAw%10F'
Here is my python code using Pycrypto which does the encryption:
from base64 import b64decode
from Crypto.PublicKey.RSA import construct
def get_encrypted_password(password, modulus, exponent):
password = password.encode('utf-8')
# decode base64 string to be used as modulus(n) and exponent(e) components for constructing the RSA public key object
modulus = b64decode(modulus)
exponent = b64decode(exponent)
n = int.from_bytes(modulus, byteorder=sys.byteorder)
e = int.from_bytes(exponent, byteorder=sys.byteorder)
pubkey = construct((n,e))
encrypted = pubkey.encrypt(password,None)[0]
#url encode the encrypted password
encrypted = urllib.parse.quote_plus(encrypted)
return encrypted
This is the C# code which does the encryption:
public static string EncryptForTransport(string strToEncrypt, string rsaPublicKey)
{
KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.AllFlags);
permission.Assert();
if (string.IsNullOrEmpty(strToEncrypt))
{ return strToEncrypt; }
RSACryptoServiceProvider rsaEncryptor = GetRsaEncryptor(rsaPublicKey);
byte[] buffer = rsaEncryptor.Encrypt(Encoding.UTF8.GetBytes(strToEncrypt), false);
try
{
rsaEncryptor.Clear();
}
catch (CryptographicException)
{
//errors may occur ignore them.
}
string encryptedStr = HttpUtility.UrlEncode(buffer);// byteConverterGetString;
return encryptedStr;
}
private static RSACryptoServiceProvider GetRsaEncryptor(string rsaPublicKey)
{
RSACryptoServiceProvider.UseMachineKeyStore = true;
RSACryptoServiceProvider rsaEncryptor = RSACryptoServiceProvider.Create() as RSACryptoServiceProvider;
if (rsaEncryptor.PersistKeyInCsp)
rsaEncryptor.PersistKeyInCsp = false;
rsaEncryptor.FromXmlString(rsaPublicKey);
return rsaEncryptor;
}
Any ideas on what I might be doing wrong with encrypting the password using RSA in Python?
To match what the C# code is doing you must parse the big-endian modulus and exponent correctly, and use PKCS v1.5 padding. This example below modifies your code slightly to show this.
from base64 import b64decode
from Crypto.PublicKey.RSA import construct
from Crypto.Cipher import PKCS1_v1_5
import urllib.parse
def get_encrypted_password(password, modulus, exponent):
password = password.encode('utf-8')
# decode base64 string to be used as modulus(n) and exponent(e) components for
# constructing the RSA public key object
modulus = b64decode(modulus)
exponent = b64decode(exponent)
n = int.from_bytes(modulus, byteorder='big')
e = int.from_bytes(exponent, byteorder='big')
pubkey = construct((n, e))
pubkey = PKCS1_v1_5.new(pubkey)
encrypted = pubkey.encrypt(password)
# url encode the encrypted password
encrypted = urllib.parse.quote_plus(encrypted)
return encrypted
I am trying to create an online database application using PHP for the server and C# form application for the client.
On the server I encrypt a simple string using a public RSA key with the PHPSecLib. Then the C# application receives the string and tries to decrypt it using the corresponding private key.
The bytes are base64 encoded on the server and decoded to bytes again by C#. I created the key pair using the PHPSecLib.
This is the code I use on the client application:
public string rsa_decrypt(string encryptedText, string privateKey) {
byte[] bytesToDecrypt = Convert.FromBase64String(encryptedText);
Pkcs1Encoding decrypter = new Pkcs1Encoding(new RsaEngine());
//the error occurs on this line:
AsymmetricCipherKeyPair RSAParams = (AsymmetricCipherKeyPair)new PemReader(new StringReader(privateKey)).ReadObject();
decrypter.Init(false, RSAParams.Private);
byte[] decryptedBytes = decrypter.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length);
string decryptedString = Convert.ToBase64String(decryptedBytes);
return decryptedString;
}
But, I get the following error on the line specified above^.
An unhandled exception of type 'System.IO.IOException' occurred in
BouncyCastle.Crypto.dll
Additional information: -----END RSA PRIVATE KEY not found
I believe there's nothing wrong with the key pair combo as I get an error before I even try to decrypt anything.
The privateKey parameter is currently hardcoded into the script using this format:
string privateKey = "-----BEGIN RSA PRIVATE KEY-----XXXXXXXX-----END RSA PRIVATE KEY-----";
So it seems to me the footer actually is included in the string... I have debugged and googled everywhere but I can't seem to solve it. I'm pretty new to RSA&Bouncycastle so maybe I'm just using wrong methods.
Hope you can help, thanks!
- G4A
P.S. This is my first Stackoverflow question, I just created an account, so if you could also give me some feedback on the way I formulated this question; great!
You need to add a new line between the pre/post encapsulation boundary text and the Base64 data, so:
string privateKey = "-----BEGIN RSA PRIVATE KEY-----\r\nXXX\r\n-----END RSA PRIVATE KEY-----";
This is because the pem specification allows for the existence of other textual headers between the two.
If this doesn't work
"-----BEGIN RSA PRIVATE KEY-----\r\nXXXXXXXX\r\n-----END RSA PRIVATE KEY-----"
please try this
"-----BEGIN RSA PRIVATE KEY-----
XXXXXXXX
-----END RSA PRIVATE KEY-----"
We converted the BOX Private Key to Base64 Format and stored the same in Azure Vault.
Convert key to Base64 using Base64Encode method, store in Azure Key Vault.
Retrieve the encoded string in code, decoded back using Base64Decode Method.
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
I recommend use \x0A instead of \r\n and
.
Because only this option worked for me.
So :
"-----BEGIN RSA PRIVATE KEY-----\x0AXXXXXXXX\x0A-----END RSA PRIVATE KEY-----"
Without BounceyCastle.
I have my cert, and the GetPublicKey() value is not what the Java side of the house needs.
The cert if an X509Certificate2 object, using DSA encryption. Created using makecert
Convert.ToBase64String(cert.GetPublicKey()) returns
AoGAeaKLPS4ktxULg3YQL0ePphF08tKsddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9Lg
JU4JOA27snO3fCsPAVkmJ0O2pbxn+wzT7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx9
2UyuDzoQTGxgCrPccQPjUgY=
Convert.ToBase64String(cert.RawData) returns
MIICxjCCAoagAwIBAgIQbdIpaaU9rZdA+wJKA+mUfDAJBgcqhkjOOAQDMBYxFDASBgNVBAMTC0RT
QSBSb290IENBMB4XDTEzMDExMDE3MTAzNVoXDTM5MTIzMTIzNTk1OVowFDESMBAGA1UEAxMJVXNl
ciBOYW1lMIIBtzCCASwGByqGSM44BAEwggEfAoGBALWn4Iyvn7LFkV9ULoZtwJ8J1c+ibsbhjPiw
+xUgRW2LAZV2/Lv89W1jCprNkf87tN/ogMT/1VSIOo7ff/tqVRTWPVJ1ZMrR9VOnF2k/Sorg8Cmr
sAClsSWrACKIwK2XKJGWTU4oMLxvYcu85+yQ4nWLofgA/+WARrJ/rk2aUSZ3AhUAlqPLNh6JZkpD
G/OXKzhsZFUiDrkCgYEAoICjHltWOgN8/2uyAaMTNrBuJfi/HM9AWe5B8m9HDfl1K6Qx2Ni6tbYP
uFtvHdGnoqqn46l7eY+xjpi5GEydvkPtAQKmTDGcSh6vtnTeNV15Hafg5pXUKw1OisIr/bpx/KIk
cgCtSo6qC5IhDzeZXnfJYcE+8U+O6hEr5dwByN4DgYQAAoGAeaKLPS4ktxULg3YQL0ePphF08tKs
ddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9LgJU4JOA27snO3fCsPAVkmJ0O2pbxn+wzT
7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx92UyuDzoQTGxgCrPccQPjUgajWTBXMAwG
A1UdEwEB/wQCMAAwRwYDVR0BBEAwPoAQmhMLkJ/cPXGitvGMB81tZaEYMBYxFDASBgNVBAMTC0RT
QSBSb290IENBghDCpMJ75zgZokJVlZmNq/LTMAkGByqGSM44BAMDLwAwLAIUYUALM9WhgwzRMj1y
MSdoparmYvICFFxLgFr2ow3NGTkqWvHIXtjO9R0G
However, when my Java counterpart gets the public key, using the same cert file, gets
$ cat david-509.cer | openssl x509 -pubkey
-----BEGIN PUBLIC KEY-----
MIIBtzCCASwGByqGSM44BAEwggEfAoGBALWn4Iyvn7LFkV9ULoZtwJ8J1c+ibsbh
jPiw+xUgRW2LAZV2/Lv89W1jCprNkf87tN/ogMT/1VSIOo7ff/tqVRTWPVJ1ZMrR
9VOnF2k/Sorg8CmrsAClsSWrACKIwK2XKJGWTU4oMLxvYcu85+yQ4nWLofgA/+WA
RrJ/rk2aUSZ3AhUAlqPLNh6JZkpDG/OXKzhsZFUiDrkCgYEAoICjHltWOgN8/2uy
AaMTNrBuJfi/HM9AWe5B8m9HDfl1K6Qx2Ni6tbYPuFtvHdGnoqqn46l7eY+xjpi5
GEydvkPtAQKmTDGcSh6vtnTeNV15Hafg5pXUKw1OisIr/bpx/KIkcgCtSo6qC5Ih
DzeZXnfJYcE+8U+O6hEr5dwByN4DgYQAAoGAeaKLPS4ktxULg3YQL0ePphF08tKs
ddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9LgJU4JOA27snO3fCsPAVkm
J0O2pbxn+wzT7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx92UyuDzoQ
TGxgCrPccQPjUgY=
-----END PUBLIC KEY-----
And thus my problem. How do I get this value from my cert?
Thanks!
You should use cert.PublicKey.EncodedKeyValue instead of cert.GetPublicKey().
EncodedKeyValue provides ASN1 encoded value, not raw key data as GetPublicKey().
So you can use this code
void ExportPublicKey(X509Certificate2 cert, string filePath)
{
byte[] encodedPublicKey = cert.PublicKey.EncodedKeyValue.RawData;
File.WriteAllLines(filePath, new[] {
"-----BEGIN PUBLIC KEY-----",
Convert.ToBase64String(encodedPublicKey, Base64FormattingOptions.InsertLineBreaks),
"-----END PUBLIC KEY-----",
});
}
See Ian Boyd's answer. It just provides all the answer that you're looking for about encoding. Note that it's related to RSA and not DSA, but it gaves you all the informations about PEM/DER/ASN.1 encoding, which is your problem here.