I am trying to get a public PGP key from a keyring created by GnuPG using the BouncyCastle C# library. I've gotten it to semi-work by using the following code. The problem is that the public key it outputs is about half the length of the real one and the last few bytes are also different. I'm just trying to get the real key.
UPDATE: Something interesting to note is that the keyring I generated only had one public key, yet I'm getting two out of bouncycastle. I also found that if you insert the second key into the first a few characters from the end, it produces almost the original key. Only a few chars at the end are different. So why are there two keys and why does this occur? What am I missing?
Is the GnuPG keyring not compatible?
Also note that the code shown here only gets the last key. I'm now adding each to a list.
Here is my code:
public static string ReadKey(string pubkeyFile)
{
string theKey;
Stream fs = File.OpenRead(pubkeyFile);
//
// Read the public key rings
//
PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(fs));
fs.Close();
foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings())
{
pgpPub.GetPublicKey();
foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
{
//AsymmetricKeyParameter pubKey = pgpKey.GetKey();
//SubjectPublicKeyInfo k = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey);
//byte[] keyData = k.ToAsn1Object().GetDerEncoded();
//byte[] keyData = k.GetEncoded();
byte[] keyData = pgpKey.GetEncoded();
theKey = Convert.ToBase64String(keyData);
}
}
return theKey;
}
Here is the actual public key:
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v2.0.20 (MingW32)
mQENBFP2z94BCADKfQT9DGHm4y/VEAYGL7XiUavbv+aE7D2OZ2jCbwnx7BYzQBu8
63v5qYe7oH0oBOiw67VaQSjS58fSBAE8vlTkKjvRAscHJNUX9qZrQoRtpMSnrK7N
Ca9N2ptvof7ykF1TAgbxDSSnhwysVznYc7mx76BO6Qx8KChqEd0Yp3w2U89YkUqN
qdzjB7ZIhj5hDM9f4eyHwsz0uZgyqLKK5VgNj6dHVmOHZt6+RIydRC2lGfocWKM8
loPkk6GiSX9sdEm6GXxi7gV/Q3Jr0G099AFg57cWyj1eO6NC8YHLgBH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Qj376C69W90R/LHByCrcCg7
xmqAvO9a8Eac7Rk+Fc+5NKVw9D1rP7MqZGgIQQoh8jLiI2MblvEEahwNxA9AYs8U
PpMD0pdo93wxXIYuKc40MF4yFL9LfpPxDnf373dbYQjk3pNThQ5RagIgLNEhRow4
5x/1wcO6FMx5a/irQXnJ2o1XYRvznBeCsoyOAYbikA==
=r3Qj
-----END PGP PUBLIC KEY BLOCK-----
Here is NEW KEY produced by BouncyCastle (sorry can't help formatting):
mQENBFP2z94BCADKfQT9DGHm4y/VEAYGL7XiUavbv+aE7D2OZ2jCbwnx7BYzQBu863v5qYe7oH0oBOiw67VaQSjS58fSBAE8vlTkKjvRAscHJNUX9qZrQoRtpMSnrK7NCa9N2ptvof7ykF1TAgbxDSSnhwysVznYc7mx76BO6Qx8KChqEd0Yp3w2U89YkUqNqdzjB7ZIhj5hDM9f4eyHwsz0uZgyqLKK5VgNj6dHVmOHZt6+RIydRC2lGfocWKM8loPkk6GiSX9sdEm6GXxi7gV/Q3Jr0G099AFg57cWyj1eO6NC8YHLgBHwrB1IkFwiJ0x5IHZssy/XleQ1i1izc3ntWiiH24powuAhABEBAAG0H3N5bmFwczMgPHN5bmFwczNAc2FmZS1tYWlsLm5ldD6JATkEEwECACMFAlP2z94CGwMHCwkIBwMCAQYVCAIJCgsEFgIDAQIeAQIXgAAKCRD944Hz1MHUYP+AB/4roauazFR5lDrJBFB0YoH4VFKM28IJtuy6OThg3cxhqI/N74sZoxtB90QQk4lcshdpwD7CIe9TCKrnhWokIdm4N91mTGDmW7iIeM3kcPp3mj9/7hGOetESuz9JxhBQ0aHAXYk5LdHeDKyRg1KL3JvWrJ27fioDoLLpxxdudSd2nJLhi0hAaHKnkLVl98r37AwxTigGj+J2rN47D+UepJraf8jeeZrY/RfwKJVleF1KYPIgduwX3jdiABrI4EsZP/CdbEWTvmmkFFtD4clSMsmqaXPTa3VeaL/saScBPL93tDsjqCddcgW28hsnhzoJ7TM78j2zNcTXZjK8/tNCDnShsAIAA7kBDQRT9s/eAQgA5ggDCKTqedfMsFJRuT83uR3aYBokBdul88MVLd5jwDFwVEO76kTA/8zWoD1yrYaf6eLdI0aBcBcBfuwqka8ZL9ka4+Tqgw+yahE2OZ30WdB734uHD5H9oEte0lSOC0hUP7/7CEjTYiNwaP8b6TnivgH9PO4+ARHvL4xbss39PBwoJSqC+lgKfOflnNr4/uxGx+tWJaCijboKt+AMrjYdUGJpeiyNOG9ikdG/6l01vFKi764eGBmjqZPNJew6QZioBrV5/CRX1PVd7BgrHEp38w7yo6qZrSl4iRcTtqcjwjeY0SnxjDksgH2dtTSKwSREf1r7iAJbPE4pJPsCkSl66QARAQABiQEfBBgBAgAJBQJT9s/eAhsMAAoJEP3jgfPUwdRgwxAH/jgPYYG9xS2xLXDb5FJfcE7S2sa/ZwLAaMKHzRCEx/eoVcOIunpvUY4Nvf/uCa5w4Ym7obBa/xfLiqI/omRhcNjaVx2COskvgS27lY/IzpGAMhqt+BzDVl7ktTa+FRzsSmyppi7vGIXWEZNihfXzyNkI9++guvVvdEfyxwcgq3AoO8ZqgLzvWvBGnO0ZPhXPuTSlcPQ9az+zKmRoCEEKIfIy4iNjG5bxBGocDcQPQGLPFD6TA9KXaPd8MVyGLinONDBeMhS/S36T8Q539+93W2EI5N6TU4UOUWoCICzRIUaMOOcf9cHDuhTMeWv4q0F5ydqNV2Eb85wXgrKMjgGG4pCwAgAD
Still not the same. Put both keys in notepad and search the "tNCDnS", after that is where they change.
Thanks for sticking with me. I've gotten far enough with this that I don't want to scrap the whole code for some shitty encryption.
You may have been a victim of BouncyCastle's somewhat uncommon usage of the term "keyring". Here is BouncyCastle's usage of three related terms:
PgpPublicKey: This is the public part of a single mathematical key, in PGP format. It does not contain any subkeys.
PgpPublicKeyRing: This is a cryptographic key with its subkeys. Other programs usually refer to this as a PGP Key.
PgpPublicKeyRingBundle: This is any number of PgpPublicKeyRings (as defined in BouncyCastle). Other programs usually refer to this as a Public Key Ring (without bundle).
You iterated through the keyring to find all PgpPublicKey objects. You decoded them and return the last and only the last of them as a string. If you paste the input and output strings to pgpdump.net (you have to add the BEGIN and END headers to the output), you see that you lose the subkey in this procedure. Use the PgpPublicKeyRing's GetEncoded() method instead. This should retain all information and is also easier :-).
Additionally, PGP's Radix-encoding is a little bit more than just Base64-encoding. A lot of programs and libraries, including BC, ignores whether there are PGP headers and footers and also the CRC checksum that Radix-encoding includes as opposed to simple Base64. However, GPG is more strict and seems not to accept ASCII armors without CRC checksum. Therefore, you have to use the binary key (which is the byte[] keyData in your problem code) or create a proper PGP ASCII armor. I have edited the following code based on your code to implement the latter using BC's ArmoredOutputStream:
public static string ReadKey(string pubkeyFile)
{
Stream fs = File.OpenRead(pubkeyFile);
//
// Read the public key rings
//
PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(fs));
fs.Close();
foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings())
{
using (MemoryStream ms = new MemoryStream())
{
using (ArmoredOutputStream aos = new ArmoredOutputStream(ms))
pgpPub.Encode(aos);
return System.Text.Encoding.ASCII.GetString(ms.ToArray());
}
}
return null;
}
EDIT: The following is a complete program with no external dependencies. It works for me, i.e. outputs "Same!". Please run that exact program and check whether it outputs "Same!" or "Difference!". If it outputs "Same!", then you can use it to correct your own program code:
using System;
using System.IO;
using Org.BouncyCastle.Bcpg.OpenPgp;
class Program
{
private const string PGP_OVERFLOW_KEYBODY =
"mQENBFP2z94BCADKfQT9DGHm4y/VEAYGL7XiUavbv+aE7D2OZ2jCbwnx7BYzQBu8\r\n" +
"63v5qYe7oH0oBOiw67VaQSjS58fSBAE8vlTkKjvRAscHJNUX9qZrQoRtpMSnrK7N\r\n" +
"Ca9N2ptvof7ykF1TAgbxDSSnhwysVznYc7mx76BO6Qx8KChqEd0Yp3w2U89YkUqN\r\n" +
"qdzjB7ZIhj5hDM9f4eyHwsz0uZgyqLKK5VgNj6dHVmOHZt6+RIydRC2lGfocWKM8\r\n" +
"loPkk6GiSX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Af+OA9hgb3FLbEtcNvkUl9wTtLaxr9nAsBowofNEITH96hV\r\n" +
"w4i6em9Rjg29/+4JrnDhibuhsFr/F8uKoj+iZGFw2NpXHYI6yS+BLbuVj8jOkYAy\r\n" +
"Gq34HMNWXuS1Nr4VHOxKbKmmLu8YhdYRk2KF9fPI2Qj376C69W90R/LHByCrcCg7\r\n" +
"xmqAvO9a8Eac7Rk+Fc+5NKVw9D1rP7MqZGgIQQoh8jLiI2MblvEEahwNxA9AYs8U\r\n" +
"PpMD0pdo93wxXIYuKc40MF4yFL9LfpPxDnf373dbYQjk3pNThQ5RagIgLNEhRow4\r\n" +
"5x/1wcO6FMx5a/irQXnJ2o1XYRvznBeCsoyOAYbikA==";
static void Main(string[] args)
{
string parsedKey = ReadKeyDirectly(PGP_OVERFLOW_KEYBODY);
if (parsedKey != PGP_OVERFLOW_KEYBODY.Replace("\r\n",""))
Console.WriteLine("Difference!");
else
Console.WriteLine("Same!");
}
public static string ReadKeyDirectly(string stringKeyData)
{
Stream fs = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(stringKeyData));
fs.Seek(0, SeekOrigin.Begin);
PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(fs));
foreach (PgpPublicKeyRing pubRing in pubRings.GetKeyRings())
return Convert.ToBase64String(pubRing.GetEncoded());
return null;
}
}
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+LlY3aOqzsU2sqnzGnItRzr2HnQwVV10MMFo3fbuWopzXqzVjQbnxJM9G79l20Np2eFLDVp4zpiYrGHWSFOnfIDqmy5ke57WnISJwnPz6A+ByhYVJfaxohkk+csbaPCsILQ0ZCzTnCcoh9svw9AIvlHn5YyAa8Gl5o6Ub8lsJXOSftGVtcCsWRiLbD1pg1CTQmoKPPxUFsa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8YShFl/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+csbaPCsILQ0ZCzTnCcoh9svw9AIvlHn5YyAa8Gl5o6Ub8lsJXOSftGVtcCsWRiLbD1pg1CTQmoKPPxUFsaU9iPXrfb48+5hFFOVe6+22S8YShFl/HaRq8TMESXmCiRgbgzBV7zmABkJFtH6WUBkXqBTSlUoEsYUHIV61vptroHHui/aVxnynv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u+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 am encrypting the message in .NET with RSACryptoServiceProvider with private key. (PKCS#1 v1.5)
When I try to decrypt in .NET with the following code that uses public key everything works fine:
private static string Decrypt(string key, string content)
{
byte[] rgb = Convert.FromBase64String(content);
var cryptoServiceProvider = new RSACryptoServiceProvider(new CspParameters()
{
ProviderType = 1
});
cryptoServiceProvider.ImportCspBlob(Convert.FromBase64String(key));
return Convert.ToBase64String(cryptoServiceProvider.Decrypt(rgb, false));
}
When on the other hand I try to find an algorithm to make the same decrypt method in Android, I am failing to decrypt it properly with public key. I exported the modulus and exponent from public key in .NET in order to load it properly on Android.
The method in Android is here:
public String Decrypt(String input) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
String modulusString = "mmGn1IXB+/NEm1ecLiUzgz7g2L6L5EE5DUcptppTNwZSqxeYKn0AuAccupL0iyX3LMPw6Dl9pjPXDjk93TQwYwyGgZaXOSRDQd/W2Y93g8erpGBRm/Olt7QN2GYhxP8Vn+cWUbNuikdD4yMfYX9NeD9UNt5WJGFf+jRkLk0zRK0A7ZIS+q0NvGJ/CgaRuoe3x4Mh1qYP9ZWNRw8rsDbZ6N2zyUa3Hk/WJkptRa6jrzc937r3QYF3eDTurVJZHwC7c3TJ474/8up3YNREnpK1p7hqwQ78fn35Tw4ZyTNxCevVJfYtc7pKHHiwfk36OxtOIesfKlMnHMs4vMWJm79ctixqAe3i9aFbbRj710dKAfZZ0FnwSnTpsoKO5g7N8mKY8nVpZej7tcLdTL44JqWEqnQkocRqgO/p3R8V/6To/OjQGf0r6ut9y/LnlM5qalnKJ1gFg1D7gCzZJ150TX4AO5kGSAFRyjkwGxnR0WLKf+BDZ8T/syOrFOrzg6b05OxiECwCvLWk0AaQiJkdu2uHbsFUj3J2BcwDYm/kZiD0Ri886xHqZMNExZshlIqiecqCskQhaMVC1+aCm+IFf16Qg/+eMYCd+3jm/deezT4rcMBOV/M+muownGYQ9WOdjEK53h9oVheahD3LqCW8MizABFimvXR3wAgkIUvhocVhSN0=";
String exponentString = "AQAB";
byte[] modulusBytes = Base64.decode(modulusString.getBytes("UTF-8"), Base64.DEFAULT);
byte[] dBytes = Base64.decode(exponentString.getBytes("UTF-8"), Base64.DEFAULT);
BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger d = new BigInteger(1, dBytes);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, d);
PublicKey key = keyFactory.generatePublic(keySpec);
//at one point I read somewhere that .net reverses the byte array so that it needs to be reversed for java, but who knows any more
/*byte[] inputArrayReversed = Base64.decode(input.getBytes("UTF-8"), Base64.DEFAULT);
for (int i = 0; i < inputArrayReversed.length / 2; i++) {
byte temp = inputArrayReversed[i];
inputArrayReversed[i] = inputArrayReversed[inputArrayReversed.length - 1];
inputArrayReversed[inputArrayReversed.length - 1] = temp;
}*/
byte[] decryptedText = null;
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
decryptedText = cipher.doFinal(Base64.decode(input.getBytes("UTF-8"), Base64.DEFAULT));
return Base64.encodeToString(decryptedText, Base64.NO_WRAP);
//return new String(decryptedText, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
Actually I tried also with different algorithms specified in Cypher class, also tried many other combinations, tried using SpongyCastle instead of built in Android RSA providers, but nothing worked. If anybody has any clue to point me in right direction, I would be absolutely grateful.
First hint is that decrypted string from .NET comes as around 25 characters long, and when I get Android to return decrypted string without exceptions it is usually much longer, around 500 bytes.
Second hint deleted
Third hint I also tried spongycastle, but it didn't help that much
Anyways, thank you in advance for any help!!!
UPDATE 1
Second hint is deleted because was wrong, disregard it. Now I have one question if the following can prove that the public key is loaded correctly, just to rule that problem out.
BigInteger modulus and exponent in the upper Android code and the following BigIntegers in .NET show equal integer values.
var parameters = csp.ExportParameters(false);
var modulusInteger = new BigInteger(parameters.Modulus.Reverse().Concat(new byte[] { 0 }).ToArray());
var exponentInteger = new BigInteger(parameters.Exponent.Reverse().Concat(new byte[] { 0 }).ToArray());
UPDATE 2
This and This SO answers provide some interesting clues
Heeh, the mistake was one of the basics, we had an architecture where we were doing encryption with public key and decryption with private key. The problem was in the architecture itself because as we initially set it up, we were sending private keys to all our client apps, which is big security flaw.
My mistake was that I assumed that on the client we have public key and actually from private key all the time I was trying to load the public key and then do decrypt.
If I knew the PKI in depth and communicated a bit better with my colleague, I could have noticed few things:
Decrypt can be done with private key only, while one the other hand verify can be done with public key, so when I saw Decrypt being used on client in .NET, I should have assumed that on the client we have private key (which is a security flaw in the end in the way we want to use PKI)
Few things that I already knew or learnt and want to share with others:
Private key should be kept secret, whether you want to have it on server or preferably only on one client because public key can easily be guessed from private key and then someone can easily repeat your whole encryption process easily and breach your security
PKI works for two scenarios:
First scenario is when you want to Encrypt something and that only specific person/computer can Decrypt it. In first scenario as you see, many stakeholders can have someone's Public key and send messages to him and that only he can read them with his Private key. Second scenario is when you want to be sure that the message that came to you was not altered and was sent by specific person/computer. In that case you Sign data with Private key and Verify it on the other end with Public key. The only process that is suitable for us is Sign <-> Verify because we send plain text license with signature in it, and thus on the client we want to be sure that nobody tampered with the plain text license and that it came from us.
In your code, if Decrypt or Verify functions throw exceptions in 50% of the time it is because of loading the incorrect key or incorrectly loading the correct key and in the other 50% it is because you are using the incorrect algorithm or because algorithm parameters are incorrectly set or because the algorithm implementations between platforms are incompatible (the last one is very rare)
.NET server code
public string Sign(string privateKey, string data)
{
_rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey));
//// Write the message to a byte array using UTF8 as the encoding.
var encoder = new UTF8Encoding();
byte[] byteData = encoder.GetBytes(data);
//// Sign the data, using SHA512 as the hashing algorithm
byte[] encryptedBytes = _rsaProvider.SignData(byteData, new SHA1CryptoServiceProvider());
return Convert.ToBase64String(encryptedBytes);
}
.NET client code (Win Mobile)
private bool Verify(string key, string signature, string data)
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
rsaProvider.ImportCspBlob(Convert.FromBase64String(key));
byte[] signatureBytes = Convert.FromBase64String(signature);
var encoder = new UTF8Encoding();
byte[] dataBytes = encoder.GetBytes(data);
return rsaProvider.VerifyData(dataBytes, new SHA1CryptoServiceProvider(), signatureBytes);
}
Android client code:
public boolean Verify(RSAPublicKey key, String signature, String data)
{
try
{
Signature sign = Signature.getInstance("SHA1withRSA");
sign.initVerify(key);
sign.update(data.getBytes("UTF-8"));
return sign.verify(Base64.decode(signature.getBytes("UTF-8"), Base64.NO_WRAP));
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
in .NET public key is exported in xml format with following code:
public string ExportPublicToXML(string publicKey)
{
RSACryptoServiceProvider csp = new RSACryptoServiceProvider(new CspParameters()
{
ProviderType = 1
});
csp.ImportCspBlob(Convert.FromBase64String(publicKey));
return csp.ToXmlString(false);
}
and then modulus and exponent are used in Android to load public key:
private RSAPublicKey GetPublicKey(String keyXmlString) throws InvalidKeySpecException, UnsupportedEncodingException, NoSuchAlgorithmException
{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
String modulusString = keyXmlString.substring(keyXmlString.indexOf("<Modulus>"), keyXmlString.indexOf("</Modulus>")).replace("<Modulus>", "");
String exponentString = keyXmlString.substring(keyXmlString.indexOf("<Exponent>"), keyXmlString.indexOf("</Exponent>")).replace("<Exponent>", "");
byte[] modulusBytes = Base64.decode(modulusString.getBytes("UTF-8"), Base64.DEFAULT);
byte[] dBytes = Base64.decode(exponentString.getBytes("UTF-8"), Base64.DEFAULT);
BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger d = new BigInteger(1, dBytes);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, d);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
This is a duplicate of an unanswered question here: Using an RSA Public Key to decrypt a string that was encrypted using RSA Private Key
You can see the author found a solution using some code from here:
http://www.codeproject.com/KB/security/PrivateEncryption.aspx
Using code from that link looks very promising. The only thing missing is the padding. I typically use PKCS1.5 padding which is the default for OpenSSL RSA.
I know the answer to this question is very close. I know the only thing holding back decryption is the pkcs1.5 padding on the encrypted openssl ciphertext.
I was surprised to see how little information is out there on this subject because there are many situations where you would need a server to encrypt something, sign something, etc, and have a client application verify, decrypt, etc with the public key.
I also extensively tried using the RSACryptoServiceProvider to verify hash's resulting from the encryption using OpenSSL. For example, I would do a private key encryption using a SHA256 hash of the plaintext, then try to do a RSACryptoServiceProvider verify on that signature, and it does not work. I think the way MS does this is non standard and there are perhaps special customization at work with that.
So, the alternative is this question, which is simply taking private key encrypted ciphertext and using C# to decrypt it, thus, verifying it's authenticity. Hashes can be incorporated to make a simple signature verification system for data objects signed by the server and verified on the client.
I've looked through the PKCS1 RFC's, OpenSSL rsa source code, and other projects, I cannot get a solid answer on how to account for PKCS1 padding when doing my RSA Decrypt. I cannot locate where in the OpenSSL source code they handle the PKCS1 padding, otherwise, I might have an answer by now.
Also, this is my first question, I know it's a duplicate of an unanswered question, so, what to do? I googled that too, and found nothing.
The other thing I don't understand is why my decrypt method doesn't work. Since padding is removed after decryption, my decrypted data should resemble plaintext, and it's not even close. So, I'm almost sure that pkcs1 padding means that other things are happening, specifically, to the ciphertext which means that the ciphertext must be preprocessed prior to decryption to remove padding elements.
Perhaps simply filtering the ciphertext to remove padding elements is the simplest solution here...
Here is my Decrypt method:
public static byte[] PublicDecryption(this RSACryptoServiceProvider rsa, byte[] cipherData)
{
if (cipherData == null)
throw new ArgumentNullException("cipherData");
BigInteger numEncData = new BigInteger(cipherData);
RSAParameters rsaParams = rsa.ExportParameters(false);
BigInteger Exponent = GetBig(rsaParams.Exponent);
BigInteger Modulus = GetBig(rsaParams.Modulus);
BigInteger decData = BigInteger.ModPow(numEncData, Exponent, Modulus);
byte[] data = decData.ToByteArray();
byte[] result = new byte[data.Length - 1];
Array.Copy(data, result, result.Length);
result = RemovePadding(result);
Array.Reverse(result);
return result;
}
private static byte[] RemovePadding(byte[] data)
{
byte[] results = new byte[data.Length - 4];
Array.Copy(data, results, results.Length);
return results;
}
The problem isn't with the padding. In fact, removing padding values from decrypted ciphertext is actually very simple. The problem was with the software at this location:
You can see the author found a solution using some code from here: http://www.codeproject.com/KB/security/PrivateEncryption.aspx
And with Microsoft's implementation of System.Numeric which simply cannot handle larger integers...
To fix the issue, I looked at previous releases of code on the codeproject site and ended up with this PublicDecrypt method.
public static byte[] PublicDecryption(this RSACryptoServiceProvider rsa, byte[] cipherData)
{
if (cipherData == null)
throw new ArgumentNullException("cipherData");
BigInteger numEncData = new BigInteger(cipherData);
RSAParameters rsaParams = rsa.ExportParameters(false);
BigInteger Exponent = new BigInteger(rsaParams.Exponent);
BigInteger Modulus = new BigInteger(rsaParams.Modulus);
BigInteger decData2 = numEncData.modPow(Exponent, Modulus);
byte[] data = decData2.getBytes();
bool first = false;
List<byte> bl = new List<byte>();
for (int i = 0; i < data.Length; ++i)
{
if (!first && data[i] == 0x00)
{
first = true;
}
else if (first)
{
if (data[i] == 0x00)
{
return bl.ToArray();
}
bl.Add(data[i]);
}
}
if (bl.Count > 0)
return bl.ToArray();
return new byte[0];
}
That will perfectly decrypt ciphertext created by openssl using the rsautl utility, or the Perl Crypt::OpenSSL::RSA private_encrypt method.
The other big change was dropping the Microsoft BitInteger library which simply didn't work. I ended up using the one mentioned in the Code Project article , and found here:
http://www.codeproject.com/Articles/2728/C-BigInteger-Class
The key here is to set the maxintsize in the library to a value which is larger based on how big of a key size you are using. For 4096 bit, a value of 500 worked fine (approx length of the modulus).
Here is the calling method:
var encmsg3 = "JIA7qtOrbBthptILxnurAeiQM3JzSoi5WiPCpZrIIqURKfVQMN1BrondF9kyNzbjTs1DaEKEuMBVwKExZe22yCvXXpm8pwcEGc9EHcVK2MPqNo89tIF8LJcaDqBMwLvxdaa/QgebtpmOVN/TIWfuiV8KR+Wn07KwsgV+3SALbNgbOIR3RtCx3IiQ3tZzybJb08+ZKwJEOT011uwvvGmtJskQgq9PC8kr1RPXMgaP6xMX7PHFJ8ORhkuWOFfCh+R4NhY1cItVhnRewKpIC2qVlpzUYRAgKIKdCXuZDqUQdIponR29eTovvLb0DvKQCLTf9WI1SzUm6pKRn0vLsQL7L3UYHWl43ISrTpDdp+3oclhgRF3uITR4WCvoljephbGc6Gelk5z3Vi6lN0oQaazJ7zIen+a/Ts7ZX3KKlwPl4/lAFRjdjoqu7u4IAK7O7u1Jf2xDiGw18C/eGt8UHl09zU4qQf9/u+7gtJ+10z2NERlLSaCDjVqslwmmxu81pG2gCv8LfpR4JlPaFfBZMGfGBihyGryWhJwizUXXo8wgdoYbHRXe8/gL19qro0ea5pA9aAhDjTpX1Zzbwu2rUU7j6wtwQtUDJOGXXCw1VOHsx6WXeW196RkqG72ucVIaSAlx5TFJv8cnj6werEx1Ung5456gth3gj19zHc8E/Mwcpsk=";
byte[] enc = Convert.FromBase64String(encmsg3);
var dec = rsa2.PublicDecryption(enc);
Debug.Print("PLAINTEXT: " + Encoding.UTF8.GetString(dec));
The only last thing someone would need to completely replicate this would be getting the private key into openssl format so that they could pass the private and public keys back and forth between openssl and C#.
I used openssl.net, and created an RSA instance, and set all the variables using bignumbers. Here's the code for that:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(Properties.Resources.RSAParameters);
RSAParameters par = rsa.ExportParameters(true); // export the private key
using (OpenSSL.Crypto.RSA rsaos = new OpenSSL.Crypto.RSA())
using (BigNumber bnmod = BigNumber.FromArray(par.Modulus))
using (BigNumber bnexp = BigNumber.FromArray(par.Exponent))
using (BigNumber bnD = BigNumber.FromArray(par.D))
using (BigNumber bnP = BigNumber.FromArray(par.P))
using (BigNumber bnQ = BigNumber.FromArray(par.Q))
using (BigNumber bnDmodP = BigNumber.FromArray(par.DP))
using (BigNumber bnDmodQ = BigNumber.FromArray(par.DQ))
using (BigNumber bnInverse = BigNumber.FromArray(par.InverseQ))
{
rsaos.PublicExponent = bnexp;
rsaos.PublicModulus = bnmod;
rsaos.IQmodP = bnInverse;
rsaos.DmodP1 = bnDmodP;
rsaos.DmodQ1 = bnDmodQ;
rsaos.SecretPrimeFactorP = bnP;
rsaos.SecretPrimeFactorQ = bnQ;
rsaos.PrivateExponent = bnD;
string privatekey = rsaos.PrivateKeyAsPEM;
string publickey = rsaos.PublicKeyAsPEM
}
With that you can easily create an RSA key, export everything to OpenSSL, and encrypt/decrypt anything you want within reason. It is enough to handle private key encryption followed by public key decryption.
Cool.
There is a problem in the line in the PublicDecryption function:
BigInteger numEncData = new BigInteger(cipherData);
it shall be:
BigInteger numEncData = GetBig(cipherData);
This line shall also be removed:
Array.Reverse(result);
You may encounter some padding problem, but if you can get the data right, it shall be easy to correct that.
I need two methods one to encrypt and one to decrypt an xml file with a key= "hello world",the key hello world should be used to encrypt and decrypt the xml file.These methods should work on all machines!!! Any encryption methods will do. XML File contents below:
<root>
<lic>
<number>19834209</number>
<expiry>02/02/2002</expiry>
</lic>
</root>
Can some give me a sample?The issue is the msdn sample encyptions make a xml file encypted but when I decrypt on another machine it doesn't work.For example
I tried this sample:
How to: Encrypt XML Elements with Asymmetric Keys,
but here there is some kinda session and on another machine it says bad data phewf!
If you want the same key for encrypting and decrypting you should use a symmetric method (that's the definition, really). Here's the closest one to your sample (same source).
http://msdn.microsoft.com/en-us/library/sb7w85t6.aspx
The posted sample isn't working because they aren't using the same keys. Not only on different machines: running the program on the same machine twice should not work either (didn't work for me), because they use different random keys every time.
try adding this code after creating your key:
key = new RijndaelManaged();
string password = "Password1234"; //password here
byte[] saltBytes = Encoding.UTF8.GetBytes("Salt"); // salt here (another string)
var p = new Rfc2898DeriveBytes(password, saltBytes); //TODO: think about number of iterations (third parameter)
// sizes are devided by 8 because [ 1 byte = 8 bits ]
key.IV = p.GetBytes(key.BlockSize / 8);
key.Key = p.GetBytes(key.KeySize / 8);
Now the program is using the same key and initial vector, and Encrypt and Decrypt should work on all machines.
Also, consider renaming key to algorithm, otherwise this is very misleading. I'd say it's a bad, not-working-well example from MSDN.
NOTE: PasswordDeriveBytes.GetBytes() has been deprecated because of serious (security) issues within the PasswordDeriveBytes class. The code above has been rewritten to use the safer Rfc2898DeriveBytes class instead (PBKDF2 instead of PBKDF1). Code generated with the above using PasswordDeriveBytes may be compromised.
See also: Recommended # of iterations when using PKBDF2-SHA256?
First of all, if you want to use the same key for encrypting and decrypting, you should look at symmetric cryptography. Asymmetric cryptography is when the keys for encrypting and decrypting are different. Just so that you know - RSA is asymmetric, TripleDES and Rijndael are symmetric. There are others too, but .NET does not have default implementations for them.
I'd advise studying the System.Security.Cryptography namespace. And learning a bit about all that stuff. It has all you need to encrypt and decrypt files, as well as generate a password. In particular, you might be interested in these classes:
CryptoStream
PasswordDeriveBytes
RijndaelManaged
There are also examples for usage in MSDN for each of them. You can use these classes to encrypt any file, not just XML. If however you want to encrypt just a select few elements, you can take a look at System.Security.Cryptography.Xml namespace. I see you've already found one article about it. Keep following the links on that page and you will learn more about those classes.
Would be cooler if you used a private key to sign the <lic> element and added the result to the file (in a <hash> element perhaps). This would make it possibly for everyone to read the xml file in case your support needs to know the license number, or the date of expiry, but they can not change any values without the private key.
The public key needed to verify the signature would be common knowledge.
Clarification
Signing your code will only protect it against changes, it will not keep any information in it hidden. Your original question mentions encryption, but I am not sure that it is a requirement to hide the data, or just protect it from modification.
Example code: (Never publish PrivateKey.key. ServerMethods are only needed when signing the xml file, ClientMethods are only needed when verifying the xml file.)
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
public static class Program {
public static void Main() {
if (!File.Exists("PublicKey.key")) {
// Assume first run, generate keys and sign document.
ServerMethods.GenerateKeyPair();
var input = new XmlDocument();
input.Load("input.xml");
Debug.Assert(input.DocumentElement != null);
var licNode = input.DocumentElement["lic"];
Debug.Assert(licNode != null);
var licNodeXml = licNode.OuterXml;
var signedNode = input.CreateElement("signature");
signedNode.InnerText = ServerMethods.CalculateSignature(licNodeXml);
input.DocumentElement.AppendChild(signedNode);
input.Save("output.xml");
}
if (ClientMethods.IsValidLicense("output.xml")) {
Console.WriteLine("VALID");
} else {
Console.WriteLine("INVALID");
}
}
public static class ServerMethods {
public static void GenerateKeyPair() {
var rsa = SharedInformation.CryptoProvider;
using (var keyWriter = File.CreateText("PublicKey.key"))
keyWriter.Write(rsa.ToXmlString(false));
using (var keyWriter = File.CreateText("PrivateKey.key"))
keyWriter.Write(rsa.ToXmlString(true));
}
public static string CalculateSignature(string data) {
var rsa = SharedInformation.CryptoProvider;
rsa.FromXmlString(File.ReadAllText("PrivateKey.key"));
var dataBytes = Encoding.UTF8.GetBytes(data);
var signatureBytes = rsa.SignData(dataBytes, SharedInformation.HashAlgorithm);
return Convert.ToBase64String(signatureBytes);
}
}
public static class ClientMethods {
public static bool IsValid(string data, string signature) {
var rsa = SharedInformation.CryptoProvider;
rsa.FromXmlString(File.ReadAllText("PublicKey.key"));
var dataBytes = Encoding.UTF8.GetBytes(data);
var signatureBytes = Convert.FromBase64String(signature);
return rsa.VerifyData(dataBytes, SharedInformation.HashAlgorithm, signatureBytes);
}
public static bool IsValidLicense(string filename) {
var doc = new XmlDocument();
doc.Load(filename);
var licNode = doc.SelectSingleNode("/root/lic") as XmlElement;
var signatureNode = doc.SelectSingleNode("/root/signature") as XmlElement;
if (licNode == null || signatureNode == null) return false;
return IsValid(licNode.OuterXml, signatureNode.InnerText);
}
}
public static class SharedInformation {
public static int KeySize {
get { return 1024; }
}
public static string HashAlgorithm {
get { return "SHA512"; }
}
public static RSACryptoServiceProvider CryptoProvider {
get { return new RSACryptoServiceProvider(KeySize, new CspParameters()); }
}
}
}
this is how you digitally sign and verify XML documents Sign XML Documents
I have a .NET application. I need to store a text value encrypted in a file, then retrieve the encrypted value somewhere else in the code, and decrypt it.
I don't need the strongest or most secure encryption method on earth, just something that will suffice to say - I have the value encrypted, and am able to decrypt it.
I've searched a lot on the net to try and use cryptography, but most of the examples I find, don't clearly define the concepts, and the worst part is they seem to be machine specific.
Essentially, can someone please send a link to an easy to use method of encryption that can encrypt string values to a file, and then retrieve these values.
StackOverflow's Extension library has two nice little extensions to encrypt and decrypt a string with RSA. I have used the topic here a few times myself but haven't tested it really, but it is a StackOverflow Extension library so I assume it is tested and stable.
Encrypt:
public static string Encrypt(this string stringToEncrypt, string key)
{
if (string.IsNullOrEmpty(stringToEncrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");
}
System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
cspp.KeyContainerName = key;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true);
return BitConverter.ToString(bytes);
}
Decrypt:
public static string Decrypt(this string stringToDecrypt, string key)
{
string result = null;
if (string.IsNullOrEmpty(stringToDecrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
}
try
{
System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
cspp.KeyContainerName = key;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
string[] decryptArray = stringToDecrypt.Split(new string[] { "-" }, StringSplitOptions.None);
byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));
byte[] bytes = rsa.Decrypt(decryptByteArray, true);
result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
}
finally
{
// no need for further processing
}
return result;
}
If you're looking at doing symmetric encryption, then I'd consider the Enterprise Library Cryptography Application Block. David Hayden had a useful blog post about it, though its for Enterprise Library 2.0 (the current is 4.1), I think you will it is still useful.
In .NET you can use an instance of a SymmetricAlgorithm. Here on Stack Overflow there is a question that demonstrates how to encrypt and decrypt strings using a password. How you are going to handle the password is a different matter but I assume that you are not too concerned about that and simply want to "hide" some text from the prying eye.
Here is a blog post using the cryptography library that .NET comes with for a symmetric encryption/decryption.
A symmetric algorithm uses the same key to encrypt and decrypt, much as you use one key to lock and unlock your car door.
A public key algorithm would use one key to encrypt and another to decrypt, so, I can send you a file that is encrypted, and know that only you can decrypt it, as you have kept your key very secure and private.
http://blog.binaryocean.com/2006/01/08/NETSymmetricEncryption.aspx