Bouncy Castle Sign and Verify SHA256 Certificate With C# - c#

I have been through a large number of examples of how people use Bouncy Castle to dynamically generate RSA Key Pairs and then sign and verify all within one block of code. Those answers were great and really helped me ramp up quickly!
That said, I need to create a client that can pass through WCF JSON calls a public key to be used later for signature verification and I cannot seem to get this to work. First here is the code I use to generate the Certificate:
public System.Security.Cryptography.X509Certificates.X509Certificate2 LoadCertificate()
{
System.Security.Cryptography.X509Certificates.X509Certificate2 returnX509 = null;
//X509Certificate returnCert = null;
try
{
returnX509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(CertificateName, CertificatePassword);
//returnCert = DotNetUtilities.FromX509Certificate(returnX509);
}
catch
{
Console.WriteLine("Failed to obtain cert - trying to make one now.");
try
{
Guid nameGuid = Guid.NewGuid();
AsymmetricCipherKeyPair kp;
var x509 = GenerateCertificate("CN=Server-CertA-" + nameGuid.ToString(), out kp);
SaveCertificateToFile(x509, kp, CertificateName, CertificateAlias, CertificatePassword);
returnX509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(CertificateName, CertificatePassword);
//returnCert = DotNetUtilities.FromX509Certificate(returnX509);
Console.WriteLine("Successfully wrote and retrieved cert!");
}
catch (Exception exc)
{
Console.WriteLine("Failed to create cert - exception was: " + exc.ToString());
}
}
return returnX509;
}
With that completed, I then use the following code to sign a message:
public string SignData(string Message, string PrivateKey)
{
try
{
byte[] orgBytes = UnicodeEncoding.ASCII.GetBytes(Message);
byte[] privateKey = UnicodeEncoding.ASCII.GetBytes(PrivateKey);
string curveName = "P-521";
X9ECParameters ecP = NistNamedCurves.GetByName(curveName);
ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
BigInteger biPrivateKey = new BigInteger(privateKey);
ECPrivateKeyParameters keyParameters = new ECPrivateKeyParameters(biPrivateKey, ecSpec);
signer.Init(true, keyParameters);
signer.BlockUpdate(orgBytes, 0, orgBytes.Length);
byte[] data = signer.GenerateSignature();
//Base64 Encode
byte[] encodedBytes;
using (MemoryStream encStream = new MemoryStream())
{
base64.Encode(orgBytes, 0, orgBytes.Length, encStream);
encodedBytes = encStream.ToArray();
}
if (encodedBytes.Length > 0)
return UnicodeEncoding.ASCII.GetString(encodedBytes);
else
return "";
}
catch (Exception exc)
{
Console.WriteLine("Signing Failed: " + exc.ToString());
return "";
}
}
And, finally, my attempt to verify:
public bool VerifySignature(string PublicKey, string Signature, string Message)
{
try
{
AsymmetricKeyParameter pubKey = new AsymmetricKeyParameter(false);
var publicKey = PublicKeyFactory.CreateKey(Convert.FromBase64String(PublicKey));
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
byte[] orgBytes = UnicodeEncoding.ASCII.GetBytes(Message);
signer.Init(false, publicKey);
signer.BlockUpdate(orgBytes, 0, orgBytes.Length);
//Base64 Decode
byte[] encodeBytes = UnicodeEncoding.ASCII.GetBytes(Signature);
byte[] decodeBytes;
using (MemoryStream decStream = new MemoryStream())
{
base64.Decode(encodeBytes, 0, encodeBytes.Length, decStream);
decodeBytes = decStream.ToArray();
}
return signer.VerifySignature(decodeBytes);
}
catch (Exception exc)
{
Console.WriteLine("Verification failed with the error: " + exc.ToString());
return false;
}
}
Here is my test app:
Console.WriteLine("Attempting to load cert...");
System.Security.Cryptography.X509Certificates.X509Certificate2 thisCert = LoadCertificate();
if (thisCert != null)
{
Console.WriteLine(thisCert.IssuerName.Name);
Console.WriteLine("Signing the text - Mary had a nuclear bomb");
string signature = SignData("Mary had a nuclear bomb", thisCert.PublicKey.Key.ToXmlString(true));
Console.WriteLine("Signature: " + signature);
Console.WriteLine("Verifying Signature");
if (VerifySignature(thisCert.PublicKey.Key.ToXmlString(false), signature, "Mary had a nuclear bomb."))
Console.WriteLine("Valid Signature!");
else
Console.WriteLine("Signature NOT valid!");
}
When I attempt to run the test app, I am getting the error "Key not valid for use in specified state." on the line:
string signature = SignData("Mary had a nuclear bomb", thisCert.PublicKey.Key.ToXmlString(true));
I tried replacing the "PublicKey.Key" with "PrivateKey" but that did not make a difference. I also tried using the BounceyCastle X509Certificate but I could not figure out how to extract the keys. Any ideas?
Thank you!
UPDATE: I did figure out how to sign and verify with just .NET but that is not really useful to me as I need to be cross platform and, in fact, our main client app is written in Java. Does anybody know the Bouncy Castle equivalent to the following code?
public string SignDataAsXml(string Message, X509Certificate2 ThisCert)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = false;
doc.LoadXml("<core>" + Message + "</core>");
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(doc);
// Add the key to the SignedXml document.
signedXml.SigningKey = ThisCert.PrivateKey;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Create a new KeyInfo object.
KeyInfo keyInfo = new KeyInfo();
// Load the certificate into a KeyInfoX509Data object
// and add it to the KeyInfo object.
keyInfo.AddClause(new KeyInfoX509Data(ThisCert));
// Add the KeyInfo object to the SignedXml object.
signedXml.KeyInfo = keyInfo;
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
if (doc.FirstChild is XmlDeclaration)
{
doc.RemoveChild(doc.FirstChild);
}
using (var stringWriter = new StringWriter())
{
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
doc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
return stringWriter.GetStringBuilder().ToString();
}
}
}
public bool VerifyXmlSignature(string XmlMessage, X509Certificate2 ThisCert)
{
// Create a new XML document.
XmlDocument xmlDocument = new XmlDocument();
// Load the passed XML file into the document.
xmlDocument.LoadXml(XmlMessage);
// Create a new SignedXml object and pass it the XML document class.
SignedXml signedXml = new SignedXml(xmlDocument);
// Find the "Signature" node and create a new XmlNodeList object.
XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");
// Load the signature node.
signedXml.LoadXml((XmlElement)nodeList[0]);
// Check the signature and return the result.
return signedXml.CheckSignature(ThisCert, true);
}

Bouncy Castle doesn't support XML formats at all. Unless your use-case strictly requires it, you'll find it much easier going just to use Base64 encodings, with certificates (X.509) and private keys (PKCS#8) stored in PEM format. These are all string formats, so should be usable with JSON directly.
There are other problems in the code samples: signing should use the private key, signatures shouldn't be treated as ASCII strings, possibly your messages are actually UTF8. I would expect the inner sign/verify routines to perhaps look like this:
public string SignData(string msg, ECPrivateKeyParameters privKey)
{
try
{
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
signer.Init(true, privKey);
signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
byte[] sigBytes = signer.GenerateSignature();
return Convert.ToBase64String(sigBytes);
}
catch (Exception exc)
{
Console.WriteLine("Signing Failed: " + exc.ToString());
return null;
}
}
public bool VerifySignature(ECPublicKeyParameters pubKey, string signature, string msg)
{
try
{
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
byte[] sigBytes = Convert.FromBase64String(signature);
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
signer.Init(false, pubKey);
signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
return signer.VerifySignature(sigBytes);
}
catch (Exception exc)
{
Console.WriteLine("Verification failed with the error: " + exc.ToString());
return false;
}
}
A further issue is that I think .NET didn't get ECDSA support until .NET 3.5, in any case there's no ECDsa class in .NET 1.1 (which is BC's target for the upcoming 1.8 release - we will be "modernising" after that), so DotNetUtilities doesn't have support for ECDSA. However, we can export to PKCS#12 and import to BC. An example program:
public void Program()
{
Console.WriteLine("Attempting to load cert...");
System.Security.Cryptography.X509Certificates.X509Certificate2 thisCert = LoadCertificate();
Console.WriteLine(thisCert.IssuerName.Name);
Console.WriteLine("Signing the text - Mary had a nuclear bomb");
byte[] pkcs12Bytes = thisCert.Export(X509ContentType.Pkcs12, "dummy");
Pkcs12Store pkcs12 = new Pkcs12StoreBuilder().Build();
pkcs12.Load(new MemoryStream(pkcs12Bytes, false), "dummy".ToCharArray());
ECPrivateKeyParameters privKey = null;
foreach (string alias in pkcs12.Aliases)
{
if (pkcs12.IsKeyEntry(alias))
{
privKey = (ECPrivateKeyParameters)pkcs12.GetKey(alias).Key;
break;
}
}
string signature = SignData("Mary had a nuclear bomb", privKey);
Console.WriteLine("Signature: " + signature);
Console.WriteLine("Verifying Signature");
var bcCert = DotNetUtilities.FromX509Certificate(thisCert);
if (VerifySignature((ECPublicKeyParameters)bcCert.GetPublicKey(), signature, "Mary had a nuclear bomb."))
Console.WriteLine("Valid Signature!");
else
Console.WriteLine("Signature NOT valid!");
}
I haven't really tested any of the above code, but it should give you something to go on. Note that BC has key and certificate generators too, so you could choose to use BC for everything (except XML!), and export/import to/from .NET land only where necessary.

Thanks to Petters answer I wanted to add code to verify the signature with RSA algorithm.
public bool VerifySignature(AsymmetricKeyParameter pubKey, string signature, string msg)
{
try
{
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
byte[] sigBytes = Convert.FromBase64String(signature);
ISigner signer = SignerUtilities.GetSigner("SHA-256withRSA");
signer.Init(false, pubKey);
signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
return signer.VerifySignature(sigBytes);
}
catch (Exception exc)
{
Console.WriteLine("Verification failed with the error: " + exc.ToString());
return false;
}
}

Related

Decrypt a pdf file using bouncy castle using 3des algorithm

i need to decrypt a pdf file using bouncy castle libreries.
I use c#.
I can encrypt a pdf file using the following code:
public static byte[] CmsEncrypt3DES(string InFilePath, string CertFilePath)
{
byte[] encoded;
try
{
byte[] numArray = File.ReadAllBytes(InFilePath);
X509Certificate x509Certificate =ESCmsEncrypt.LoadCertificate(CertFilePath);
CmsEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CmsEnvelopedDataGenerator();
CmsProcessableByteArray cmsProcessableByteArray = new CmsProcessableByteArray(numArray);
cmsEnvelopedDataGenerator.AddKeyTransRecipient(x509Certificate);
encoded = cmsEnvelopedDataGenerator.Generate(cmsProcessableByteArray, PkcsObjectIdentifiers.DesEde3Cbc.Id).GetEncoded();
}
catch (Exception exception1)
{
Exception exception = exception1;
throw exception;
}
return encoded;
}
I import the certificate using this method:
public static X509Certificate LoadCertificate(string filename)
{
X509Certificate x509Certificate;
try
{
X509CertificateParser x509CertificateParser = new X509CertificateParser();
FileStream fileStream = new FileStream(filename, FileMode.Open);
X509Certificate x509Certificate1 = x509CertificateParser.ReadCertificate(fileStream);
fileStream.Close();
x509Certificate = x509Certificate1;
}
catch (Exception exception1)
{
Exception exception = exception1;
Log.LogError("ESCmsEncrypt.LoadCertificate", exception.Message, exception.ToString());
throw exception;
}
return x509Certificate;
}
This code work well but i' don't know how to decrypt this file using bouncy castle.
I've tried but without results.
Thanks
Valerio M.
EDIT
i've also used this code but it doesn't work:
public static void test()
{
X509Certificate2Collection scollection = new X509Certificate2Collection();
// Output which certificate will be used
Console.WriteLine("Using Certificate:");
string path_certificato = ConfigurationManager.AppSettings["certificate_file"].ToString();
X509Certificate2 cert = new X509Certificate2();
X509Certificate2 x509 = new X509Certificate2(File.ReadAllBytes(path_certificato));
Console.WriteLine("---------------------------------------------------------------------");
Console.WriteLine("1.\tFull DN: {0}", x509.Subject);
Console.WriteLine("\tThumbprint: {0}", x509.Thumbprint);
Console.WriteLine("---------------------------------------------------------------------");
cert = x509;
scollection.Add(cert);
// Wait
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
// Create data for encryption
string message = "THIS IS OUR SECRET MESSAGE";
byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Encrypt
Console.WriteLine("Encrypting message...");
//ContentInfo contentInfo = new ContentInfo(data); // will use default ContentInfo Oid, which is "DATA"
// Explicitly use ContentInfo Oid 1.2.840.113549.1.7.1, "DATA", which is the default.
ContentInfo contentInfo = new ContentInfo(new System.Security.Cryptography.Oid("1.2.840.113549.1.7.1"), data);
// If using OID 1.2.840.113549.3.7 (the default one used if empty constructor is used) or 1.2.840.113549.1.9.16.3.6 everything works
// If using OID 2.16.840.1.101.3.4.1.42 (AES CBC) it breaks
AlgorithmIdentifier encryptionAlgorithm = new AlgorithmIdentifier(new System.Security.Cryptography.Oid("1.2.840.113549.3.7"));
EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo); // this will use default encryption algorithm (3DES)
//EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo, encryptionAlgorithm);
Console.WriteLine("Encyption Algorithm:" + envelopedCms.ContentEncryptionAlgorithm.Oid.FriendlyName);
Console.WriteLine("Encyption Algorithm:" + envelopedCms.ContentEncryptionAlgorithm.Oid.Value);
CmsRecipientCollection recipients = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, scollection);
/*Console.WriteLine("Receipientinfo count: " + encryptionEnvelopedCms.RecipientInfos.Count.ToString());
foreach (var i in encryptionEnvelopedCms.RecipientInfos)
{
Console.Write("RecipientInfo Encryption Oid: " + i.KeyEncryptionAlgorithm.Oid);
}
*/
envelopedCms.Encrypt(recipients);
byte[] encryptedData = envelopedCms.Encode();
Console.WriteLine("Message encrypted!");
EnvelopedCms envelopedCms_new = new EnvelopedCms();
envelopedCms_new.Decode(encryptedData);
envelopedCms_new.Decrypt(scollection);
byte[] decryptedData = envelopedCms_new.ContentInfo.Content;
}
"envelopedCms_new.Decode(encryptedData);"this part doesn't work
System.Security.Cryptography.CryptographicException: 'Impossibile trovare la proprietĂ  o l'oggetto.

How to generate .sig of XML of digitally signed XML document in C#?

I have requirement of signing xml document with digital signature and with that document I need to generate .sig file of digitally signed xml. I am using PKCS7 Algorithm for the same. I am able to successfully put signature in xml. But not been able to generate .sig file. My code is as follows:
public static void SignXmlDocumentWithCertificate(XmlDocument doc, X509Certificate2 cert)
{
SignedXml signedxml = new SignedXml(doc);
signedxml.SigningKey = cert.PrivateKey;
Reference reference = new Reference();
reference.Uri = "";
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
signedxml.AddReference(reference);
KeyInfo keyinfo = new KeyInfo();
keyinfo.AddClause(new KeyInfoX509Data(cert));
signedxml.KeyInfo = keyinfo;
signedxml.ComputeSignature();
XmlElement xmlsig = signedxml.GetXml();
doc.DocumentElement.AppendChild(doc.ImportNode(xmlsig, true));
//Console.WriteLine(doc.ImportNode(xmlsig,true));
}
Now I am generating .sig file like this:
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsaParameters);
byte[] ciphertext = rsa.Encrypt(keyBytes, false);
string cipherresult = Convert.ToBase64String(ciphertext);
Console.WriteLine(cipherresult);
which is throwing an error of bad length \r\n.
My xml after digitally signed is :
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<CATALOG>
<PLANT>
<COMMON>Grecian Windflower</COMMON>
<BOTANICAL>Anemone blanda</BOTANICAL>
<ZONE>6</ZONE>
<LIGHT>Mostly Shady</LIGHT>
<PRICE>$9.16</PRICE>
<AVAILABILITY>071099</AVAILABILITY>
</PLANT>
</CATALOG>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>/VUzr4wRNv2e6SzE6TdHLM8c+/A=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>i3gGf2Q......8Q==</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>MIID6D.......fFo=</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</xml>
Now I know I am either doing in wrong way or there is something I have missed out. My question is
Is there a way out for generating .sig file with signed xml?
Is it possible for large xml file in PKCS7?
As my requriement are:
The digital signature will be generated as a part of PKCS7 envelop as a plain bytes. A PKCS7 envelop will contain the certificate used for signing as well as the digital signature itself.
The PKCS7 envelop will not be base-64 encoded. It will not contain any start aend identifiers. The plain PKCS7 envelop which is a sequence of bytes will be written into the .sig file.
The digital signature will be generated using SHA-2(512bits) algorithm for message digest and RSA-2048 algorithm for encryption
Try following code. I merged your code with sample from msdn. I also used default user certificate on PC :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load(FILENAME);
string computerName = Environment.GetEnvironmentVariable("COMPUTERNAME");
string userName = Environment.GetEnvironmentVariable("USERNAME");
X509Certificate2 cert = GetCertificateFromStore("CN=" + computerName + "\\" + userName);
SignXmlDocumentWithCertificate(doc, cert);
RSACryptoServiceProvider publicKey = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] unencryptedData = Encoding.UTF8.GetBytes(doc.OuterXml);
Stream stream = EncryptFile(unencryptedData,publicKey);
Console.ReadLine();
}
public static void SignXmlDocumentWithCertificate(XmlDocument doc, X509Certificate2 cert)
{
SignedXml signedxml = new SignedXml(doc);
signedxml.SigningKey = cert.PrivateKey;
Reference reference = new Reference();
reference.Uri = "";
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
signedxml.AddReference(reference);
KeyInfo keyinfo = new KeyInfo();
keyinfo.AddClause(new KeyInfoX509Data(cert));
signedxml.KeyInfo = keyinfo;
signedxml.ComputeSignature();
XmlElement xmlsig = signedxml.GetXml();
doc.DocumentElement.AppendChild(doc.ImportNode(xmlsig, true));
//Console.WriteLine(doc.ImportNode(xmlsig,true));
}
private static X509Certificate2 GetCertificateFromStore(string certName)
{
// Get the certificate store for the current user.
X509Store store = new X509Store(StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
// Place all certificates in an X509Certificate2Collection object.
X509Certificate2Collection certCollection = store.Certificates;
// If using a certificate with a trusted root you do not need to FindByTimeValid, instead:
// currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, true);
X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false);
if (signingCert.Count == 0)
return null;
// Return the first certificate in the collection, has the right name and is current.
return signingCert[0];
}
finally
{
store.Close();
}
}
// Encrypt a file using a public key.
private static MemoryStream EncryptFile(byte[] unencryptedData, RSACryptoServiceProvider rsaPublicKey)
{
MemoryStream stream = null;
using (AesManaged aesManaged = new AesManaged())
{
// Create instance of AesManaged for
// symetric encryption of the data.
aesManaged.KeySize = 256;
aesManaged.BlockSize = 128;
aesManaged.Mode = CipherMode.CBC;
using (ICryptoTransform transform = aesManaged.CreateEncryptor())
{
RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey);
byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType());
// Create byte arrays to contain
// the length values of the key and IV.
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
int lKey = keyEncrypted.Length;
LenK = BitConverter.GetBytes(lKey);
int lIV = aesManaged.IV.Length;
LenIV = BitConverter.GetBytes(lIV);
// Write the following to the FileStream
// for the encrypted file (outFs):
// - length of the key
// - length of the IV
// - ecrypted key
// - the IV
// - the encrypted cipher content
stream = new MemoryStream();
try
{
stream.Write(LenK, 0, 4);
stream.Write(LenIV, 0, 4);
stream.Write(keyEncrypted, 0, lKey);
stream.Write(aesManaged.IV, 0, lIV);
// Now write the cipher text using
// a CryptoStream for encrypting.
CryptoStream outStreamEncrypted = new CryptoStream(stream, transform, CryptoStreamMode.Write);
try
{
// By encrypting a chunk at
// a time, you can save memory
// and accommodate large files.
int count = 0;
int offset = 0;
// blockSizeBytes can be any arbitrary size.
int blockSizeBytes = aesManaged.BlockSize / 8;
do
{
if (offset + blockSizeBytes <= unencryptedData.Length)
{
count = blockSizeBytes;
}
else
{
count = unencryptedData.Length - offset;
}
outStreamEncrypted.Write(unencryptedData, offset, count);
offset += count;
}
while (offset < unencryptedData.Length);
outStreamEncrypted.FlushFinalBlock();
}
catch(Exception ex)
{
Console.WriteLine("Error : {0}", ex.Message);
}
}
catch(Exception ex)
{
Console.WriteLine("Error : {0}", ex.Message);
}
stream.Position = 0;
}
}
return stream;
}
}
}

Encoding problems signing a xml document due to special characters

Signing an xml document using c# I continuously have signature verification issues because of the special characters, in concrete this one 'Âș' commonly used for addresses in Spain.
The encoding for this xml file is "ISO-8859-1", however if I use UTF-8 it works fine.
The method I use for signing is this one:
public static string SignXml(XmlDocument Document, X509Certificate2 cert)
{
SignedXml signedXml = new SignedXml(Document);
signedXml.SigningKey = cert.PrivateKey;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env =
new XmlDsigEnvelopedSignatureTransform(true);
reference.AddTransform(env);
XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
reference.AddTransform(c14t);
KeyInfo keyInfo = new KeyInfo();
KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);
keyInfo.AddClause(keyInfoData);
signedXml.KeyInfo = keyInfo;
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
Document.DocumentElement.AppendChild(
Document.ImportNode(xmlDigitalSignature, true));
return Document.OuterXml;
}
Taken from: http://www.wiktorzychla.com/2012/12/interoperable-xml-digital-signatures-c_20.html
And this is how I call it:
static void Main(string[] args)
{
string path = ".\\DATOS\\Ejemplo.xml";
string signedDocString = null;
XmlDocument entrada = new XmlDocument();
entrada.Load(path);
X509Certificate2 myCert = null;
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates;
foreach (var certificate in certificates)
{
if (certificate.Subject.Contains("XXXX"))
{
Console.WriteLine(certificate.Subject);
myCert = certificate;
break;
}
}
if (myCert != null)
{
signedDocString = SignXml(entrada, myCert);
}
if (VerifyXml(signedDocString))
{
Console.WriteLine("VALIDO");
}
else
{
Console.WriteLine("NO VALIDO");
}
Console.ReadLine();
}
The xml document must use the encoding ISO-8859-1, this is not optional. And I cannot suppress the special characters.
Any suggestion about how to handle this?
my fault.
In the verification method I was using utf8:
public bool VerifyXml( string SignedXmlDocumentString )
{
byte[] stringData = Encoding.UTF8.GetBytes( SignedXmlDocumentString );
using ( MemoryStream ms = new MemoryStream( stringData ) )
return VerifyXmlFromStream( ms );
}
In that step I was altering the encoding and so the document content wasn't the same as the original one. Quite newbie error.
The solution:
public static bool VerifyXml(XmlDocument SignedXmlDocument)
{
byte[] stringData = Encoding.Default.GetBytes(SignedXmlDocument.OuterXml);
using (MemoryStream ms = new MemoryStream(stringData))
return VerifyXmlFromStream(ms);
}

Read RSA PrivateKey in C# and Bouncy Castle

I have successfully written to public and private key files with OpenSSL format.
Files:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpHCHYgawzNlxVebSKXL7vfc/i
hP+dQgMxlaPEi7/vpQtV2szHjIP34MnUKelXFuIETJjOgjWAjTTJoj38MQUWc3u7
SRXaGVggqQEKH+cRi5+UcEObIfpi+cIyAm9MJqKabfJK2e5X/OS7FgAwPjgtDbZO
ZxamOrWWL8KGB+lH+QIDAQAB
-----END PUBLIC KEY-----
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCpHCHYgawzNlxVebSKXL7vfc/ihP+dQgMxlaPEi7/vpQtV2szH
jIP34MnUKelXFuIETJjOgjWAjTTJoj38MQUWc3u7SRXaGVggqQEKH+cRi5+UcEOb
Ifpi+cIyAm9MJqKabfJK2e5X/OS7FgAwPjgtDbZOZxamOrWWL8KGB+lH+QIDAQAB
AoGBAIXtL6jFWVjdjlZrIl4JgXUtkDt21PD33IuiVKZNft4NOWLu+wp17/WZYn3S
C2fbSXfaKZIycKi0K8Ab6zcUo0+QZKMoaG5GivnqqTPVAuZchkuMUSVgjGvKAC/D
12/b+w+Shs9pvqED1CxfvtePXNwL6ZNuaREFC5hF/YpMVyg5AkEA3BUCZYJ+Ec96
2cwsdY6HocW8Kn+RIqMjkNtyLA19cQV5mpIP7kAiW6drBDlraVANi+5AgK2zQ+ZT
hYzs/JfRKwJBAMS1g5/B7XXnfC6VTRs8AMveZudi5wS/aGpaApybsfx1NTLLsm3l
GmGTkbCr+EPzvJ5zRSIAHAA6N6NdORwzEWsCQHTli+JTD5dyNvScaDkAvbYFi06f
d32IXYnBpcEUYT65A8BAOMn5ssYwBL23qf/ED431vLkcig1Ut6RGGFKKaQUCQEfa
UdkSWm39/5N4f/DZyySs+YO90csfK8HlXRzdlnc0TRlf5K5VyHwqDkatmoMfzh9G
1dLknVXL7jTjQZA2az8CQG0jRSQ599zllylMPPVibW98701Mdhb1u20p1fAOkIrz
+BNEdOPqPVIyqIP830nnFsJJgTG2eKB59ym+ypffRmA=
-----END RSA PRIVATE KEY-----
And public key contains just the public key portion of course.
After encrypting my message using the public key. I want to read the private key file
and decrypt it but it's not working. I'm getting exceptions trying to read the private key saying can't cast object to asymmetriccipherkey.
Here is my code:
public static AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
var fileStream = System.IO.File.OpenText(pemFilename);
var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
return KeyParameter;
}
static void Encrypt2(string publicKeyFileName, string inputMessage, string encryptedFileName)
{
UTF8Encoding utf8enc = new UTF8Encoding();
FileStream encryptedFile = null;
try
{
// Converting the string message to byte array
byte[] inputBytes = utf8enc.GetBytes(inputMessage);
// RSAKeyPairGenerator generates the RSA Key pair based on the random number and strength of key required
/*RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();
*/
AsymmetricKeyParameter publicKey = ReadAsymmetricKeyParameter(publicKeyFileName);
// Creating the RSA algorithm object
IAsymmetricBlockCipher cipher = new RsaEngine();
// Initializing the RSA object for Encryption with RSA public key. Remember, for encryption, public key is needed
cipher.Init(true, publicKey);
//Encrypting the input bytes
byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);
//Write the encrypted message to file
// Write encrypted text to file
encryptedFile = File.Create(encryptedFileName);
encryptedFile.Write(cipheredBytes, 0, cipheredBytes.Length);
}
catch (Exception ex)
{
// Any errors? Show them
Console.WriteLine("Exception encrypting file! More info:");
Console.WriteLine(ex.Message);
}
finally
{
// Do some clean up if needed
if (encryptedFile != null)
{
encryptedFile.Close();
}
}
}
Here is the decrypt function. 2nd one is without using Bouncy Castle, however, I'd rather use Bouncy Castle since later I'll be also encrypting and decrypting in Java.
static void Decrypt2(string privateKeyFileName, string encryptedFileName, string plainTextFileName)
{
UTF8Encoding utf8enc = new UTF8Encoding();
FileStream encryptedFile = null;
StreamWriter plainFile = null;
byte[] encryptedBytes = null;
string plainText = "";
try
{
// Converting the string message to byte array
//byte[] inputBytes = utf8enc.GetBytes(inputMessage);
// RSAKeyPairGenerator generates the RSA Key pair based on the random number and strength of key required
/*RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();
*/
StreamReader sr = File.OpenText(privateKeyFileName);
PemReader pr = new PemReader(sr);
PemReader pemReader = new PemReader(new StringReader(privateKeyFileName));
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
Console.WriteLine(keyPair.ToString());
AsymmetricKeyParameter privatekey = keyPair.Private;
Console.WriteLine(pr.ReadPemObject());
AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
AsymmetricKeyParameter privateKey = ReadAsymmetricKeyParameter(privateKeyFileName);
// Creating the RSA algorithm object
IAsymmetricBlockCipher cipher = new RsaEngine();
Console.WriteLine("privateKey: " + privateKey.ToString());
// Initializing the RSA object for Decryption with RSA private key. Remember, for decryption, private key is needed
//cipher.Init(false, KeyPair.Private);
//cipher.Init(false, KeyPair.Private);
cipher.Init(false, keyPair.Private);
// Read encrypted text from file
encryptedFile = File.OpenRead(encryptedFileName);
encryptedBytes = new byte[encryptedFile.Length];
encryptedFile.Read(encryptedBytes, 0, (int)encryptedFile.Length);
//Encrypting the input bytes
//byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);
byte[] cipheredBytes = cipher.ProcessBlock(encryptedBytes, 0, encryptedBytes.Length);
//Write the encrypted message to file
// Write encrypted text to file
plainFile = File.CreateText(plainTextFileName);
plainText = Encoding.Unicode.GetString(cipheredBytes);
plainFile.Write(plainText);
}
catch (Exception ex)
{
// Any errors? Show them
Console.WriteLine("Exception encrypting file! More info:");
Console.WriteLine(ex.Message);
}
finally
{
// Do some clean up if needed
if (plainFile != null)
{
plainFile.Close();
}
if (encryptedFile != null)
{
encryptedFile.Close();
}
}
}
// Decrypt a file
static void Decrypt(string privateKeyFileName, string encryptedFileName, string plainFileName)
{
// Variables
CspParameters cspParams = null;
RSACryptoServiceProvider rsaProvider = null;
StreamReader privateKeyFile = null;
FileStream encryptedFile = null;
StreamWriter plainFile = null;
string privateKeyText = "";
string plainText = "";
byte[] encryptedBytes = null;
byte[] plainBytes = null;
try
{
// Select target CSP
cspParams = new CspParameters();
cspParams.ProviderType = 1; // PROV_RSA_FULL
//cspParams.ProviderName; // CSP name
rsaProvider = new RSACryptoServiceProvider(cspParams);
// Read private/public key pair from file
privateKeyFile = File.OpenText(privateKeyFileName);
privateKeyText = privateKeyFile.ReadToEnd();
// Import private/public key pair
rsaProvider.FromXmlString(privateKeyText);
// Read encrypted text from file
encryptedFile = File.OpenRead(encryptedFileName);
encryptedBytes = new byte[encryptedFile.Length];
encryptedFile.Read(encryptedBytes, 0, (int)encryptedFile.Length);
// Decrypt text
plainBytes = rsaProvider.Decrypt(encryptedBytes, false);
// Write decrypted text to file
plainFile = File.CreateText(plainFileName);
plainText = Encoding.Unicode.GetString(plainBytes);
plainFile.Write(plainText);
}
catch (Exception ex)
{
// Any errors? Show them
Console.WriteLine("Exception decrypting file! More info:");
Console.WriteLine(ex.Message);
}
finally
{
// Do some clean up if needed
if (privateKeyFile != null)
{
privateKeyFile.Close();
}
if (encryptedFile != null)
{
encryptedFile.Close();
}
if (plainFile != null)
{
plainFile.Close();
}
}
} // Decrypt
I figured this out. Basically to read a private openssl key using BouncyCastle and C# is like this:
static AsymmetricKeyParameter readPrivateKey(string privateKeyFileName)
{
AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(privateKeyFileName))
keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
return keyPair.Private;
}
Then this key can be used to decrypt data such as below:
AsymmetricKeyParameter key = readPrivateKey(pemFilename);
RsaEngine e = new RsaEngine();
e.Init(false, key);
byte[] decipheredBytes = e.ProcessBlock(cipheredData, 0, cipheredData.Length);

Signing and verifying signatures with RSA C#

I recently posted about issues with encrypting large data with RSA, I am finally done with that and now I am moving on to implementing signing with a user's private key and verifying with the corresponding public key. However, whenever I compare the signed data and the original message I basically just get false returned. I am hoping some of your could see what I am doing wrong.
Here is the code:
public static string SignData(string message, RSAParameters privateKey)
{
//// The array to store the signed message in bytes
byte[] signedBytes;
using (var rsa = new RSACryptoServiceProvider())
{
//// Write the message to a byte array using UTF8 as the encoding.
var encoder = new UTF8Encoding();
byte[] originalData = encoder.GetBytes(message);
try
{
//// Import the private key used for signing the message
rsa.ImportParameters(privateKey);
//// Sign the data, using SHA512 as the hashing algorithm
signedBytes = rsa.SignData(originalData, CryptoConfig.MapNameToOID("SHA512"));
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
//// Set the keycontainer to be cleared when rsa is garbage collected.
rsa.PersistKeyInCsp = false;
}
}
//// Convert the a base64 string before returning
return Convert.ToBase64String(signedBytes);
}
So that is the first step, to sign the data, next I move on to verifying the data:
public static bool VerifyData(string originalMessage, string signedMessage, RSAParameters publicKey)
{
bool success = false;
using (var rsa = new RSACryptoServiceProvider())
{
byte[] bytesToVerify = Convert.FromBase64String(originalMessage);
byte[] signedBytes = Convert.FromBase64String(signedMessage);
try
{
rsa.ImportParameters(publicKey);
SHA512Managed Hash = new SHA512Managed();
byte[] hashedData = Hash.ComputeHash(signedBytes);
success = rsa.VerifyData(bytesToVerify, CryptoConfig.MapNameToOID("SHA512"), signedBytes);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
return success;
}
And here is the test client:
public static void Main(string[] args)
{
PublicKeyInfrastructure pki = new PublicKeyInfrastructure();
Cryptograph crypto = new Cryptograph();
RSAParameters privateKey = crypto.GenerateKeys("email#email.com");
const string PlainText = "This is really sent by me, really!";
RSAParameters publicKey = crypto.GetPublicKey("email#email.com");
string encryptedText = Cryptograph.Encrypt(PlainText, publicKey);
Console.WriteLine("This is the encrypted Text:" + "\n " + encryptedText);
string decryptedText = Cryptograph.Decrypt(encryptedText, privateKey);
Console.WriteLine("This is the decrypted text: " + decryptedText);
string messageToSign = encryptedText;
string signedMessage = Cryptograph.SignData(messageToSign, privateKey);
//// Is this message really, really, REALLY sent by me?
bool success = Cryptograph.VerifyData(messageToSign, signedMessage, publicKey);
Console.WriteLine("Is this message really, really, REALLY sent by me? " + success);
}
Am I missing a step here? According to the Cryptography API and the examples there, I shouldn't manually compute any hashes, since I supply the algorithm within the method call itself.
Any help will be greatly appreciated.
Your problem is at the beginning of the VerifyData method:
public static bool VerifyData(string originalMessage, string signedMessage, RSAParameters publicKey)
{
bool success = false;
using (var rsa = new RSACryptoServiceProvider())
{
//Don't do this, do the same as you did in SignData:
//byte[] bytesToVerify = Convert.FromBase64String(originalMessage);
var encoder = new UTF8Encoding();
byte[] bytesToVerify = encoder.GetBytes(originalMessage);
byte[] signedBytes = Convert.FromBase64String(signedMessage);
try
...
For some reason you switched to FromBase64String instead of UTF8Encoding.GetBytes.

Categories

Resources