Bouncy Castle Decryption in c# from private key and encrytedtext - c#

Encrytped text is:
wMXLjsRSfO1VngHqotJXoxygP1eTktr3gc3tuhdzXpqOy1N1V8/wflJuHkn1PX7Rf3/ccvL5vzPYYaKIm3s4IMhshrwVH3p4euprwRyNTvlBPLLmZ/b/wuTXkKqRdK81V9oHocIfxerivS4oIJfA4J6fMbtKom6IoE4GVhiAsJs=
My Private Key is:
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDIlsvQQVhLQsmRFr/KUcAjOE/nlCNPS+0Q+Q8sIhEZFmT9f2qR
3d/9gtaxGY/WYgFwFplMArtaMzqcQSwntH296E1CdDj2U/v1AhTVCupeyNdz7//E
hIWrmlHjkrFynghRBFEEkACDtAV96VdtDvk10Knzl2CZ2kPklGz39sQsgQIDAQAB
AoGBAKVEwYbD4CiaTZNSaBEdTC54njVSs8kI6Ll8S4j0RJwj/G90xOyMH5ozbAqc
4gsj0sV0iTe8ZHsMDHVjqSrJpnMU6wDHhKQpr+zITJUxbTPjxgJf/2tKtsvFIMnb
2ghjTS/lMMzMPyeMhUcsLjPpoK9c+SDkl/PWU9Ay/pYvCCf1AkEA77JrZzn4gdJ3
VqtXUlV/y249frMPwYh+dS+aahyUUw0QW9BVa65Ume2iO5gGFVC3eJBZYxALFGai
ih06j0HOlwJBANY7bvp/2UfM2XWHYXvKXfasq/UzOMnc7jQvGJV6aFvch6mVxuTi
+ah7CCqGPVEbn8ZK92FwtsHYd5EvQO+R2KcCQCDfe1Ng4/AKCUvdm9Ay4Z/oso5Z
yGNmcNFpgefjm4P4WrH81Ho8ImYp7QH3S35I36CtS1UGsj5OBSSj9ZAIGmkCQDI/
xowjKMfamLckhg0PLnMJlVvyI8PVelnrIg0NpSTG2VtBsmFFi+Gk2gl/ayp3HEba
lqPYWEWnjIQVXVnUD8kCQQDJpHSBSFQWRBRGHl2Oyy1SXiBYFdW2FH7+2c1WzN4P
iKkmgOXqC2RfMD0aE/xtMe8F2zFhPKcARIvEvfneVjmT
-----END RSA PRIVATE KEY-----
I am using Bouncy Castle in c# , when i decrypt using the encrytedtext and private key using below code:
keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
IAsymmetricBlockCipher cipher = new RsaEngine();
RsaKeyParameters privateKey = (RsaKeyParameters)keyPair.Private;
cipher.Init(false, keyPair.Private);
byte[] deciphered = cipher.ProcessBlock(bytesl, 0, bytesl.Length);
string decipheredText = utf8enc.GetString(deciphered);
I am getting decipheredText as
☻♣?????U??`?u????|???^H?|???☺????♦M>?→?&↔.0p?J??a?▼?S←$*▬T☼? xQ??-??Ai9;??siqD??_??? ♥↓§?k?Ny??kr?U??↔z Mazher Ul Haq
but my actual string was "Mazher Ul Haq" , How to get actual string

Your "encrypted text" is actually base64 text. I suspect that if you convert that into non-base64 data first, you should be fine. If you've already got it as a string, that's as simple as:
byte[] binaryData = Convert.FromBase64String(base64Text);
If you need to convert it to a string first:
string base64Text = Encoding.ASCII.GetString(base64Binary);
byte[] binaryData = Convert.FromBase64String(base64Text);

Related

RSA/ECB/PKCS1Padding C# Decyription Error String To PrivateKey

I'm getting an error in Private Key conversion, I can't decrypt.
Error: System.InvalidCastException: Could not cast object of type 'Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair' to type 'Org.BouncyCastle.Crypto.AsymmetricKeyParameter'.
When I convert it to AsymmetricCipherKeyPair type, the type does not match in the bottom line. I am waiting for your help.
static void Main()
{
var plainData = "plain_text";
RSA publicKeyEncryptor = getRSAPublic(#"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlYB5JrwA9fMxZxTRhG0NnKRwJizMZGJNq/xFfFxaEmKp3O6vZgsZMlFTi2kSC++yR/KriGKuGgbIYrgomn7BueoooAw5KLVO9CKKtNyQgg28vdOBbnQqljA+KID0PouAD8MqpDk9opi41zeEQPOSkAUsq5sHMptG7h9cgj0mNr2c4ffNolHAhPsrZVtGYtswhtznDkG463VOKLAmDLDeY9bASUsQXFOY+Em93GHFjStgZSTIEBof6HbUqIQf2rGjuPYCQsB/94BFma58epGz12zUPwKFMuxg89wbLOCjyAkocgS9zDnwKr7DVv08GmCUVVqI6ySzbWpKhiqWQvz4hwIDAQAB");
var plainBytes = Encoding.ASCII.GetBytes(plainData);
string encryptedPayload = System.Convert.ToBase64String(publicKeyEncryptor.Encrypt(plainBytes, RSAEncryptionPadding.Pkcs1));
RSA privateKeyDecyrpt = getRSAPrivate();
var y = privateKeyDecyrpt.Decrypt(Encoding.ASCII.GetBytes(encryptedPayload), RSAEncryptionPadding.Pkcs1);
Console.WriteLine(encryptedPayload);
}
public static RSA getRSAPublic(string publicKey)
{
string publicKeyPem = $"-----BEGIN PUBLIC KEY-----\r\n{ publicKey }\r\n-----END PUBLIC KEY-----\r\n";
var pemReader = new PemReader(new StringReader(publicKeyPem));
AsymmetricKeyParameter keyPairRaw = (AsymmetricKeyParameter)pemReader.ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)keyPairRaw);
RSA rsaObj = System.Security.Cryptography.RSA.Create();
rsaObj.ImportParameters(rsaParams);
return rsaObj;
}
public static RSA getRSAPrivate()
{
string privateKeyPem = #"-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAlYB5JrwA9fMxZxTRhG0NnKRwJizMZGJNq/xFfFxaEmKp3O6v
ZgsZMlFTi2kSC++yR/KriGKuGgbIYrgomn7BueoooAw5KLVO9CKKtNyQgg28vdOB
bnQqljA+KID0PouAD8MqpDk9opi41zeEQPOSkAUsq5sHMptG7h9cgj0mNr2c4ffN
olHAhPsrZVtGYtswhtznDkG463VOKLAmDLDeY9bASUsQXFOY+Em93GHFjStgZSTI
EBof6HbUqIQf2rGjuPYCQsB/94BFma58epGz12zUPwKFMuxg89wbLOCjyAkocgS9
zDnwKr7DVv08GmCUVVqI6ySzbWpKhiqWQvz4hwIDAQABAoIBAEJFR+8Gqbpcykpy
bQmxubX1Io2ZkCTzepDBbB/bZEYAHGIGIBQw2UN3z3vd4JUP9Mx14tm7PIfm987i
6YTKqZ97D/UaVgAYlt4brbbMivZLlp3i8t3+ep5G1lboCtzqw6K5Fd7kTNEVt+IX
BvYvwok68flD6GXjdQa7Oiu1ZYofxXOBg84RDWu6E6edDj/XaaX12WOYaQ4p6zDn
jyYNMiYYkKoUI1a884cN50WAAIGs0n3TxgJGXZa0n/Y3CpvuphAoHPQQs7ZyJPlP
k29gaFXdotzv1TDKk0I+eTIlonMl1EyW0wDPvfMuV7EYNNfmtmqrT3OWkOpUU8fO
9eDKhukCgYEA5nlVlTKAx5LsKI3KGRQF3jiWAaQAUKoON68Sx47fSJSv317QyZqM
qbQTLz5vSytbTyHhgIEc2dtdRbl7MYkvvzaizjPDEHEJSwlTmnzt81qGYtjNGC+j
tz6Bx5MGDE8Ax3ls60Lm0uH9TMQyJZWTepZGght5WXP5NpmzJ6zG7D0CgYEApg9S
zZyMN1rNtcz6Pqaqll33hchIQd+vh2LLKkHAoQP93oWtipxyT08yr4tQ5ke3nwjj
onIt6KR0U2aSIv9OUwXw2cSwghCIqTKmtont88WXYh9zRtnZ+U0An9r3x+fr7e8y
wpk7lFPP840pzQQjyEQ2s3woMlssqOiS6SyGMBMCgYB04KVBEypxixWN/1G05A2R
wxp3XIb4YTTykisw3khnU1fZLAkvo9ufl/1+oOfps+QLPkBQXamW5YLogAZ0eYCo
NHndnixW4yv2TJWEK8Sz+31ZFV702/vnSqCf5/RSO6JGhlJxAC10VjyROJHBs5fl
u92nz2z7qy9/u/Q5s4nxdQKBgAx6qFFVS2A5ja302nVs1vL32ssN8wgoRCubbAMf
79bp0uEvEIyTFzAIlpmEka7MgusLovepNvP9r9Q4qBDDOOKaVrA2zMDpdyun58ld
8ijYl3jDPkl7w5qtg7d/oBFAx4UY7aqcE1MhPUZjPFnwzrOVFLtGQEsQePm0iJ3H
P8pLAoGAUCC6KxGF20y0uBnSLS2q3iqAqZNO57ZLnJRAscsViNEhqn4G5OZbcANa
RsyFluCwjuKFg9yW9s6ZKzjPXsAEWTyXpayICSG4gJBRfdzUol5Sjo9JweqMhiVh
5G9uBYx3+kEpYNvJDcYK89HQ3fAcfeZ1o9sXYtwccOulSQ5euAE=
-----END RSA PRIVATE KEY-----";
var pemReader = new PemReader(new StringReader(privateKeyPem));
AsymmetricKeyParameter keyPairRaw = (AsymmetricKeyParameter)pemReader.ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)keyPairRaw);
RSA rsaObj = System.Security.Cryptography.RSA.Create();
rsaObj.ImportParameters(rsaParams);
return rsaObj;
}
The code essentially contains casting-related bugs that are most easily identified during debugging by determining the object types:
I'm getting an error in Private Key conversion, I can't decrypt. Error: System.InvalidCastException: Could not cast object of type 'Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair' to type 'Org.BouncyCastle.Crypto.AsymmetricKeyParameter'.
You can't import the private key 1:1 like the public key, because both have different formats. The PemReader returns a different object type in the case of the private key, namely AsymmetricCipherKeyPair, which you cannot cast into an AsymmetricKeyParameter. This is what the error message says. So it must be:
AsymmetricCipherKeyPair keyPairRaw = (AsymmetricCipherKeyPair)pemReader.ReadObject();
When I convert it to AsymmetricCipherKeyPair type, the type does not match in the bottom line.
You need to modify this line as well. Here you have to pass a keyPairRaw.Private that must be cast to RsaPrivateCrtKeyParameters:
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPairRaw.Private);
With these changes the import of the private key works.
Another bug is in the decryption. The ciphertext is Base64 encoded during encryption, therefore it must be Base64 decoded during decryption and not ASCII encoded, i.e. correct is:
var decrypted = privateKeyDecyrpt.Decrypt(Convert.FromBase64String(encryptedPayload), RSAEncryptionPadding.Pkcs1);
Keep in mind that the options for importing keys in .NET are highly dependent on the version. There are versions where you can import PEM keys out-of-the-box (e.g. as of .NET 5), so that BouncyCastle is not needed.

System.IO.IOException: -----END RSA PRIVATE KEY not found

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-----"

Importing an Objective-C RSA public key into c# RSACryptoServiceProvider

Here is the Objective-C we are using to generate the RSA object using the following lib: https://github.com/kuapay/iOS-Certificate--Key--and-Trust-Sample-Project
BDRSACryptor *rsa = [[BDRSACryptor alloc] init];
BDRSACryptorKeyPair *RSAKeyPair = [rsa generateKeyPairWithKeyIdentifier:nil error:error];
We then pass RSAKeyPair.publicKey to our c#, where using the BouncyCastles library:
using (TextReader sr = new StringReader(pempublic))
{
var pemReader = new PemReader(sr);
var temp = (RsaKeyParameters)pemReader.ReadObject();
var RSAKeyInfo = new RSAParameters
{
Modulus = temp.Modulus.ToByteArray(),
Exponent = temp.Exponent.ToByteArray()
};
var rsaEncryptor = new RSACryptoServiceProvider();
rsaEncryptor.ImportParameters(RSAKeyInfo);
}
There are no errors, but the encryption is different. The same string encrypted in c# and obj-c are different, and we are unable to encrypt on one end and decrypt on the other.
Help!
Edit: Willing to consider any methodology of exchanging public keys between c# and obj-c. This is just the closest we have come so far.
Edit2: Contents of pempublic
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/ugxekK+lY0VLeD8qA5nEhIn7IzBkgcrpiEM109chFxHobtvWEZbu8TqTIBtIgtISNp4idcEvahPniEyUawjmRSWB7uYmcHJ3pWaIo5/wBthmGrqS/XjedVXT6RuzaoPf9t0YXyW6YiH1kQZn4gjZF51O6iIk2+VnfkYVqeKBtQIDAQAB-----END PUBLIC KEY-----
Edit3: Regarding padding: C# and obj-c are both using OEAP padding.
Edit4: How the text is being encrypted: c#
byte[] testBytes = Encoding.UTF8.GetBytes("1234567890");
byte[] encryptedBytes = rsaEncryptor.Encrypt(testBytes, true);
string base64 = Convert.ToBase64String(encryptedBytes);
obj-c
NSString *encrypted = [rsa encrypt:#"1234567890" key:RSAKeyPair.publicKey error:error];
Final Edit:
Solved by using the Chilkat encryption library on the .NET server. We are now able to load an RSA encryptor from a public key in both XML and PEM format generated from a .NET, Java, or Objective-C Client. If anyone could explain why the .NET RSACryptoServiceProvider wouldn't work, we are all quite curious.
please check my answer to my own question
RSA C# encryption with public key to use with PHP openssl_private_decrypt(): Chilkat, BouncyCastle, RSACryptoServiceProvider
i think it may be helpful
to make it short, try using temp.Modulus.ToByteArrayUnsigned()
I wrote RSA and AES implementation using CommonCrypto, implementation is done in order to be interoperable with .NET
Check it out
https://github.com/ozgurshn/EncryptionForiOS
I used base64 encoding
.NET side could be
public string RsaDecryption(byte[] cipherText, string privateKey)
{
var cspDecryption = new RSACryptoServiceProvider();
cspDecryption.FromXmlString(privateKey);
var bytesPlainTextData = cspDecryption.Decrypt(cipherText, false);
return Encoding.UTF8.GetString(bytesPlainTextData);
}
public byte[] RsaEncryption(string plainText, string publicKey)
{
var cspEncryption = new RSACryptoServiceProvider();
cspEncryption.FromXmlString(publicKey);
var bytesPlainTextData = Encoding.UTF8.GetBytes(plainText);
var bytesCypherText = cspEncryption.Encrypt(bytesPlainTextData, false);
return bytesCypherText;
}

Encrypt in C# using RSACryptoServiceProvide and decrypt using openssl_private_decrypt in PHP

I spent whole day for trying to get it work but no luck:(
I use these code in C# for encryption:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters rsaParam = rsa.ExportParameters(false);
rsaParam.Modulus = Convert.FromBase64String("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwlhAsNcNCDRgzCc49u/0iSDrdJn7yoiH/HHipbQp0QSejzg/48mMA6wb32OPQ7qzBgJNvwiQbMvi89BvGNAJ9K8vM0RW7WOqtnb/8IK9BAJVtEwJ3vvKTf5EluiUgWVbGYpWPjbl/lsD3/hRTR0uF46h7q4OlARxOupl9xVS2wQIDAQAB");
rsa.ImportParameters(rsaParam);
string msg = "This is a test.";
byte[] encValue = rsa.Encrypt(Encoding.UTF8.GetBytes(msg), true);
Console.WriteLine(Convert.ToBase64String(encValue));
This is the PHP code I use to decrypt.
// Read key
$fp = fopen($KeyPath,"r");
$Key = fread($fp,8192);
fclose($fp);
openssl_private_decrypt($data, $decrypted, openssl_get_privatekey($Key, "123456"));
The private key I used(Passphase "123456"):
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,16B167A1F1E4E61E
A0eOxhU9Fp4ZIkmSpCUOA2VGG8evE71bEz/eO5LlUatUTt4RQcu68mFOM23PdnHl
YqjTV7AwedUu+LsNtjDfy+NJzvvi+re/kpYAD9RWDE0buHGp86vIhxJLCA633JSt
kcMbkFBBbJPBW74FK7Djo2tlE/jKFb4Uy6EIBEsI56pcbdOIKWHTOLHb3/gG8spx
/jPyylR1D1Rm1Nw9mhfQ8c+GZoXYn919Zx9fvKYq5CiH8hqy6q1TCsTjUpdgdkxz
3kDQ6nn4cOCCwCwU2F+iRpzmSE0DORPtCK/rNdhHXaVqm/SvIDSerpX6L4l8NiRx
Vb19htQChysfB7O/XiDVxL8gqSUmMrSujP50NUlyuBEG/32JyCounlX/4JQEGvAN
ALGkLwULhp1D2ATQVck5aNncxcbuB56laf+KZm5E83Tbeu1j4MG+JzJq+kbLVuYi
7TJ1JqjjL4Ixlyh/M23UuViFsw1V0zuZslFhvtq0/hdNXhIgNVmMFPFadOSKMtVY
kTkX7+coEXrtwPV+4ztoH3M2+zwZczkNECbed9H0PPw6uhrOpu+EyGR4qJ/TsMe1
Ht60veBMuPhwC5TqKP8Luz8x57d5Y4+kBFMvQda1b38PUuXSRw2OZ+cBHk0wrET/
pnyOIhg3lvREPvhXpe1oyaSZZLu95xTAj9YSDG+iKToDCD8hgdaRn1Pi6VOaz8Ru
+AUjz0L0fbwrU7jZ3x2L1AGsdwVwmwTL8Fwk/WY8sWu3KCW4olW1nQ8o/4+jO7q9
JvrYW/HxqIxP0Mnc9ODNmaG/NH1q5v7LIPAz47bpqXwdr8hDV/L5mA==
-----END RSA PRIVATE KEY-----
I am not familiar with encryption, can some one please tell how to get it work?
PS: I think the code in php is fine since I tested the code seperately.
You can use this code for encrypt your string.
public string EncodeData(string sData)
{
try {
byte[] encData_byte = new byte[sData.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
} catch (Exception ex) {
throw new Exception("Error in base64Encode" + ex.Message);
}
}
and for decrypt your string you can use this code.
public string DecodeData(string sData)
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(sData);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
Try this this will work.
Thank you.
Are you sure RSACryptoProvider is working with the key in the format you're providing it in?
A lot of examples of RSACryptoProvider I've seen use XML-based private keys. eg.
RSA Signing with PHP and verifying with C#
"<RSAKeyValue><Modulus>3BqiIB3ouyXHDMpW43TlZrx8fkts2FVVARJKNXFRQ/WIlsthDzL2jY2KEJVN6BKE4A51X+8LMzAI+2z3vIgAQT3bRSfOwygpGBjdhhnXJwFlQ6Gf/+z0ffQfVx/DHw3+QWphcwGDBst+KIA6u6ayy+RDE+jEityyyWDiWqkR9J8=</Modulus><Exponent>AQAB</Exponent><P>8a8nuVhIANh7J2TLn4wWTXhZY1tvlyFKaslOeAOVr+wgEWLQpLZ0Jpjm8aUyyOYPXlk7xrA5BOebtz41diu4RQ==</P><Q>6SQ9y3sEMjrf/c4bHGVlhOj4LUVykradWWUNC0ya7llnR8y1djJ1uUut+EoAa1JQCGukuv4K8NvN1Ieo72Fhkw==</Q><DP>cg0VMusNN5DxNRrk2IrUL4TesfuBQpGMO6554DrY1acZTvsRuNj9IQXA3kH2IEYo9H4prk6U6dKeci/iLLze/Q==</DP><DQ>m/pZNXeZ+RkWnrFzxe24m9FZqMAbxThT0Wkf7v1Tcj9yL8EvbmKYDF4riD/KRAMP9HJABbLNExObg6M3TOAz7Q==</DQ><InverseQ>w8PvW8srrPCuOcphBKXSyoZxCZn81+rovBxuE8AB95m5X+URE8SunK7f+g7hBBin6nUOaVGohBP8jzkQEsdx1Q==</InverseQ> <D>AsVPDypxOJHkLJQLffeFv8JVqt1WNG72j/nj90JC7KEVpBhRU3inw+ZpO4Y1odtB0vQ7pAaFVJKhOlEH2Va48hNUEQujML8rE+LZXgI3lu0TlqOCIqTHIljeJry0ca30XFtFDp9kh0Kr/0CgGMqgIed+hDUjAad8ke9D2YicDok=</D></RSAKeyValue>"
I searched for days and finally figured out myself:)
I am loading the parameters in the wrong way.
According to the RSA Public key structures(PEM):
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwlhAsNcNCDRgzCc49u/0iSDrdJn7yoiH/HHipbQp0QSejzg/48mMA6wb32OPQ7qzBgJNvwiQbMvi89BvGNAJ9K8vM0RW7WOqtnb/8IK9BAJVtEwJ3vvKTf5EluiUgWVbGYpWPjbl/lsD3/hRTR0uF46h7q4OlARxOupl9xVS2wQIDAQAB
Which I split the string into 3 parts(base64 encoded):
Header
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC
Modulus:
wlhAsNcNCDRgzCc49u/0iSDrdJn7yoiH/HHipbQp0QSejzg/48mMA6wb32OPQ7qzBgJNvwiQbMvi89BvGNAJ9K8vM0RW7WOqtnb/8IK9BAJVtEwJ3vvKTf5EluiUgWVbGYpWPjbl/lsD3/hRTR0uF46h7q4OlARxOupl9xVS2wQ
Exponent:
IDAQAB
(Note that I still didn't get a clear idea of the RSA key strutures. Those above are just a blurry view of a key structure, but for those who interested in, I recommend you to read the API Documentation "RSAParameters" or the RSA specification)
Obviously what I was doing is to import the entire key string to the RSAParameters.Modulus. That is not the way to import the key. So that's why it didn't work.
The way to do it is to extract the modulus and exponent which was needed for a public encryption from the key file. And import into RSAParameters
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
RSAKeyInfo.Modulus = modulus;
RSAKeyInfo.Exponent = exponent;
RSA.ImportParameters(RSAKeyInfo);
Then encrypt the string:
RSA.Encrypt("HAHA I GOT IT!!", false);
The way to extract. I recommend going to JavaScience for more info. There are bunch of cryptographic utilities there.

problem generating pgp keys?

I'm using RSACryptoServiceProvider I've generated public key and private key. The keys generated by it are in the following format:
Public key:
<RSAKeyValue>
<Modulus>m9bAoh2...eGNKYs=</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>
Private key:
<RSAKeyValue>
<Modulus>m9bAo...ZAIeGNKYs=</Modulus>
<Exponent>AQAB</Exponent>
<P>xGj/UcXs...R1lmeVQ==</P>
<Q>yx6e18aP...GXzXIXw==</Q>
<DP>NyxvnJ...1xAsEyQ==</DP>
<DQ>La17Jycd...FhApEqwznQ==</DQ>
<InverseQ>JrG7WCT...Hp3OWA==</InverseQ>
<D>RdWsOFn....KL699Vh6HK0=</D>
</RSAKeyValue>
but using PGP Desktop i've generated keys like this -
Public key:
mQCNBEoOlp8BBACi/3EvBZ83ZduvG6YHu5F0P7Z3xOnpIsaPvTk0q+dnjwDUa5sU
lEFbUZgDXSz7ZRhyiNqUOy+IG3ghPxpiKGBtldVpi33qaFCCEBiqsxRRpVCLgTUK
HP2kH5ysrlFWkxTo
=a4t9
Private key:
lQHgBEoOlp8BBACi/3EvBZ83ZduvG6YHu5F0P7Z3xOnpIsaPvTk0q+dnjwDUa5sU
lEFbUZgDXSz7ZRhyiNqUOy+IG3ghPxpiKGBtldVpi33qaFCCEBiqsxRRpVCLgTUK
waBnEitQti3XgUUEZnz/rnXcQVM0QFBe6H5x8fMDUw==
=CVPD
So when I'm passing the keys generated by PGP Desktop it is able to do encryption and decryption perfectly but when im passing the keys generated by RSACryptoServiceProvider I'm not able to encrypt and decrypt?
Can anyone please tell me how to generate keys in the pattern generated by PGP?
using the bouncycastle c# library this is how i generate key pairs.
public void GenerateKey(string username, string password, string keyStoreUrl)
{
IAsymmetricCipherKeyPairGenerator kpg = new RsaKeyPairGenerator();
kpg.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x13), new SecureRandom(), 1024, 8));
AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();
FileStream out1 = new FileInfo(string.Format("{0}secret.asc", keyStoreUrl)).OpenWrite();
FileStream out2 = new FileInfo(string.Format("{0}pub.asc", keyStoreUrl)).OpenWrite();
ExportKeyPair(out1, out2, kp.Public, kp.Private, username, password.ToCharArray(), true);
}
private static void ExportKeyPair(
Stream secretOut,
Stream publicOut,
AsymmetricKeyParameter publicKey,
AsymmetricKeyParameter privateKey,
string identity,
char[] passPhrase,
bool armor)
{
if (armor)
{
secretOut = new ArmoredOutputStream(secretOut);
}
PgpSecretKey secretKey = new PgpSecretKey(
PgpSignature.DefaultCertification,
PublicKeyAlgorithmTag.RsaGeneral,
publicKey,
privateKey,
DateTime.Now,
identity,
SymmetricKeyAlgorithmTag.Cast5,
passPhrase,
null,
null,
new SecureRandom()
// ,"BC"
);
secretKey.Encode(secretOut);
secretOut.Close();
if (armor)
{
publicOut = new ArmoredOutputStream(publicOut);
}
PgpPublicKey key = secretKey.PublicKey;
key.Encode(publicOut);
publicOut.Close();
}
and it generate private and public keys in armored ASCII format such as.
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: BCPG v1.32
mIsEShU7ywEEAKtxKTtGTyUaVxFuWBpziA2l7qDKhe6jznre3DMPuzDnN4Ax573a
7s/bPOkzkK9tEUGFw+BW6F4DkKydv8SQfSN5Vvc0RFMha8X1E8jki1oXTIPA8bKK
dg8ZewZt8+Zwpt5IPAkIydmxDhMjwd71ay3p1ypOfROFPOfc2dBPx/0JAAUTtAdo
YW1zbWFuiJwEEAECAAYFAkoVdAsACgkQEz/ESPB1tojuIQP8CjAzJx8PoIN33pxQ
AfGF+fMCZx8/m7dDBE113aiio25BCvNKOpFwye2UK4ioKN70k24pzkyi8AZO22/s
u6GL7XEiiBZLPynBxJR4A7PzvD3KNqdQUqesu9IkPFyXz3UFH3clR0hnZtZtgnbk
L9dvj5RYVuGiS3Dcf1zoLMOiCdc=
=dFfG
-----END PGP PUBLIC KEY BLOCK-----
RSA and PGP are different.
What you are essentially asking is how do I run my petrol car on diesel? The answer is you can't.
You should look into PGP CommandLine - this allows you to perform PGP commands from the command line.
thanks for the good methods, was faffing around the web for them since quite a while,
some correction tho...
After a call to
ExportKeyPair(out1, out2, kp.Public, kp.Private, username, password.ToCharArray(), true);
please also call
out1.Close();
out2.Close();
A sample private key generated from the above routine
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: BCPG C# v1.6.1.0
lQHqBEvhYOcBBACa5HjZ14ULRvZLKj+rwscQh63Zd9rnfZmVKN5fNsK+ocxxV8rc
TWa6P3knIWCra1lqZ1onNtM8tL1XRuK9pagu7XPjjHUR37ajYv/e0/w9IHlOBtM4
1T3oMM48FBH5WGZswOQnTCHoHpZilx7zeJgcyoUayM9uaWGWVLb6PqAE2QAFE/8D
AwL4BEE4Y+mD6GB0ctnbN4tZuctydODYJUNOK3p+UdgEh5rj5nOelB5h3kqFWdwq
8F3EBxB4guRnLOxIeSjzvFoFpqb4QSrM4brdisaHoK0qgrsyCaQhdepVlz662hSD
5bxJPQqmJ4c9X7x6tTMwDAseoz+VUK9U91iN9jv72hp2dXJYjJvBbkTX9euz2i4P
HrlLV2DuOeGWipsb+sIOuYqpZoK5aMq5AAGTTmmApYam/+0d2lXTt+Cw0FkoN1U+
CWriVFE+x58/MmpqKttlrHyp/c7aRmdxeKheY7QAnKPmTRFZAu6HR/DnLSya6+Qz
MqsYBZAocDs7Bg9U6N79Ynl7mkChoVR4ZwJE/OXgHDRSYlcBwT++frHI06cn1l8t
f0CWU/Z6EuYj/rmgL/v5ln7EQ2H+SRypPxYJKK8dTcu2uk5Ev1x4EOQ2nF1BxBB1
CceSVEimc2TDcVj0K7QIc3BhcmVraDOInAQQAQIABgUCS+FS1wAKCRBHXl7hbFhY
BLInA/9TPwmivxofs7/y4xmrl0X+Ruish0l+KC45/MQGU1bT2MYCR5jefyaUIHMK
gH8bX4DHobBFxtkTXoTgpZmm5JNHGiSQoOXqW7iqHOkp6q6rkwV9BYvfsbjMsfAB
bV7l29CMoMDj1qB3k9CJDP4MuorEI5Qx30x07Mm2+uwcYC2+Ag==
=jh9t
-----END PGP PRIVATE KEY BLOCK-----
thanks once again for the above methods.
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: BCPG C# v1.6.1.0
mIsES+Fg5wEEAJrkeNnXhQtG9ksqP6vCxxCHrdl32ud9mZUo3l82wr6hzHFXytxN
Zro/eSchYKtrWWpnWic20zy0vVdG4r2lqC7tc+OMdRHftqNi/97T/D0geU4G0zjV
PegwzjwUEflYZmzA5CdMIegelmKXHvN4mBzKhRrIz25pYZZUtvo+oATZAAUTtAhz
cGFyZWtoM4icBBABAgAGBQJL4VLXAAoJEEdeXuFsWFgEsicD/1M/CaK/Gh+zv/Lj
GauXRf5G6KyHSX4oLjn8xAZTVtPYxgJHmN5/JpQgcwqAfxtfgMehsEXG2RNehOCl
mabkk0caJJCg5epbuKoc6SnqrquTBX0Fi9+xuMyx8AFtXuXb0IygwOPWoHeT0IkM
/gy6isQjlDHfTHTsybb67BxgLb4C
=ZyOZ
-----END PGP PUBLIC KEY BLOCK-----

Categories