RSA using bouncy castle with key stored in CSP blog - c#

I have a private key in a csp format. I need migrate to Bouncy Castle. But I don't find any function to import this format.
Please, can you help me to traslate this code?
using (RSACryptoServiceProvider privatekey = new RSACryptoServiceProvider()) {
privatekey.ImportCspBlob("chave em csp");
Byte[] buffer = Encoding.GetEncoding("utf-8").GetBytes(textEdit1.Text);
Byte[] signature = privatekey.SignData(buffer, "SHA1");
return Convert.ToBase64String(signature);
}
Thanks

You can start with this: C# Sign Data with RSA using BouncyCastle, it tells how to sign using Bouncy Castle, to import the key to Bouncy Castle, you need to look at the DotNetUtilities class on Org.BouncyCastle.Security namespace.

Related

Update x509Certificate2 with correct Cryptographic Service Provider in Bouncy Castle

I am creating x509Certificate2 using CertificateGenerator.GenerateCertificate from this blog post of Wiktor Zychla (http://www.wiktorzychla.com/2012/12/how-to-create-x509certificate2.html)
Bouncy Castle crypto library is used to generate the certificate file. I need stronger signature algorithm to be used, so instead of SHA1withRSA (one in example) I am using SHA256withRSA.
Certificate is generated and exported successfully to .pfx file. When using the certificate later on I get error Invalid algorithm specified.
When run certutil -dump mycert.pfx, I see incorrect Cryptographic Service Provider (CSP) is set: Microsoft Base Cryptographic Provider v1.0
...
---------------- End Nesting Level 1 ----------------
Provider = Microsoft Base Cryptographic Provider v1.0
...
How can I tell Bouncy Castle API to use different CSP? The Microsoft Enhanced RSA and AES Cryptographic Provider, that actually can deal with SHA256withRSA.
There is very little resources on Bouncy Castle and C#, so any link to some documentation or related examples would be greatly appreciated.
List of CryptoAPI CSPs and algorithms, they support:
https://msdn.microsoft.com/en-us/library/windows/desktop/bb931357(v=vs.85).aspx
The easiest way is to specify the CSP when you are importing the generated pfx. You can use this command
certutil -importPFX -csp "Microsoft Enhanced RSA and AES Cryptographic Provider" -v c:\yourpfx.pfx AT_KEYEXCHANGE,NoExport,NoProtect
which will
import into LocalMachine\My
set CSP to Microsoft Enhanced RSA and AES Cryptographic Provider
set private key usage to Exchange
set private key as non-exportable
set private key with no additional (password) protection
The CSP is windows specific field in PKCS#12 (PFX) and no one except windows is setting this. If you are using PFX from file new X509Certificate2(filename) then you have to change the private key. Convert PrivateKey property to RSACryptoServiceProvider and modify CspParameters (I don't have a snippet right now). Then set the modified RSACryptoServiceProvider back to PrivateKey property.
------- Edit
Here is the sample code that changes CSP on PFX read from file
// need to set exportable flag to be able to ... export private key
X509Certificate2 cert = new X509Certificate2(#"d:\test.pfx", "a", X509KeyStorageFlags.Exportable);
var privKey = cert.PrivateKey as RSACryptoServiceProvider;
// will be needed later
var exported = privKey.ToXmlString(true);
// change CSP
var cspParams = new CspParameters()
{
ProviderType = 24,
ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider"
};
// create new PrivateKey from CspParameters and exported privkey
var newPrivKey = new RSACryptoServiceProvider(cspParams);
newPrivKey.FromXmlString(exported);
// Assign edited private key back
cert.PrivateKey = newPrivKey;
// export as PKCS#12/PFX
var bytes = cert.Export(X509ContentType.Pfx, "a");

Digital signature using bouncy castle and certificate private key

I am developing a feature to digital sign some content. I have valid certificate with a private key. How to digital sign using the private key and bouncy castle?
I tried the following but want some right way to achieve the same using bouncy castle:
X509Certificate2 signingCert =
CryptoHelper.FindCertificate("21A6107EC254457AAF3D4D6FD286FB79");
var rsaObj = (RSACryptoServiceProvider)signingCert.PrivateKey;
_privateKey = rsaObj.ExportParameters(true);
Thanks!
I donĀ“t know exactly what you need based on your code, but there X509 namespace/code is at
bcgit/bc-csharp - X509 and there is an utility class for conversion between System.Security.Cryptography and BouncyCastle
bcgit/bc-csharp - DotNetUtilities.cs
BouncyCastle got lots of test (and examples). Have a look at bcgit/bc-csharp - TestCertificateGen.cs too. Maybe this helps you.
EDIT: In general it should go something like this
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
// Your loaded certificate
X509Certificate cert = null;
// Your loaded RSA key
AsymmetricKeyParameter privateKey = null;
AsymmetricKeyParameter publicKey = cert.GetPublicKey();
ISigner signer = SignerUtilities.GetSigner(cert.SigAlgName);
// Init for signing, you pass in the private key
signer.Init(true, privateKey);
// Init for verification, you pass in the public key
signer.Init(false, publicKey);
Greetings

How to use GnuPG (Libgcrypt) generated keys with RSACryptoServiceProvider?

Is it possible to use PGP keys in .NET's RSA?
I tried this code, without success.
X509Certificate2 certificate = new X509Certificate2();
certificate.Import("C:\\All Public Keys.asc");
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;
How to load this key?

How can I add a private key to X509Certificate2 after I have already added the public key?

My steps are:
Create X509Certificate2 with public key:
X509Certificate2 clientCertificate = new X509Certificate2("public key certificate blob as byte[]");
How do I want to load the private key blob to clientCertificate?
It looks like you can not import RSA private key with just .net framework tools.
Check out this thread How to read a PEM RSA private key from .NET.
Just in case anyone like me and up looking at this old post when searching for how to generate X509Certificate2 from pem fil/private key:
The .Net 5.0 framework has a very simplified approach to this:
var certPem = File.ReadAllText("cert.pem");
var eccPem = File.ReadAllText("ecc.pem");
var cert = X509Certificate2.CreateFromPem(certPem, eccPem);
(source: https://www.scottbrady91.com/C-Sharp/PEM-Loading-in-dotnet-core-and-dotnet)
Also see: How to import PKCS#8 RSA privateKey (created by OpenSSL) in C#
It includes a link to Mono's source code which can read PKCS#8 / PEM files and return an RSA instance from it.

BouncyCastle create AsymmetricCipherKeyPair from existing keys?

I have two AssymetricAlgorithm RSA keys that I have pulled out of a certificate that was in my keystore. One is the Public Key and the other the Private. Is there a way of getting this keypair into a BouncyCastle AsymmetricCipherKeyPair? BouncyCastle's AsymmetricCipherKeyPair expects a public and private AsymmetricKeyParameter however I have no way of getting my Private key without it being an instance of AssymetricAlgorithm.
The answer to this lies here:
Get Private Key from BouncyCastle X509 Certificate? C#
I think this will help if key is marked as exportable
RSACryptoServiceProvider key = (RSACryptoServiceProvider)X509Certificate2object.PrivateKey;
RSAParameters rsaparam = key.ExportParameters(true);
AsymmetricCipherKeyPair keypair = DotNetUtilities.GetRsaKeyPair(rsaparam);

Categories