I'm trying to save RsaKeyParameter Public Key into an SQL database. I get an error that Bouncy Castle can't convert RsaKeyParameters to bytes.
Using BouncyCastle c#.
I've generate an RSA key pair, extracted the private and public keys into variables. I then need to store the public key for verification at a later stage in the application.
I found a post on converting to byte then string as follows;
byte[] serializedPublicBytes =
publicKeyInfo.ToAsn1Object().GetDerEncoded();
string serializedPublic = Convert.ToBase64String(serializedPublicBytes);
but it doesn't like ToAsn1Object. Just to add this is an example, I'm aware my variable names are different.
RsaKeyPairGenerator rsaKeyPairGen = new RsaKeyPairGenerator();
rsaKeyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
AsymmetricCipherKeyPair keyPair = rsaKeyPairGen.GenerateKeyPair();
RsaKeyParameters PrivateKey = (RsaKeyParameters)keyPair.Private;
RsaKeyParameters PublicKey = (RsaKeyParameters)keyPair.Public;
The public key should to byte, then string, to save into the database.
The public key can be converted to the X.509/SubjectPublicKeyInfo-ASN.1/DER-format using BouncyCastle. This is a binary format from which a string can be generated using Base64-encoding:
byte[] publicKeyDer = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey).GetDerEncoded();
String publicKeyDerBase64 = Convert.ToBase64String(publicKeyDer);
Here, publicKey is the public key stored in the RsaKeyParameters-instance. The reverse process is:
byte[] publicKeyDerRestored = Convert.FromBase64String(publicKeyDerBase64);
RsaKeyParameters publicKeyRestored = (RsaKeyParameters)PublicKeyFactory.CreateKey(publicKeyDerRestored);
Detailed descriptions of the X.509/SubjectPublicKeyInfo- and ASN.1/DER-format can be found here and here, respectively.
Both, publicKeyDer (as hex-string) and publicKeyDerBase64, can be displayed in an ASN.1-Editor, e.g. https://lapo.it/asn1js/
Another approach is to create the PEM-format using the Org.BouncyCastle.OpenSsl.PEMWriter- and Org.BouncyCastle.OpenSsl.PEMReader-class
(not to be confused with Org.BouncyCastle.Utilities.IO.Pem.PEMWriter/PEMReader):
TextWriter textWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(textWriter);
pemWriter.WriteObject(publicKey);
pemWriter.Writer.Flush();
String publicKeyPEM = textWriter.ToString();
and the reverse is:
TextReader textReader = new StringReader(publicKeyPEM);
PemReader pemReader = new PemReader(textReader);
RsaKeyParameters publicKeyRestored = (RsaKeyParameters)pemReader.ReadObject();
The PEM-format is essentially a textual representation of the DER-format using an implicit Base64-encoding (e.g. explained here) and a header (-----BEGIN PUBLIC KEY-----) and footer (-----END PUBLIC KEY-----). Therefore, the Base64-encoded part is identical (if line breaks are ignored) for both, publicKeyDerBase64 and publicKeyPEM.
Related
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.
I am trying o create a method that constructs an AsymmetricKeyParameter from a PEM encoded public key. Unfortunately, pemReader.ReadObject() return null.
Here's a working solution for a private key: convert PEM encoded RSA private key to AsymmetricKeyParameter
What is wrong with this method?
static AsymmetricKeyParameter ReadPublicKeyFromPemEncodedString(string pemEncodedKey)
{
AsymmetricKeyParameter result = null;
using (var stringReader = new StringReader(pemEncodedKey))
{
var pemReader = new PemReader(stringReader);
var pemObject = pemReader.ReadObject(); // null!
result = ((AsymmetricCipherKeyPair)pemObject).Public;
}
return result;
}
Here is the PEM-encoded public key I am testing with. I have tried without the comment and also removing SSH2.
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20170608"
AAAAB3NzaC1yc2EAAAABJQAAAQEAk0AmagKx285Ufbri/olc+f3WagL1Ho+DrYdD
SbuU7cJAq+uD9xGvvP9m2JavSP4wO9i9pB/cmCFMPoIj3oGJt1/cnLb/U2juneOw
6Uo0N3F8TXdyXfZNAIPhq/jw0YfIypTFTTvFkKXfTArIwW/bQBW8/dujFR8i5CxP
jRKRDOBEy0PPOLJDD0iUr9GX/h/EO4jQ7B/GszjhPiPx+gJCilaMY+jrSczjxpsK
OXzpZEdT1NqMrzgvIZPHYhQzAiw9vQzov3vezDwKgKcRrUixZ2B8uiEQNn7Wa2Qz
WF3vL+6CGflFNYQcc0leDQBe86baYhCollouP4jfaH9KcMkYYw==
---- END SSH2 PUBLIC KEY ----
Bouncy castle just does not understand this format of public key (SSH2) (you can verify this by looking at source code of PemReader if you would like to). Unfortunately I don't know how to convert it to appropriate format in C#, but you can do that with many tools, for example with ssh-keygen (also available in gitbash for windows), or openssl. Your public key will look like this when converted to PEM:
-----BEGIN RSA PUBLIC KEY-----
MIIBCAKCAQEAk0AmagKx285Ufbri/olc+f3WagL1Ho+DrYdDSbuU7cJAq+uD9xGv
vP9m2JavSP4wO9i9pB/cmCFMPoIj3oGJt1/cnLb/U2juneOw6Uo0N3F8TXdyXfZN
AIPhq/jw0YfIypTFTTvFkKXfTArIwW/bQBW8/dujFR8i5CxPjRKRDOBEy0PPOLJD
D0iUr9GX/h/EO4jQ7B/GszjhPiPx+gJCilaMY+jrSczjxpsKOXzpZEdT1NqMrzgv
IZPHYhQzAiw9vQzov3vezDwKgKcRrUixZ2B8uiEQNn7Wa2QzWF3vL+6CGflFNYQc
c0leDQBe86baYhCollouP4jfaH9KcMkYYwIBJQ==
-----END RSA PUBLIC KEY-----
And it will be correctly handled by your current code, with a little change:
var pemReader = new PemReader(stringReader);
var pemObject = pemReader.ReadObject(); // null!
// it's already AsymmetricKeyParameter
result = ((AsymmetricKeyParameter)pemObject);
I'm trying to encrypt a string given a public key that I've retrieved from an API. The public key is plain text (base 64 encoded), something like:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCH9/o5IG0tu9VNYiJSltzV5ewK9TNoLeToSYkoH4lEytRM61AMeO6aBRZ3dsY1Czb+fgK6Q+M4ub/9jbcXIGmVLvTypdn+VW1dotXzMP5sfDgCUuhScjH7gqsXQAvaF5LxjLUbL5I5zCGXbPVwBCEyVhN0oNp3TtNKoMcF6AjNhwIDAQAB
I now want to encrypt a string using this public key. I've found some relevant code that reads from a PEM format, but obviously it won't work here:
byte[] dataToEncrypt = Encoding.UTF8.GetBytes(aString);
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
using (var txtreader = new StringReader(key))
{
var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
encryptEngine.Init(true, keyParameter);
}
var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(dataToEncrypt, 0, dataToEncrypt.Length));
keyParameter ends up being null. The documentation for Bouncycastle seems to be pretty scant, I don't really have an idea of what I should be using to get the right AsymmetricKeyParameter type.
I suppose I could write a PEM file from the key but feels a bit wasteful.
So the broader question is: How do I encrypt using PKSC1 padding when I have the public key as a string already?
The more precise question is: What AsymmetricKeyParameter type should I be using?
Thanks in advance.
EDIT
I've found a workaround using the native RSACryptoServiceProvider here. Still, would be good to know how to do this with BC.
I am trying to read an RSA private key into .Net using BouncyCastle to test data I have previously encrypted. The encrypted data is working fine using the public key and Bouncy Castle and I have also used the same private key as below (which is DER format) to successfully decrypt my data in a PHP application but I don't know why I can't create the private key in .Net to do the same thing:
byte[] privatekey = File.ReadAllBytes(#"C:\Users\Luke\privkey.der");
var rsaKeyParameters = (RsaKeyParameters)PrivateKeyFactory.CreateKey(privatekey);
The second line throws an exception:
"unknown object in factory: DerInteger\r\nParameter name: obj"
I also tried using a stream instead of a byte array and the same error occurs. The key pair was created using OpenSSL and as mentioned, decryption works in PHP using openssl_private_decrypt() and the same key as in the .Net code. I also tried a PEM format of the same key and that also didn't work (but I don't think BC supports PEM directly anyway)
Has anyone done this before? Thanks
The problem was that I had assumed PublicKeyFactory and PrivateKeyFactory were complimentary since they are in the same namespace. They are not!
To decode the private key, I needed the following alternative code:
var privKeyObj = Asn1Object.FromStream(privatekey);
var privStruct = new RsaPrivateKeyStructure((Asn1Sequence)privKeyObj);
// Conversion from BouncyCastle to .Net framework types
var rsaParameters = new RSAParameters();
rsaParameters.Modulus = privStruct.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = privStruct.PublicExponent.ToByteArrayUnsigned();
rsaParameters.D = privStruct.PrivateExponent.ToByteArrayUnsigned();
rsaParameters.P = privStruct.Prime1.ToByteArrayUnsigned();
rsaParameters.Q = privStruct.Prime2.ToByteArrayUnsigned();
rsaParameters.DP = privStruct.Exponent1.ToByteArrayUnsigned();
rsaParameters.DQ = privStruct.Exponent2.ToByteArrayUnsigned();
rsaParameters.InverseQ = privStruct.Coefficient.ToByteArrayUnsigned();
var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
return Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(ciphertext), true));
A BIG thankyou to owlstead for their help.
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;
}